Recalculate normals for cached meshes.
[oweals/minetest.git] / src / nodedef.cpp
1 /*
2 Minetest
3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "nodedef.h"
21
22 #include "main.h" // For g_settings
23 #include "itemdef.h"
24 #ifndef SERVER
25 #include "tile.h"
26 #include "mesh.h"
27 #include <IMeshManipulator.h>
28 #endif
29 #include "log.h"
30 #include "settings.h"
31 #include "nameidmapping.h"
32 #include "util/numeric.h"
33 #include "util/serialize.h"
34 #include "exceptions.h"
35 #include "debug.h"
36 #include "gamedef.h"
37
38 /*
39         NodeBox
40 */
41
42 void NodeBox::reset()
43 {
44         type = NODEBOX_REGULAR;
45         // default is empty
46         fixed.clear();
47         // default is sign/ladder-like
48         wall_top = aabb3f(-BS/2, BS/2-BS/16., -BS/2, BS/2, BS/2, BS/2);
49         wall_bottom = aabb3f(-BS/2, -BS/2, -BS/2, BS/2, -BS/2+BS/16., BS/2);
50         wall_side = aabb3f(-BS/2, -BS/2, -BS/2, -BS/2+BS/16., BS/2, BS/2);
51 }
52
53 void NodeBox::serialize(std::ostream &os, u16 protocol_version) const
54 {
55         int version = protocol_version >= 21 ? 2 : 1;
56         writeU8(os, version);
57
58         if (version == 1 && type == NODEBOX_LEVELED)
59                 writeU8(os, NODEBOX_FIXED);
60         else
61                 writeU8(os, type);
62
63         if(type == NODEBOX_FIXED || type == NODEBOX_LEVELED)
64         {
65                 writeU16(os, fixed.size());
66                 for(std::vector<aabb3f>::const_iterator
67                                 i = fixed.begin();
68                                 i != fixed.end(); i++)
69                 {
70                         writeV3F1000(os, i->MinEdge);
71                         writeV3F1000(os, i->MaxEdge);
72                 }
73         }
74         else if(type == NODEBOX_WALLMOUNTED)
75         {
76                 writeV3F1000(os, wall_top.MinEdge);
77                 writeV3F1000(os, wall_top.MaxEdge);
78                 writeV3F1000(os, wall_bottom.MinEdge);
79                 writeV3F1000(os, wall_bottom.MaxEdge);
80                 writeV3F1000(os, wall_side.MinEdge);
81                 writeV3F1000(os, wall_side.MaxEdge);
82         }
83 }
84
85 void NodeBox::deSerialize(std::istream &is)
86 {
87         int version = readU8(is);
88         if(version < 1 || version > 2)
89                 throw SerializationError("unsupported NodeBox version");
90
91         reset();
92
93         type = (enum NodeBoxType)readU8(is);
94
95         if(type == NODEBOX_FIXED || type == NODEBOX_LEVELED)
96         {
97                 u16 fixed_count = readU16(is);
98                 while(fixed_count--)
99                 {
100                         aabb3f box;
101                         box.MinEdge = readV3F1000(is);
102                         box.MaxEdge = readV3F1000(is);
103                         fixed.push_back(box);
104                 }
105         }
106         else if(type == NODEBOX_WALLMOUNTED)
107         {
108                 wall_top.MinEdge = readV3F1000(is);
109                 wall_top.MaxEdge = readV3F1000(is);
110                 wall_bottom.MinEdge = readV3F1000(is);
111                 wall_bottom.MaxEdge = readV3F1000(is);
112                 wall_side.MinEdge = readV3F1000(is);
113                 wall_side.MaxEdge = readV3F1000(is);
114         }
115 }
116
117 /*
118         TileDef
119 */
120
121 void TileDef::serialize(std::ostream &os, u16 protocol_version) const
122 {
123         if(protocol_version >= 17)
124                 writeU8(os, 1);
125         else
126                 writeU8(os, 0);
127         os<<serializeString(name);
128         writeU8(os, animation.type);
129         writeU16(os, animation.aspect_w);
130         writeU16(os, animation.aspect_h);
131         writeF1000(os, animation.length);
132         if(protocol_version >= 17)
133                 writeU8(os, backface_culling);
134 }
135
136 void TileDef::deSerialize(std::istream &is)
137 {
138         int version = readU8(is);
139         name = deSerializeString(is);
140         animation.type = (TileAnimationType)readU8(is);
141         animation.aspect_w = readU16(is);
142         animation.aspect_h = readU16(is);
143         animation.length = readF1000(is);
144         if(version >= 1)
145                 backface_culling = readU8(is);
146 }
147
148 /*
149         SimpleSoundSpec serialization
150 */
151
152 static void serializeSimpleSoundSpec(const SimpleSoundSpec &ss,
153                 std::ostream &os)
154 {
155         os<<serializeString(ss.name);
156         writeF1000(os, ss.gain);
157 }
158 static void deSerializeSimpleSoundSpec(SimpleSoundSpec &ss, std::istream &is)
159 {
160         ss.name = deSerializeString(is);
161         ss.gain = readF1000(is);
162 }
163
164 /*
165         ContentFeatures
166 */
167
168 ContentFeatures::ContentFeatures()
169 {
170         reset();
171 }
172
173 ContentFeatures::~ContentFeatures()
174 {
175 }
176
177 void ContentFeatures::reset()
178 {
179         /*
180                 Cached stuff
181         */
182 #ifndef SERVER
183         solidness = 2;
184         visual_solidness = 0;
185         backface_culling = true;
186 #endif
187         has_on_construct = false;
188         has_on_destruct = false;
189         has_after_destruct = false;
190         /*
191                 Actual data
192
193                 NOTE: Most of this is always overridden by the default values given
194                       in builtin.lua
195         */
196         name = "";
197         groups.clear();
198         // Unknown nodes can be dug
199         groups["dig_immediate"] = 2;
200         drawtype = NDT_NORMAL;
201         mesh = "";
202 #ifndef SERVER
203         for(u32 i = 0; i < 24; i++)
204                 mesh_ptr[i] = NULL;
205 #endif
206         visual_scale = 1.0;
207         for(u32 i = 0; i < 6; i++)
208                 tiledef[i] = TileDef();
209         for(u16 j = 0; j < CF_SPECIAL_COUNT; j++)
210                 tiledef_special[j] = TileDef();
211         alpha = 255;
212         post_effect_color = video::SColor(0, 0, 0, 0);
213         param_type = CPT_NONE;
214         param_type_2 = CPT2_NONE;
215         is_ground_content = false;
216         light_propagates = false;
217         sunlight_propagates = false;
218         walkable = true;
219         pointable = true;
220         diggable = true;
221         climbable = false;
222         buildable_to = false;
223         rightclickable = true;
224         leveled = 0;
225         liquid_type = LIQUID_NONE;
226         liquid_alternative_flowing = "";
227         liquid_alternative_source = "";
228         liquid_viscosity = 0;
229         liquid_renewable = true;
230         freezemelt = "";
231         liquid_range = LIQUID_LEVEL_MAX+1;
232         drowning = 0;
233         light_source = 0;
234         damage_per_second = 0;
235         node_box = NodeBox();
236         selection_box = NodeBox();
237         collision_box = NodeBox();
238         waving = 0;
239         legacy_facedir_simple = false;
240         legacy_wallmounted = false;
241         sound_footstep = SimpleSoundSpec();
242         sound_dig = SimpleSoundSpec("__group");
243         sound_dug = SimpleSoundSpec();
244 }
245
246 void ContentFeatures::serialize(std::ostream &os, u16 protocol_version)
247 {
248         if(protocol_version < 24){
249                 serializeOld(os, protocol_version);
250                 return;
251         }
252
253         writeU8(os, 7); // version
254         os<<serializeString(name);
255         writeU16(os, groups.size());
256         for(ItemGroupList::const_iterator
257                         i = groups.begin(); i != groups.end(); i++){
258                 os<<serializeString(i->first);
259                 writeS16(os, i->second);
260         }
261         writeU8(os, drawtype);
262         writeF1000(os, visual_scale);
263         writeU8(os, 6);
264         for(u32 i = 0; i < 6; i++)
265                 tiledef[i].serialize(os, protocol_version);
266         writeU8(os, CF_SPECIAL_COUNT);
267         for(u32 i = 0; i < CF_SPECIAL_COUNT; i++){
268                 tiledef_special[i].serialize(os, protocol_version);
269         }
270         writeU8(os, alpha);
271         writeU8(os, post_effect_color.getAlpha());
272         writeU8(os, post_effect_color.getRed());
273         writeU8(os, post_effect_color.getGreen());
274         writeU8(os, post_effect_color.getBlue());
275         writeU8(os, param_type);
276         writeU8(os, param_type_2);
277         writeU8(os, is_ground_content);
278         writeU8(os, light_propagates);
279         writeU8(os, sunlight_propagates);
280         writeU8(os, walkable);
281         writeU8(os, pointable);
282         writeU8(os, diggable);
283         writeU8(os, climbable);
284         writeU8(os, buildable_to);
285         os<<serializeString(""); // legacy: used to be metadata_name
286         writeU8(os, liquid_type);
287         os<<serializeString(liquid_alternative_flowing);
288         os<<serializeString(liquid_alternative_source);
289         writeU8(os, liquid_viscosity);
290         writeU8(os, liquid_renewable);
291         writeU8(os, light_source);
292         writeU32(os, damage_per_second);
293         node_box.serialize(os, protocol_version);
294         selection_box.serialize(os, protocol_version);
295         writeU8(os, legacy_facedir_simple);
296         writeU8(os, legacy_wallmounted);
297         serializeSimpleSoundSpec(sound_footstep, os);
298         serializeSimpleSoundSpec(sound_dig, os);
299         serializeSimpleSoundSpec(sound_dug, os);
300         writeU8(os, rightclickable);
301         writeU8(os, drowning);
302         writeU8(os, leveled);
303         writeU8(os, liquid_range);
304         writeU8(os, waving);
305         // Stuff below should be moved to correct place in a version that otherwise changes
306         // the protocol version
307         os<<serializeString(mesh);
308         collision_box.serialize(os, protocol_version);
309 }
310
311 void ContentFeatures::deSerialize(std::istream &is)
312 {
313         int version = readU8(is);
314         if(version != 7){
315                 deSerializeOld(is, version);
316                 return;
317         }
318
319         name = deSerializeString(is);
320         groups.clear();
321         u32 groups_size = readU16(is);
322         for(u32 i = 0; i < groups_size; i++){
323                 std::string name = deSerializeString(is);
324                 int value = readS16(is);
325                 groups[name] = value;
326         }
327         drawtype = (enum NodeDrawType)readU8(is);
328         visual_scale = readF1000(is);
329         if(readU8(is) != 6)
330                 throw SerializationError("unsupported tile count");
331         for(u32 i = 0; i < 6; i++)
332                 tiledef[i].deSerialize(is);
333         if(readU8(is) != CF_SPECIAL_COUNT)
334                 throw SerializationError("unsupported CF_SPECIAL_COUNT");
335         for(u32 i = 0; i < CF_SPECIAL_COUNT; i++)
336                 tiledef_special[i].deSerialize(is);
337         alpha = readU8(is);
338         post_effect_color.setAlpha(readU8(is));
339         post_effect_color.setRed(readU8(is));
340         post_effect_color.setGreen(readU8(is));
341         post_effect_color.setBlue(readU8(is));
342         param_type = (enum ContentParamType)readU8(is);
343         param_type_2 = (enum ContentParamType2)readU8(is);
344         is_ground_content = readU8(is);
345         light_propagates = readU8(is);
346         sunlight_propagates = readU8(is);
347         walkable = readU8(is);
348         pointable = readU8(is);
349         diggable = readU8(is);
350         climbable = readU8(is);
351         buildable_to = readU8(is);
352         deSerializeString(is); // legacy: used to be metadata_name
353         liquid_type = (enum LiquidType)readU8(is);
354         liquid_alternative_flowing = deSerializeString(is);
355         liquid_alternative_source = deSerializeString(is);
356         liquid_viscosity = readU8(is);
357         liquid_renewable = readU8(is);
358         light_source = readU8(is);
359         damage_per_second = readU32(is);
360         node_box.deSerialize(is);
361         selection_box.deSerialize(is);
362         legacy_facedir_simple = readU8(is);
363         legacy_wallmounted = readU8(is);
364         deSerializeSimpleSoundSpec(sound_footstep, is);
365         deSerializeSimpleSoundSpec(sound_dig, is);
366         deSerializeSimpleSoundSpec(sound_dug, is);
367         rightclickable = readU8(is);
368         drowning = readU8(is);
369         leveled = readU8(is);
370         liquid_range = readU8(is);
371         waving = readU8(is);
372         // If you add anything here, insert it primarily inside the try-catch
373         // block to not need to increase the version.
374         try{
375                 // Stuff below should be moved to correct place in a version that
376                 // otherwise changes the protocol version
377         mesh = deSerializeString(is);
378         collision_box.deSerialize(is);
379         }catch(SerializationError &e) {};
380 }
381
382 /*
383         CNodeDefManager
384 */
385
386 class CNodeDefManager: public IWritableNodeDefManager {
387 public:
388         CNodeDefManager();
389         virtual ~CNodeDefManager();
390         void clear();
391         virtual IWritableNodeDefManager *clone();
392         virtual const ContentFeatures& get(content_t c) const;
393         virtual const ContentFeatures& get(const MapNode &n) const;
394         virtual bool getId(const std::string &name, content_t &result) const;
395         virtual content_t getId(const std::string &name) const;
396         virtual void getIds(const std::string &name, std::set<content_t> &result) const;
397         virtual const ContentFeatures& get(const std::string &name) const;
398         content_t allocateId();
399         virtual content_t set(const std::string &name, const ContentFeatures &def);
400         virtual content_t allocateDummy(const std::string &name);
401         virtual void updateAliases(IItemDefManager *idef);
402         virtual void updateTextures(IGameDef *gamedef);
403         void serialize(std::ostream &os, u16 protocol_version);
404         void deSerialize(std::istream &is);
405
406 private:
407         void addNameIdMapping(content_t i, std::string name);
408 #ifndef SERVER
409         void fillTileAttribs(ITextureSource *tsrc, TileSpec *tile, TileDef *tiledef,
410                 u32 shader_id, bool use_normal_texture, bool backface_culling,
411                 u8 alpha, u8 material_type);
412 #endif
413
414         // Features indexed by id
415         std::vector<ContentFeatures> m_content_features;
416
417         // A mapping for fast converting back and forth between names and ids
418         NameIdMapping m_name_id_mapping;
419
420         // Like m_name_id_mapping, but only from names to ids, and includes
421         // item aliases too. Updated by updateAliases()
422         // Note: Not serialized.
423
424         std::map<std::string, content_t> m_name_id_mapping_with_aliases;
425
426         // A mapping from groups to a list of content_ts (and their levels)
427         // that belong to it.  Necessary for a direct lookup in getIds().
428         // Note: Not serialized.
429         std::map<std::string, GroupItems> m_group_to_items;
430
431         // Next possibly free id
432         content_t m_next_id;
433 };
434
435
436 CNodeDefManager::CNodeDefManager()
437 {
438         clear();
439 }
440
441
442 CNodeDefManager::~CNodeDefManager()
443 {
444 #ifndef SERVER
445         for (u32 i = 0; i < m_content_features.size(); i++) {
446                 ContentFeatures *f = &m_content_features[i];
447                 for (u32 j = 0; j < 24; j++) {
448                         if (f->mesh_ptr[j])
449                                 f->mesh_ptr[j]->drop();
450                 }
451         }
452 #endif
453 }
454
455
456 void CNodeDefManager::clear()
457 {
458         m_content_features.clear();
459         m_name_id_mapping.clear();
460         m_name_id_mapping_with_aliases.clear();
461         m_group_to_items.clear();
462         m_next_id = 0;
463
464         u32 initial_length = 0;
465         initial_length = MYMAX(initial_length, CONTENT_UNKNOWN + 1);
466         initial_length = MYMAX(initial_length, CONTENT_AIR + 1);
467         initial_length = MYMAX(initial_length, CONTENT_IGNORE + 1);
468         m_content_features.resize(initial_length);
469
470         // Set CONTENT_UNKNOWN
471         {
472                 ContentFeatures f;
473                 f.name = "unknown";
474                 // Insert directly into containers
475                 content_t c = CONTENT_UNKNOWN;
476                 m_content_features[c] = f;
477                 addNameIdMapping(c, f.name);
478         }
479
480         // Set CONTENT_AIR
481         {
482                 ContentFeatures f;
483                 f.name                = "air";
484                 f.drawtype            = NDT_AIRLIKE;
485                 f.param_type          = CPT_LIGHT;
486                 f.light_propagates    = true;
487                 f.sunlight_propagates = true;
488                 f.walkable            = false;
489                 f.pointable           = false;
490                 f.diggable            = false;
491                 f.buildable_to        = true;
492                 f.is_ground_content   = true;
493                 // Insert directly into containers
494                 content_t c = CONTENT_AIR;
495                 m_content_features[c] = f;
496                 addNameIdMapping(c, f.name);
497         }
498
499         // Set CONTENT_IGNORE
500         {
501                 ContentFeatures f;
502                 f.name                = "ignore";
503                 f.drawtype            = NDT_AIRLIKE;
504                 f.param_type          = CPT_NONE;
505                 f.light_propagates    = false;
506                 f.sunlight_propagates = false;
507                 f.walkable            = false;
508                 f.pointable           = false;
509                 f.diggable            = false;
510                 f.buildable_to        = true; // A way to remove accidental CONTENT_IGNOREs
511                 f.is_ground_content   = true;
512                 // Insert directly into containers
513                 content_t c = CONTENT_IGNORE;
514                 m_content_features[c] = f;
515                 addNameIdMapping(c, f.name);
516         }
517 }
518
519
520 IWritableNodeDefManager *CNodeDefManager::clone()
521 {
522         CNodeDefManager *mgr = new CNodeDefManager();
523         *mgr = *this;
524         return mgr;
525 }
526
527
528 const ContentFeatures& CNodeDefManager::get(content_t c) const
529 {
530         if (c < m_content_features.size())
531                 return m_content_features[c];
532         else
533                 return m_content_features[CONTENT_UNKNOWN];
534 }
535
536
537 const ContentFeatures& CNodeDefManager::get(const MapNode &n) const
538 {
539         return get(n.getContent());
540 }
541
542
543 bool CNodeDefManager::getId(const std::string &name, content_t &result) const
544 {
545         std::map<std::string, content_t>::const_iterator
546                 i = m_name_id_mapping_with_aliases.find(name);
547         if(i == m_name_id_mapping_with_aliases.end())
548                 return false;
549         result = i->second;
550         return true;
551 }
552
553
554 content_t CNodeDefManager::getId(const std::string &name) const
555 {
556         content_t id = CONTENT_IGNORE;
557         getId(name, id);
558         return id;
559 }
560
561
562 void CNodeDefManager::getIds(const std::string &name,
563                 std::set<content_t> &result) const
564 {
565         //TimeTaker t("getIds", NULL, PRECISION_MICRO);
566         if (name.substr(0,6) != "group:") {
567                 content_t id = CONTENT_IGNORE;
568                 if(getId(name, id))
569                         result.insert(id);
570                 return;
571         }
572         std::string group = name.substr(6);
573
574         std::map<std::string, GroupItems>::const_iterator
575                 i = m_group_to_items.find(group);
576         if (i == m_group_to_items.end())
577                 return;
578
579         const GroupItems &items = i->second;
580         for (GroupItems::const_iterator j = items.begin();
581                 j != items.end(); ++j) {
582                 if ((*j).second != 0)
583                         result.insert((*j).first);
584         }
585         //printf("getIds: %dus\n", t.stop());
586 }
587
588
589 const ContentFeatures& CNodeDefManager::get(const std::string &name) const
590 {
591         content_t id = CONTENT_UNKNOWN;
592         getId(name, id);
593         return get(id);
594 }
595
596
597 // returns CONTENT_IGNORE if no free ID found
598 content_t CNodeDefManager::allocateId()
599 {
600         for (content_t id = m_next_id;
601                         id >= m_next_id; // overflow?
602                         ++id) {
603                 while (id >= m_content_features.size()) {
604                         m_content_features.push_back(ContentFeatures());
605                 }
606                 const ContentFeatures &f = m_content_features[id];
607                 if (f.name == "") {
608                         m_next_id = id + 1;
609                         return id;
610                 }
611         }
612         // If we arrive here, an overflow occurred in id.
613         // That means no ID was found
614         return CONTENT_IGNORE;
615 }
616
617
618 // IWritableNodeDefManager
619 content_t CNodeDefManager::set(const std::string &name, const ContentFeatures &def)
620 {
621         assert(name != "");
622         assert(name == def.name);
623
624         // Don't allow redefining ignore (but allow air and unknown)
625         if (name == "ignore") {
626                 infostream << "NodeDefManager: WARNING: Ignoring "
627                         "CONTENT_IGNORE redefinition"<<std::endl;
628                 return CONTENT_IGNORE;
629         }
630
631         content_t id = CONTENT_IGNORE;
632         if (!m_name_id_mapping.getId(name, id)) { // ignore aliases
633                 // Get new id
634                 id = allocateId();
635                 if (id == CONTENT_IGNORE) {
636                         infostream << "NodeDefManager: WARNING: Absolute "
637                                 "limit reached" << std::endl;
638                         return CONTENT_IGNORE;
639                 }
640                 assert(id != CONTENT_IGNORE);
641                 addNameIdMapping(id, name);
642         }
643         m_content_features[id] = def;
644         verbosestream << "NodeDefManager: registering content id \"" << id
645                 << "\": name=\"" << def.name << "\""<<std::endl;
646
647         // Add this content to the list of all groups it belongs to
648         // FIXME: This should remove a node from groups it no longer
649         // belongs to when a node is re-registered
650         for (ItemGroupList::const_iterator i = def.groups.begin();
651                 i != def.groups.end(); ++i) {
652                 std::string group_name = i->first;
653
654                 std::map<std::string, GroupItems>::iterator
655                         j = m_group_to_items.find(group_name);
656                 if (j == m_group_to_items.end()) {
657                         m_group_to_items[group_name].push_back(
658                                         std::make_pair(id, i->second));
659                 } else {
660                         GroupItems &items = j->second;
661                         items.push_back(std::make_pair(id, i->second));
662                 }
663         }
664         return id;
665 }
666
667
668 content_t CNodeDefManager::allocateDummy(const std::string &name)
669 {
670         assert(name != "");
671         ContentFeatures f;
672         f.name = name;
673         return set(name, f);
674 }
675
676
677 void CNodeDefManager::updateAliases(IItemDefManager *idef)
678 {
679         std::set<std::string> all = idef->getAll();
680         m_name_id_mapping_with_aliases.clear();
681         for (std::set<std::string>::iterator
682                         i = all.begin(); i != all.end(); i++) {
683                 std::string name = *i;
684                 std::string convert_to = idef->getAlias(name);
685                 content_t id;
686                 if (m_name_id_mapping.getId(convert_to, id)) {
687                         m_name_id_mapping_with_aliases.insert(
688                                         std::make_pair(name, id));
689                 }
690         }
691 }
692
693
694 void CNodeDefManager::updateTextures(IGameDef *gamedef)
695 {
696 #ifndef SERVER
697         infostream << "CNodeDefManager::updateTextures(): Updating "
698                 "textures in node definitions" << std::endl;
699         
700         ITextureSource *tsrc = gamedef->tsrc();
701         IShaderSource *shdsrc = gamedef->getShaderSource();
702         scene::ISceneManager* smgr = gamedef->getSceneManager();
703         scene::IMeshManipulator* meshmanip = smgr->getMeshManipulator();
704
705         bool new_style_water           = g_settings->getBool("new_style_water");
706         bool new_style_leaves          = g_settings->getBool("new_style_leaves");
707         bool connected_glass           = g_settings->getBool("connected_glass");
708         bool opaque_water              = g_settings->getBool("opaque_water");
709         bool enable_shaders            = g_settings->getBool("enable_shaders");
710         bool enable_bumpmapping        = g_settings->getBool("enable_bumpmapping");
711         bool enable_parallax_occlusion = g_settings->getBool("enable_parallax_occlusion");
712
713         bool use_normal_texture = enable_shaders &&
714                 (enable_bumpmapping || enable_parallax_occlusion);
715
716         for (u32 i = 0; i < m_content_features.size(); i++) {
717                 ContentFeatures *f = &m_content_features[i];
718
719                 // Figure out the actual tiles to use
720                 TileDef tiledef[6];
721                 for (u32 j = 0; j < 6; j++) {
722                         tiledef[j] = f->tiledef[j];
723                         if (tiledef[j].name == "")
724                                 tiledef[j].name = "unknown_node.png";
725                 }
726
727                 bool is_liquid = false;
728                 bool is_water_surface = false;
729
730                 u8 material_type = (f->alpha == 255) ?
731                         TILE_MATERIAL_BASIC : TILE_MATERIAL_ALPHA;
732
733                 switch (f->drawtype) {
734                 default:
735                 case NDT_NORMAL:
736                         f->solidness = 2;
737                         break;
738                 case NDT_AIRLIKE:
739                         f->solidness = 0;
740                         break;
741                 case NDT_LIQUID:
742                         assert(f->liquid_type == LIQUID_SOURCE);
743                         if (opaque_water)
744                                 f->alpha = 255;
745                         if (new_style_water){
746                                 f->solidness = 0;
747                         } else {
748                                 f->solidness = 1;
749                                 f->backface_culling = false;
750                         }
751                         is_liquid = true;
752                         break;
753                 case NDT_FLOWINGLIQUID:
754                         assert(f->liquid_type == LIQUID_FLOWING);
755                         f->solidness = 0;
756                         if (opaque_water)
757                                 f->alpha = 255;
758                         is_liquid = true;
759                         break;
760                 case NDT_GLASSLIKE:
761                         f->solidness = 0;
762                         f->visual_solidness = 1;
763                         break;
764                 case NDT_GLASSLIKE_FRAMED:
765                         f->solidness = 0;
766                         f->visual_solidness = 1;
767                         break;
768                 case NDT_GLASSLIKE_FRAMED_OPTIONAL:
769                         f->solidness = 0;
770                         f->visual_solidness = 1;
771                         f->drawtype = connected_glass ? NDT_GLASSLIKE_FRAMED : NDT_GLASSLIKE;
772                         break;
773                 case NDT_ALLFACES:
774                         f->solidness = 0;
775                         f->visual_solidness = 1;
776                         break;
777                 case NDT_ALLFACES_OPTIONAL:
778                         if (new_style_leaves) {
779                                 f->drawtype = NDT_ALLFACES;
780                                 f->solidness = 0;
781                                 f->visual_solidness = 1;
782                         } else {
783                                 f->drawtype = NDT_NORMAL;
784                                 f->solidness = 2;
785                                 for (u32 i = 0; i < 6; i++)
786                                         tiledef[i].name += std::string("^[noalpha");
787                         }
788                         if (f->waving == 1)
789                                 material_type = TILE_MATERIAL_WAVING_LEAVES;
790                         break;
791                 case NDT_PLANTLIKE:
792                         f->solidness = 0;
793                         f->backface_culling = false;
794                         if (f->waving == 1)
795                                 material_type = TILE_MATERIAL_WAVING_PLANTS;
796                         break;
797                 case NDT_FIRELIKE:
798                         f->backface_culling = false;
799                         f->solidness = 0;
800                         break;
801                 case NDT_MESH:
802                         f->solidness = 0;
803                         f->backface_culling = false;
804                         break;
805                 case NDT_TORCHLIKE:
806                 case NDT_SIGNLIKE:
807                 case NDT_FENCELIKE:
808                 case NDT_RAILLIKE:
809                 case NDT_NODEBOX:
810                         f->solidness = 0;
811                         break;
812                 }
813
814                 if (is_liquid) {
815                         material_type = (f->alpha == 255) ?
816                                 TILE_MATERIAL_LIQUID_OPAQUE : TILE_MATERIAL_LIQUID_TRANSPARENT;
817                         if (f->name == "default:water_source")
818                                 is_water_surface = true;
819                 }
820
821                 u32 tile_shader[6];
822                 for (u16 j = 0; j < 6; j++) {
823                         tile_shader[j] = shdsrc->getShader("nodes_shader",
824                                 material_type, f->drawtype);
825                 }
826
827                 if (is_water_surface) {
828                         tile_shader[0] = shdsrc->getShader("water_surface_shader",
829                                 material_type, f->drawtype);
830                 }
831
832                 // Tiles (fill in f->tiles[])
833                 for (u16 j = 0; j < 6; j++) {
834                         fillTileAttribs(tsrc, &f->tiles[j], &tiledef[j], tile_shader[j],
835                                 use_normal_texture, f->backface_culling, f->alpha, material_type);
836                 }
837
838                 // Special tiles (fill in f->special_tiles[])
839                 for (u16 j = 0; j < CF_SPECIAL_COUNT; j++) {
840                         fillTileAttribs(tsrc, &f->special_tiles[j], &f->tiledef_special[j],
841                                 tile_shader[j], use_normal_texture,
842                                 f->tiledef_special[j].backface_culling, f->alpha, material_type);
843                 }
844
845                 // Meshnode drawtype
846                 // Read the mesh and apply scale
847                 if ((f->drawtype == NDT_MESH) && (f->mesh != "")) {
848                         f->mesh_ptr[0] = gamedef->getMesh(f->mesh);
849                         if (f->mesh_ptr[0]){
850                                 v3f scale = v3f(1.0, 1.0, 1.0) * BS * f->visual_scale;
851                                 scaleMesh(f->mesh_ptr[0], scale);
852                                 recalculateBoundingBox(f->mesh_ptr[0]);
853                         }
854                 }
855
856                 //Convert regular nodebox nodes to meshnodes
857                 //Change the drawtype and apply scale
858                 else if ((f->drawtype == NDT_NODEBOX) && 
859                                 ((f->node_box.type == NODEBOX_REGULAR) ||
860                                 (f->node_box.type == NODEBOX_FIXED)) &&
861                                 (!f->node_box.fixed.empty())) {
862                         f->drawtype = NDT_MESH;
863                         f->mesh_ptr[0] = convertNodeboxNodeToMesh(f);
864                         v3f scale = v3f(1.0, 1.0, 1.0) * f->visual_scale;
865                         scaleMesh(f->mesh_ptr[0], scale);
866                         recalculateBoundingBox(f->mesh_ptr[0]);
867                 }
868
869                 //Cache 6dfacedir rotated clones of meshes
870                 if (f->mesh_ptr[0] && (f->param_type_2 == CPT2_FACEDIR)) {
871                         for (u16 j = 1; j < 24; j++) {
872                                 f->mesh_ptr[j] = cloneMesh(f->mesh_ptr[0]);
873                                 rotateMeshBy6dFacedir(f->mesh_ptr[j], j);
874                                 recalculateBoundingBox(f->mesh_ptr[j]);
875                                 meshmanip->recalculateNormals(f->mesh_ptr[j], false, false);
876                         }
877                 }
878         }
879 #endif
880 }
881
882
883 #ifndef SERVER
884 void CNodeDefManager::fillTileAttribs(ITextureSource *tsrc, TileSpec *tile,
885                 TileDef *tiledef, u32 shader_id, bool use_normal_texture,
886                 bool backface_culling, u8 alpha, u8 material_type)
887 {
888         tile->shader_id     = shader_id;
889         tile->texture       = tsrc->getTexture(tiledef->name, &tile->texture_id);
890         tile->alpha         = alpha;
891         tile->material_type = material_type;
892
893         // Normal texture
894         if (use_normal_texture)
895                 tile->normal_texture = tsrc->getNormalTexture(tiledef->name);
896
897         // Material flags
898         tile->material_flags = 0;
899         if (backface_culling)
900                 tile->material_flags |= MATERIAL_FLAG_BACKFACE_CULLING;
901         if (tiledef->animation.type == TAT_VERTICAL_FRAMES)
902                 tile->material_flags |= MATERIAL_FLAG_ANIMATION_VERTICAL_FRAMES;
903
904         // Animation parameters
905         int frame_count = 1;
906         if (tile->material_flags & MATERIAL_FLAG_ANIMATION_VERTICAL_FRAMES) {
907                 // Get texture size to determine frame count by aspect ratio
908                 v2u32 size = tile->texture->getOriginalSize();
909                 int frame_height = (float)size.X /
910                                 (float)tiledef->animation.aspect_w *
911                                 (float)tiledef->animation.aspect_h;
912                 frame_count = size.Y / frame_height;
913                 int frame_length_ms = 1000.0 * tiledef->animation.length / frame_count;
914                 tile->animation_frame_count = frame_count;
915                 tile->animation_frame_length_ms = frame_length_ms;
916         }
917
918         if (frame_count == 1) {
919                 tile->material_flags &= ~MATERIAL_FLAG_ANIMATION_VERTICAL_FRAMES;
920         } else {
921                 std::ostringstream os(std::ios::binary);
922                 for (int i = 0; i < frame_count; i++) {
923                         FrameSpec frame;
924
925                         os.str("");
926                         os << tiledef->name << "^[verticalframe:"
927                                 << frame_count << ":" << i;
928
929                         frame.texture = tsrc->getTexture(os.str(), &frame.texture_id);
930                         if (tile->normal_texture)
931                                 frame.normal_texture = tsrc->getNormalTexture(os.str());
932                         tile->frames[i] = frame;
933                 }
934         }
935 }
936 #endif
937
938
939 void CNodeDefManager::serialize(std::ostream &os, u16 protocol_version)
940 {
941         writeU8(os, 1); // version
942         u16 count = 0;
943         std::ostringstream os2(std::ios::binary);
944         for (u32 i = 0; i < m_content_features.size(); i++) {
945                 if (i == CONTENT_IGNORE || i == CONTENT_AIR
946                                 || i == CONTENT_UNKNOWN)
947                         continue;
948                 ContentFeatures *f = &m_content_features[i];
949                 if (f->name == "")
950                         continue;
951                 writeU16(os2, i);
952                 // Wrap it in a string to allow different lengths without
953                 // strict version incompatibilities
954                 std::ostringstream wrapper_os(std::ios::binary);
955                 f->serialize(wrapper_os, protocol_version);
956                 os2<<serializeString(wrapper_os.str());
957
958                 assert(count + 1 > count); // must not overflow
959                 count++;
960         }
961         writeU16(os, count);
962         os << serializeLongString(os2.str());
963 }
964
965
966 void CNodeDefManager::deSerialize(std::istream &is)
967 {
968         clear();
969         int version = readU8(is);
970         if (version != 1)
971                 throw SerializationError("unsupported NodeDefinitionManager version");
972         u16 count = readU16(is);
973         std::istringstream is2(deSerializeLongString(is), std::ios::binary);
974         ContentFeatures f;
975         for (u16 n = 0; n < count; n++) {
976                 u16 i = readU16(is2);
977
978                 // Read it from the string wrapper
979                 std::string wrapper = deSerializeString(is2);
980                 std::istringstream wrapper_is(wrapper, std::ios::binary);
981                 f.deSerialize(wrapper_is);
982
983                 // Check error conditions
984                 if (i == CONTENT_IGNORE || i == CONTENT_AIR || i == CONTENT_UNKNOWN) {
985                         infostream << "NodeDefManager::deSerialize(): WARNING: "
986                                 "not changing builtin node " << i << std::endl;
987                         continue;
988                 }
989                 if (f.name == "") {
990                         infostream << "NodeDefManager::deSerialize(): WARNING: "
991                                 "received empty name" << std::endl;
992                         continue;
993                 }
994
995                 // Ignore aliases
996                 u16 existing_id;
997                 if (m_name_id_mapping.getId(f.name, existing_id) && i != existing_id) {
998                         infostream << "NodeDefManager::deSerialize(): WARNING: "
999                                 "already defined with different ID: " << f.name << std::endl;
1000                         continue;
1001                 }
1002
1003                 // All is ok, add node definition with the requested ID
1004                 if (i >= m_content_features.size())
1005                         m_content_features.resize((u32)(i) + 1);
1006                 m_content_features[i] = f;
1007                 addNameIdMapping(i, f.name);
1008                 verbosestream << "deserialized " << f.name << std::endl;
1009         }
1010 }
1011
1012
1013 void CNodeDefManager::addNameIdMapping(content_t i, std::string name)
1014 {
1015         m_name_id_mapping.set(i, name);
1016         m_name_id_mapping_with_aliases.insert(std::make_pair(name, i));
1017 }
1018
1019
1020 IWritableNodeDefManager *createNodeDefManager()
1021 {
1022         return new CNodeDefManager();
1023 }
1024
1025
1026 //// Serialization of old ContentFeatures formats
1027 void ContentFeatures::serializeOld(std::ostream &os, u16 protocol_version)
1028 {
1029         if (protocol_version == 13)
1030         {
1031                 writeU8(os, 5); // version
1032                 os<<serializeString(name);
1033                 writeU16(os, groups.size());
1034                 for (ItemGroupList::const_iterator
1035                                 i = groups.begin(); i != groups.end(); i++) {
1036                         os<<serializeString(i->first);
1037                         writeS16(os, i->second);
1038                 }
1039                 writeU8(os, drawtype);
1040                 writeF1000(os, visual_scale);
1041                 writeU8(os, 6);
1042                 for (u32 i = 0; i < 6; i++)
1043                         tiledef[i].serialize(os, protocol_version);
1044                 //CF_SPECIAL_COUNT = 2 before cf ver. 7 and protocol ver. 24
1045                 writeU8(os, 2);
1046                 for (u32 i = 0; i < 2; i++)
1047                         tiledef_special[i].serialize(os, protocol_version);
1048                 writeU8(os, alpha);
1049                 writeU8(os, post_effect_color.getAlpha());
1050                 writeU8(os, post_effect_color.getRed());
1051                 writeU8(os, post_effect_color.getGreen());
1052                 writeU8(os, post_effect_color.getBlue());
1053                 writeU8(os, param_type);
1054                 writeU8(os, param_type_2);
1055                 writeU8(os, is_ground_content);
1056                 writeU8(os, light_propagates);
1057                 writeU8(os, sunlight_propagates);
1058                 writeU8(os, walkable);
1059                 writeU8(os, pointable);
1060                 writeU8(os, diggable);
1061                 writeU8(os, climbable);
1062                 writeU8(os, buildable_to);
1063                 os<<serializeString(""); // legacy: used to be metadata_name
1064                 writeU8(os, liquid_type);
1065                 os<<serializeString(liquid_alternative_flowing);
1066                 os<<serializeString(liquid_alternative_source);
1067                 writeU8(os, liquid_viscosity);
1068                 writeU8(os, light_source);
1069                 writeU32(os, damage_per_second);
1070                 node_box.serialize(os, protocol_version);
1071                 selection_box.serialize(os, protocol_version);
1072                 writeU8(os, legacy_facedir_simple);
1073                 writeU8(os, legacy_wallmounted);
1074                 serializeSimpleSoundSpec(sound_footstep, os);
1075                 serializeSimpleSoundSpec(sound_dig, os);
1076                 serializeSimpleSoundSpec(sound_dug, os);
1077         }
1078         else if (protocol_version > 13 && protocol_version < 24) {
1079                 writeU8(os, 6); // version
1080                 os<<serializeString(name);
1081                 writeU16(os, groups.size());
1082                 for (ItemGroupList::const_iterator
1083                         i = groups.begin(); i != groups.end(); i++) {
1084                                 os<<serializeString(i->first);
1085                                 writeS16(os, i->second);
1086                 }
1087                 writeU8(os, drawtype);
1088                 writeF1000(os, visual_scale);
1089                 writeU8(os, 6);
1090                 for (u32 i = 0; i < 6; i++)
1091                         tiledef[i].serialize(os, protocol_version);
1092                 //CF_SPECIAL_COUNT = 2 before cf ver. 7 and protocol ver. 24
1093                 writeU8(os, 2);
1094                 for (u32 i = 0; i < 2; i++)
1095                         tiledef_special[i].serialize(os, protocol_version);
1096                 writeU8(os, alpha);
1097                 writeU8(os, post_effect_color.getAlpha());
1098                 writeU8(os, post_effect_color.getRed());
1099                 writeU8(os, post_effect_color.getGreen());
1100                 writeU8(os, post_effect_color.getBlue());
1101                 writeU8(os, param_type);
1102                 writeU8(os, param_type_2);
1103                 writeU8(os, is_ground_content);
1104                 writeU8(os, light_propagates);
1105                 writeU8(os, sunlight_propagates);
1106                 writeU8(os, walkable);
1107                 writeU8(os, pointable);
1108                 writeU8(os, diggable);
1109                 writeU8(os, climbable);
1110                 writeU8(os, buildable_to);
1111                 os<<serializeString(""); // legacy: used to be metadata_name
1112                 writeU8(os, liquid_type);
1113                 os<<serializeString(liquid_alternative_flowing);
1114                 os<<serializeString(liquid_alternative_source);
1115                 writeU8(os, liquid_viscosity);
1116                 writeU8(os, liquid_renewable);
1117                 writeU8(os, light_source);
1118                 writeU32(os, damage_per_second);
1119                 node_box.serialize(os, protocol_version);
1120                 selection_box.serialize(os, protocol_version);
1121                 writeU8(os, legacy_facedir_simple);
1122                 writeU8(os, legacy_wallmounted);
1123                 serializeSimpleSoundSpec(sound_footstep, os);
1124                 serializeSimpleSoundSpec(sound_dig, os);
1125                 serializeSimpleSoundSpec(sound_dug, os);
1126                 writeU8(os, rightclickable);
1127                 writeU8(os, drowning);
1128                 writeU8(os, leveled);
1129                 writeU8(os, liquid_range);
1130         } else 
1131                 throw SerializationError("ContentFeatures::serialize(): "
1132                         "Unsupported version requested");
1133 }
1134
1135
1136 void ContentFeatures::deSerializeOld(std::istream &is, int version)
1137 {
1138         if (version == 5) // In PROTOCOL_VERSION 13
1139         {
1140                 name = deSerializeString(is);
1141                 groups.clear();
1142                 u32 groups_size = readU16(is);
1143                 for(u32 i=0; i<groups_size; i++){
1144                         std::string name = deSerializeString(is);
1145                         int value = readS16(is);
1146                         groups[name] = value;
1147                 }
1148                 drawtype = (enum NodeDrawType)readU8(is);
1149                 visual_scale = readF1000(is);
1150                 if (readU8(is) != 6)
1151                         throw SerializationError("unsupported tile count");
1152                 for (u32 i = 0; i < 6; i++)
1153                         tiledef[i].deSerialize(is);
1154                 if (readU8(is) != CF_SPECIAL_COUNT)
1155                         throw SerializationError("unsupported CF_SPECIAL_COUNT");
1156                 for (u32 i = 0; i < CF_SPECIAL_COUNT; i++)
1157                         tiledef_special[i].deSerialize(is);
1158                 alpha = readU8(is);
1159                 post_effect_color.setAlpha(readU8(is));
1160                 post_effect_color.setRed(readU8(is));
1161                 post_effect_color.setGreen(readU8(is));
1162                 post_effect_color.setBlue(readU8(is));
1163                 param_type = (enum ContentParamType)readU8(is);
1164                 param_type_2 = (enum ContentParamType2)readU8(is);
1165                 is_ground_content = readU8(is);
1166                 light_propagates = readU8(is);
1167                 sunlight_propagates = readU8(is);
1168                 walkable = readU8(is);
1169                 pointable = readU8(is);
1170                 diggable = readU8(is);
1171                 climbable = readU8(is);
1172                 buildable_to = readU8(is);
1173                 deSerializeString(is); // legacy: used to be metadata_name
1174                 liquid_type = (enum LiquidType)readU8(is);
1175                 liquid_alternative_flowing = deSerializeString(is);
1176                 liquid_alternative_source = deSerializeString(is);
1177                 liquid_viscosity = readU8(is);
1178                 light_source = readU8(is);
1179                 damage_per_second = readU32(is);
1180                 node_box.deSerialize(is);
1181                 selection_box.deSerialize(is);
1182                 legacy_facedir_simple = readU8(is);
1183                 legacy_wallmounted = readU8(is);
1184                 deSerializeSimpleSoundSpec(sound_footstep, is);
1185                 deSerializeSimpleSoundSpec(sound_dig, is);
1186                 deSerializeSimpleSoundSpec(sound_dug, is);
1187         } else if (version == 6) {
1188                 name = deSerializeString(is);
1189                 groups.clear();
1190                 u32 groups_size = readU16(is);
1191                 for (u32 i = 0; i < groups_size; i++) {
1192                         std::string name = deSerializeString(is);
1193                         int     value = readS16(is);
1194                         groups[name] = value;
1195                 }
1196                 drawtype = (enum NodeDrawType)readU8(is);
1197                 visual_scale = readF1000(is);
1198                 if (readU8(is) != 6)
1199                         throw SerializationError("unsupported tile count");
1200                 for (u32 i = 0; i < 6; i++)
1201                         tiledef[i].deSerialize(is);
1202                 // CF_SPECIAL_COUNT in version 6 = 2
1203                 if (readU8(is) != 2)
1204                         throw SerializationError("unsupported CF_SPECIAL_COUNT");
1205                 for (u32 i = 0; i < 2; i++)
1206                         tiledef_special[i].deSerialize(is);
1207                 alpha = readU8(is);
1208                 post_effect_color.setAlpha(readU8(is));
1209                 post_effect_color.setRed(readU8(is));
1210                 post_effect_color.setGreen(readU8(is));
1211                 post_effect_color.setBlue(readU8(is));
1212                 param_type = (enum ContentParamType)readU8(is);
1213                 param_type_2 = (enum ContentParamType2)readU8(is);
1214                 is_ground_content = readU8(is);
1215                 light_propagates = readU8(is);
1216                 sunlight_propagates = readU8(is);
1217                 walkable = readU8(is);
1218                 pointable = readU8(is);
1219                 diggable = readU8(is);
1220                 climbable = readU8(is);
1221                 buildable_to = readU8(is);
1222                 deSerializeString(is); // legacy: used to be metadata_name
1223                 liquid_type = (enum LiquidType)readU8(is);
1224                 liquid_alternative_flowing = deSerializeString(is);
1225                 liquid_alternative_source = deSerializeString(is);
1226                 liquid_viscosity = readU8(is);
1227                 liquid_renewable = readU8(is);
1228                 light_source = readU8(is);
1229                 damage_per_second = readU32(is);
1230                 node_box.deSerialize(is);
1231                 selection_box.deSerialize(is);
1232                 legacy_facedir_simple = readU8(is);
1233                 legacy_wallmounted = readU8(is);
1234                 deSerializeSimpleSoundSpec(sound_footstep, is);
1235                 deSerializeSimpleSoundSpec(sound_dig, is);
1236                 deSerializeSimpleSoundSpec(sound_dug, is);
1237                 rightclickable = readU8(is);
1238                 drowning = readU8(is);
1239                 leveled = readU8(is);
1240                 liquid_range = readU8(is);
1241         } else {
1242                 throw SerializationError("unsupported ContentFeatures version");
1243         }
1244 }