Liquids: Flow into and destroy 'floodable' nodes
[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 "itemdef.h"
23 #ifndef SERVER
24 #include "client/tile.h"
25 #include "mesh.h"
26 #include <IMeshManipulator.h>
27 #endif
28 #include "log.h"
29 #include "settings.h"
30 #include "nameidmapping.h"
31 #include "util/numeric.h"
32 #include "util/serialize.h"
33 #include "exceptions.h"
34 #include "debug.h"
35 #include "gamedef.h"
36 #include <fstream> // Used in applyTextureOverrides()
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 >= 26)
124                 writeU8(os, 2);
125         else if (protocol_version >= 17)
126                 writeU8(os, 1);
127         else
128                 writeU8(os, 0);
129         os<<serializeString(name);
130         writeU8(os, animation.type);
131         writeU16(os, animation.aspect_w);
132         writeU16(os, animation.aspect_h);
133         writeF1000(os, animation.length);
134         if (protocol_version >= 17)
135                 writeU8(os, backface_culling);
136         if (protocol_version >= 26) {
137                 writeU8(os, tileable_horizontal);
138                 writeU8(os, tileable_vertical);
139         }
140 }
141
142 void TileDef::deSerialize(std::istream &is)
143 {
144         int version = readU8(is);
145         name = deSerializeString(is);
146         animation.type = (TileAnimationType)readU8(is);
147         animation.aspect_w = readU16(is);
148         animation.aspect_h = readU16(is);
149         animation.length = readF1000(is);
150         if (version >= 1)
151                 backface_culling = readU8(is);
152         if (version >= 2) {
153                 tileable_horizontal = readU8(is);
154                 tileable_vertical = readU8(is);
155         }
156 }
157
158
159 /*
160         SimpleSoundSpec serialization
161 */
162
163 static void serializeSimpleSoundSpec(const SimpleSoundSpec &ss,
164                 std::ostream &os)
165 {
166         os<<serializeString(ss.name);
167         writeF1000(os, ss.gain);
168 }
169 static void deSerializeSimpleSoundSpec(SimpleSoundSpec &ss, std::istream &is)
170 {
171         ss.name = deSerializeString(is);
172         ss.gain = readF1000(is);
173 }
174
175 /*
176         ContentFeatures
177 */
178
179 ContentFeatures::ContentFeatures()
180 {
181         reset();
182 }
183
184 ContentFeatures::~ContentFeatures()
185 {
186 }
187
188 void ContentFeatures::reset()
189 {
190         /*
191                 Cached stuff
192         */
193 #ifndef SERVER
194         solidness = 2;
195         visual_solidness = 0;
196         backface_culling = true;
197
198 #endif
199         has_on_construct = false;
200         has_on_destruct = false;
201         has_after_destruct = false;
202         /*
203                 Actual data
204
205                 NOTE: Most of this is always overridden by the default values given
206                       in builtin.lua
207         */
208         name = "";
209         groups.clear();
210         // Unknown nodes can be dug
211         groups["dig_immediate"] = 2;
212         drawtype = NDT_NORMAL;
213         mesh = "";
214 #ifndef SERVER
215         for(u32 i = 0; i < 24; i++)
216                 mesh_ptr[i] = NULL;
217         minimap_color = video::SColor(0, 0, 0, 0);
218 #endif
219         visual_scale = 1.0;
220         for(u32 i = 0; i < 6; i++)
221                 tiledef[i] = TileDef();
222         for(u16 j = 0; j < CF_SPECIAL_COUNT; j++)
223                 tiledef_special[j] = TileDef();
224         alpha = 255;
225         post_effect_color = video::SColor(0, 0, 0, 0);
226         param_type = CPT_NONE;
227         param_type_2 = CPT2_NONE;
228         is_ground_content = false;
229         light_propagates = false;
230         sunlight_propagates = false;
231         walkable = true;
232         pointable = true;
233         diggable = true;
234         climbable = false;
235         buildable_to = false;
236         floodable = false;
237         rightclickable = true;
238         leveled = 0;
239         liquid_type = LIQUID_NONE;
240         liquid_alternative_flowing = "";
241         liquid_alternative_source = "";
242         liquid_viscosity = 0;
243         liquid_renewable = true;
244         liquid_range = LIQUID_LEVEL_MAX+1;
245         drowning = 0;
246         light_source = 0;
247         damage_per_second = 0;
248         node_box = NodeBox();
249         selection_box = NodeBox();
250         collision_box = NodeBox();
251         waving = 0;
252         legacy_facedir_simple = false;
253         legacy_wallmounted = false;
254         sound_footstep = SimpleSoundSpec();
255         sound_dig = SimpleSoundSpec("__group");
256         sound_dug = SimpleSoundSpec();
257 }
258
259 void ContentFeatures::serialize(std::ostream &os, u16 protocol_version) const
260 {
261         if(protocol_version < 24){
262                 serializeOld(os, protocol_version);
263                 return;
264         }
265
266         writeU8(os, 7); // version
267         os<<serializeString(name);
268         writeU16(os, groups.size());
269         for(ItemGroupList::const_iterator
270                         i = groups.begin(); i != groups.end(); ++i){
271                 os<<serializeString(i->first);
272                 writeS16(os, i->second);
273         }
274         writeU8(os, drawtype);
275         writeF1000(os, visual_scale);
276         writeU8(os, 6);
277         for(u32 i = 0; i < 6; i++)
278                 tiledef[i].serialize(os, protocol_version);
279         writeU8(os, CF_SPECIAL_COUNT);
280         for(u32 i = 0; i < CF_SPECIAL_COUNT; i++){
281                 tiledef_special[i].serialize(os, protocol_version);
282         }
283         writeU8(os, alpha);
284         writeU8(os, post_effect_color.getAlpha());
285         writeU8(os, post_effect_color.getRed());
286         writeU8(os, post_effect_color.getGreen());
287         writeU8(os, post_effect_color.getBlue());
288         writeU8(os, param_type);
289         writeU8(os, param_type_2);
290         writeU8(os, is_ground_content);
291         writeU8(os, light_propagates);
292         writeU8(os, sunlight_propagates);
293         writeU8(os, walkable);
294         writeU8(os, pointable);
295         writeU8(os, diggable);
296         writeU8(os, climbable);
297         writeU8(os, buildable_to);
298         os<<serializeString(""); // legacy: used to be metadata_name
299         writeU8(os, liquid_type);
300         os<<serializeString(liquid_alternative_flowing);
301         os<<serializeString(liquid_alternative_source);
302         writeU8(os, liquid_viscosity);
303         writeU8(os, liquid_renewable);
304         writeU8(os, light_source);
305         writeU32(os, damage_per_second);
306         node_box.serialize(os, protocol_version);
307         selection_box.serialize(os, protocol_version);
308         writeU8(os, legacy_facedir_simple);
309         writeU8(os, legacy_wallmounted);
310         serializeSimpleSoundSpec(sound_footstep, os);
311         serializeSimpleSoundSpec(sound_dig, os);
312         serializeSimpleSoundSpec(sound_dug, os);
313         writeU8(os, rightclickable);
314         writeU8(os, drowning);
315         writeU8(os, leveled);
316         writeU8(os, liquid_range);
317         writeU8(os, waving);
318         // Stuff below should be moved to correct place in a version that otherwise changes
319         // the protocol version
320         os<<serializeString(mesh);
321         collision_box.serialize(os, protocol_version);
322         writeU8(os, floodable);
323 }
324
325 void ContentFeatures::deSerialize(std::istream &is)
326 {
327         int version = readU8(is);
328         if(version != 7){
329                 deSerializeOld(is, version);
330                 return;
331         }
332
333         name = deSerializeString(is);
334         groups.clear();
335         u32 groups_size = readU16(is);
336         for(u32 i = 0; i < groups_size; i++){
337                 std::string name = deSerializeString(is);
338                 int value = readS16(is);
339                 groups[name] = value;
340         }
341         drawtype = (enum NodeDrawType)readU8(is);
342         visual_scale = readF1000(is);
343         if(readU8(is) != 6)
344                 throw SerializationError("unsupported tile count");
345         for(u32 i = 0; i < 6; i++)
346                 tiledef[i].deSerialize(is);
347         if(readU8(is) != CF_SPECIAL_COUNT)
348                 throw SerializationError("unsupported CF_SPECIAL_COUNT");
349         for(u32 i = 0; i < CF_SPECIAL_COUNT; i++)
350                 tiledef_special[i].deSerialize(is);
351         alpha = readU8(is);
352         post_effect_color.setAlpha(readU8(is));
353         post_effect_color.setRed(readU8(is));
354         post_effect_color.setGreen(readU8(is));
355         post_effect_color.setBlue(readU8(is));
356         param_type = (enum ContentParamType)readU8(is);
357         param_type_2 = (enum ContentParamType2)readU8(is);
358         is_ground_content = readU8(is);
359         light_propagates = readU8(is);
360         sunlight_propagates = readU8(is);
361         walkable = readU8(is);
362         pointable = readU8(is);
363         diggable = readU8(is);
364         climbable = readU8(is);
365         buildable_to = readU8(is);
366         deSerializeString(is); // legacy: used to be metadata_name
367         liquid_type = (enum LiquidType)readU8(is);
368         liquid_alternative_flowing = deSerializeString(is);
369         liquid_alternative_source = deSerializeString(is);
370         liquid_viscosity = readU8(is);
371         liquid_renewable = readU8(is);
372         light_source = readU8(is);
373         damage_per_second = readU32(is);
374         node_box.deSerialize(is);
375         selection_box.deSerialize(is);
376         legacy_facedir_simple = readU8(is);
377         legacy_wallmounted = readU8(is);
378         deSerializeSimpleSoundSpec(sound_footstep, is);
379         deSerializeSimpleSoundSpec(sound_dig, is);
380         deSerializeSimpleSoundSpec(sound_dug, is);
381         rightclickable = readU8(is);
382         drowning = readU8(is);
383         leveled = readU8(is);
384         liquid_range = readU8(is);
385         waving = readU8(is);
386         // If you add anything here, insert it primarily inside the try-catch
387         // block to not need to increase the version.
388         try{
389                 // Stuff below should be moved to correct place in a version that
390                 // otherwise changes the protocol version
391         mesh = deSerializeString(is);
392         collision_box.deSerialize(is);
393         floodable = readU8(is);
394         }catch(SerializationError &e) {};
395 }
396
397 /*
398         CNodeDefManager
399 */
400
401 class CNodeDefManager: public IWritableNodeDefManager {
402 public:
403         CNodeDefManager();
404         virtual ~CNodeDefManager();
405         void clear();
406         virtual IWritableNodeDefManager *clone();
407         inline virtual const ContentFeatures& get(content_t c) const;
408         inline virtual const ContentFeatures& get(const MapNode &n) const;
409         virtual bool getId(const std::string &name, content_t &result) const;
410         virtual content_t getId(const std::string &name) const;
411         virtual void getIds(const std::string &name, std::set<content_t> &result) const;
412         virtual const ContentFeatures& get(const std::string &name) const;
413         content_t allocateId();
414         virtual content_t set(const std::string &name, const ContentFeatures &def);
415         virtual content_t allocateDummy(const std::string &name);
416         virtual void updateAliases(IItemDefManager *idef);
417         virtual void applyTextureOverrides(const std::string &override_filepath);
418         virtual void updateTextures(IGameDef *gamedef,
419                 void (*progress_cbk)(void *progress_args, u32 progress, u32 max_progress),
420                 void *progress_cbk_args);
421         void serialize(std::ostream &os, u16 protocol_version) const;
422         void deSerialize(std::istream &is);
423
424         inline virtual bool getNodeRegistrationStatus() const;
425         inline virtual void setNodeRegistrationStatus(bool completed);
426
427         virtual void pendNodeResolve(NodeResolver *nr);
428         virtual bool cancelNodeResolveCallback(NodeResolver *nr);
429         virtual void runNodeResolveCallbacks();
430         virtual void resetNodeResolveState();
431
432 private:
433         void addNameIdMapping(content_t i, std::string name);
434 #ifndef SERVER
435         void fillTileAttribs(ITextureSource *tsrc, TileSpec *tile, TileDef *tiledef,
436                 u32 shader_id, bool use_normal_texture, bool backface_culling,
437                 u8 alpha, u8 material_type);
438 #endif
439
440         // Features indexed by id
441         std::vector<ContentFeatures> m_content_features;
442
443         // A mapping for fast converting back and forth between names and ids
444         NameIdMapping m_name_id_mapping;
445
446         // Like m_name_id_mapping, but only from names to ids, and includes
447         // item aliases too. Updated by updateAliases()
448         // Note: Not serialized.
449
450         std::map<std::string, content_t> m_name_id_mapping_with_aliases;
451
452         // A mapping from groups to a list of content_ts (and their levels)
453         // that belong to it.  Necessary for a direct lookup in getIds().
454         // Note: Not serialized.
455         std::map<std::string, GroupItems> m_group_to_items;
456
457         // Next possibly free id
458         content_t m_next_id;
459
460         // NodeResolvers to callback once node registration has ended
461         std::vector<NodeResolver *> m_pending_resolve_callbacks;
462
463         // True when all nodes have been registered
464         bool m_node_registration_complete;
465 };
466
467
468 CNodeDefManager::CNodeDefManager()
469 {
470         clear();
471 }
472
473
474 CNodeDefManager::~CNodeDefManager()
475 {
476 #ifndef SERVER
477         for (u32 i = 0; i < m_content_features.size(); i++) {
478                 ContentFeatures *f = &m_content_features[i];
479                 for (u32 j = 0; j < 24; j++) {
480                         if (f->mesh_ptr[j])
481                                 f->mesh_ptr[j]->drop();
482                 }
483         }
484 #endif
485 }
486
487
488 void CNodeDefManager::clear()
489 {
490         m_content_features.clear();
491         m_name_id_mapping.clear();
492         m_name_id_mapping_with_aliases.clear();
493         m_group_to_items.clear();
494         m_next_id = 0;
495
496         resetNodeResolveState();
497
498         u32 initial_length = 0;
499         initial_length = MYMAX(initial_length, CONTENT_UNKNOWN + 1);
500         initial_length = MYMAX(initial_length, CONTENT_AIR + 1);
501         initial_length = MYMAX(initial_length, CONTENT_IGNORE + 1);
502         m_content_features.resize(initial_length);
503
504         // Set CONTENT_UNKNOWN
505         {
506                 ContentFeatures f;
507                 f.name = "unknown";
508                 // Insert directly into containers
509                 content_t c = CONTENT_UNKNOWN;
510                 m_content_features[c] = f;
511                 addNameIdMapping(c, f.name);
512         }
513
514         // Set CONTENT_AIR
515         {
516                 ContentFeatures f;
517                 f.name                = "air";
518                 f.drawtype            = NDT_AIRLIKE;
519                 f.param_type          = CPT_LIGHT;
520                 f.light_propagates    = true;
521                 f.sunlight_propagates = true;
522                 f.walkable            = false;
523                 f.pointable           = false;
524                 f.diggable            = false;
525                 f.buildable_to        = true;
526                 f.floodable           = true;
527                 f.is_ground_content   = true;
528                 // Insert directly into containers
529                 content_t c = CONTENT_AIR;
530                 m_content_features[c] = f;
531                 addNameIdMapping(c, f.name);
532         }
533
534         // Set CONTENT_IGNORE
535         {
536                 ContentFeatures f;
537                 f.name                = "ignore";
538                 f.drawtype            = NDT_AIRLIKE;
539                 f.param_type          = CPT_NONE;
540                 f.light_propagates    = false;
541                 f.sunlight_propagates = false;
542                 f.walkable            = false;
543                 f.pointable           = false;
544                 f.diggable            = false;
545                 f.buildable_to        = true; // A way to remove accidental CONTENT_IGNOREs
546                 f.is_ground_content   = true;
547                 // Insert directly into containers
548                 content_t c = CONTENT_IGNORE;
549                 m_content_features[c] = f;
550                 addNameIdMapping(c, f.name);
551         }
552 }
553
554
555 IWritableNodeDefManager *CNodeDefManager::clone()
556 {
557         CNodeDefManager *mgr = new CNodeDefManager();
558         *mgr = *this;
559         return mgr;
560 }
561
562
563 inline const ContentFeatures& CNodeDefManager::get(content_t c) const
564 {
565         return c < m_content_features.size()
566                         ? m_content_features[c] : m_content_features[CONTENT_UNKNOWN];
567 }
568
569
570 inline const ContentFeatures& CNodeDefManager::get(const MapNode &n) const
571 {
572         return get(n.getContent());
573 }
574
575
576 bool CNodeDefManager::getId(const std::string &name, content_t &result) const
577 {
578         std::map<std::string, content_t>::const_iterator
579                 i = m_name_id_mapping_with_aliases.find(name);
580         if(i == m_name_id_mapping_with_aliases.end())
581                 return false;
582         result = i->second;
583         return true;
584 }
585
586
587 content_t CNodeDefManager::getId(const std::string &name) const
588 {
589         content_t id = CONTENT_IGNORE;
590         getId(name, id);
591         return id;
592 }
593
594
595 void CNodeDefManager::getIds(const std::string &name,
596                 std::set<content_t> &result) const
597 {
598         //TimeTaker t("getIds", NULL, PRECISION_MICRO);
599         if (name.substr(0,6) != "group:") {
600                 content_t id = CONTENT_IGNORE;
601                 if(getId(name, id))
602                         result.insert(id);
603                 return;
604         }
605         std::string group = name.substr(6);
606
607         std::map<std::string, GroupItems>::const_iterator
608                 i = m_group_to_items.find(group);
609         if (i == m_group_to_items.end())
610                 return;
611
612         const GroupItems &items = i->second;
613         for (GroupItems::const_iterator j = items.begin();
614                 j != items.end(); ++j) {
615                 if ((*j).second != 0)
616                         result.insert((*j).first);
617         }
618         //printf("getIds: %dus\n", t.stop());
619 }
620
621
622 const ContentFeatures& CNodeDefManager::get(const std::string &name) const
623 {
624         content_t id = CONTENT_UNKNOWN;
625         getId(name, id);
626         return get(id);
627 }
628
629
630 // returns CONTENT_IGNORE if no free ID found
631 content_t CNodeDefManager::allocateId()
632 {
633         for (content_t id = m_next_id;
634                         id >= m_next_id; // overflow?
635                         ++id) {
636                 while (id >= m_content_features.size()) {
637                         m_content_features.push_back(ContentFeatures());
638                 }
639                 const ContentFeatures &f = m_content_features[id];
640                 if (f.name == "") {
641                         m_next_id = id + 1;
642                         return id;
643                 }
644         }
645         // If we arrive here, an overflow occurred in id.
646         // That means no ID was found
647         return CONTENT_IGNORE;
648 }
649
650
651 // IWritableNodeDefManager
652 content_t CNodeDefManager::set(const std::string &name, const ContentFeatures &def)
653 {
654         // Pre-conditions
655         assert(name != "");
656         assert(name == def.name);
657
658         // Don't allow redefining ignore (but allow air and unknown)
659         if (name == "ignore") {
660                 warningstream << "NodeDefManager: Ignoring "
661                         "CONTENT_IGNORE redefinition"<<std::endl;
662                 return CONTENT_IGNORE;
663         }
664
665         content_t id = CONTENT_IGNORE;
666         if (!m_name_id_mapping.getId(name, id)) { // ignore aliases
667                 // Get new id
668                 id = allocateId();
669                 if (id == CONTENT_IGNORE) {
670                         warningstream << "NodeDefManager: Absolute "
671                                 "limit reached" << std::endl;
672                         return CONTENT_IGNORE;
673                 }
674                 assert(id != CONTENT_IGNORE);
675                 addNameIdMapping(id, name);
676         }
677         m_content_features[id] = def;
678         verbosestream << "NodeDefManager: registering content id \"" << id
679                 << "\": name=\"" << def.name << "\""<<std::endl;
680
681         // Add this content to the list of all groups it belongs to
682         // FIXME: This should remove a node from groups it no longer
683         // belongs to when a node is re-registered
684         for (ItemGroupList::const_iterator i = def.groups.begin();
685                 i != def.groups.end(); ++i) {
686                 std::string group_name = i->first;
687
688                 std::map<std::string, GroupItems>::iterator
689                         j = m_group_to_items.find(group_name);
690                 if (j == m_group_to_items.end()) {
691                         m_group_to_items[group_name].push_back(
692                                 std::make_pair(id, i->second));
693                 } else {
694                         GroupItems &items = j->second;
695                         items.push_back(std::make_pair(id, i->second));
696                 }
697         }
698         return id;
699 }
700
701
702 content_t CNodeDefManager::allocateDummy(const std::string &name)
703 {
704         assert(name != "");     // Pre-condition
705         ContentFeatures f;
706         f.name = name;
707         return set(name, f);
708 }
709
710
711 void CNodeDefManager::updateAliases(IItemDefManager *idef)
712 {
713         std::set<std::string> all = idef->getAll();
714         m_name_id_mapping_with_aliases.clear();
715         for (std::set<std::string>::iterator
716                         i = all.begin(); i != all.end(); ++i) {
717                 std::string name = *i;
718                 std::string convert_to = idef->getAlias(name);
719                 content_t id;
720                 if (m_name_id_mapping.getId(convert_to, id)) {
721                         m_name_id_mapping_with_aliases.insert(
722                                 std::make_pair(name, id));
723                 }
724         }
725 }
726
727 void CNodeDefManager::applyTextureOverrides(const std::string &override_filepath)
728 {
729         infostream << "CNodeDefManager::applyTextureOverrides(): Applying "
730                 "overrides to textures from " << override_filepath << std::endl;
731
732         std::ifstream infile(override_filepath.c_str());
733         std::string line;
734         int line_c = 0;
735         while (std::getline(infile, line)) {
736                 line_c++;
737                 if (trim(line) == "")
738                         continue;
739                 std::vector<std::string> splitted = str_split(line, ' ');
740                 if (splitted.size() != 3) {
741                         errorstream << override_filepath
742                                 << ":" << line_c << " Could not apply texture override \""
743                                 << line << "\": Syntax error" << std::endl;
744                         continue;
745                 }
746
747                 content_t id;
748                 if (!getId(splitted[0], id)) {
749                         errorstream << override_filepath
750                                 << ":" << line_c << " Could not apply texture override \""
751                                 << line << "\": Unknown node \""
752                                 << splitted[0] << "\"" << std::endl;
753                         continue;
754                 }
755
756                 ContentFeatures &nodedef = m_content_features[id];
757
758                 if (splitted[1] == "top")
759                         nodedef.tiledef[0].name = splitted[2];
760                 else if (splitted[1] == "bottom")
761                         nodedef.tiledef[1].name = splitted[2];
762                 else if (splitted[1] == "right")
763                         nodedef.tiledef[2].name = splitted[2];
764                 else if (splitted[1] == "left")
765                         nodedef.tiledef[3].name = splitted[2];
766                 else if (splitted[1] == "back")
767                         nodedef.tiledef[4].name = splitted[2];
768                 else if (splitted[1] == "front")
769                         nodedef.tiledef[5].name = splitted[2];
770                 else if (splitted[1] == "all" || splitted[1] == "*")
771                         for (int i = 0; i < 6; i++)
772                                 nodedef.tiledef[i].name = splitted[2];
773                 else if (splitted[1] == "sides")
774                         for (int i = 2; i < 6; i++)
775                                 nodedef.tiledef[i].name = splitted[2];
776                 else {
777                         errorstream << override_filepath
778                                 << ":" << line_c << " Could not apply texture override \""
779                                 << line << "\": Unknown node side \""
780                                 << splitted[1] << "\"" << std::endl;
781                         continue;
782                 }
783         }
784 }
785
786 void CNodeDefManager::updateTextures(IGameDef *gamedef,
787         void (*progress_callback)(void *progress_args, u32 progress, u32 max_progress),
788         void *progress_callback_args)
789 {
790 #ifndef SERVER
791         infostream << "CNodeDefManager::updateTextures(): Updating "
792                 "textures in node definitions" << std::endl;
793         ITextureSource *tsrc = gamedef->tsrc();
794         IShaderSource *shdsrc = gamedef->getShaderSource();
795         scene::ISceneManager* smgr = gamedef->getSceneManager();
796         scene::IMeshManipulator* meshmanip = smgr->getMeshManipulator();
797
798         bool new_style_water           = g_settings->getBool("new_style_water");
799         bool connected_glass           = g_settings->getBool("connected_glass");
800         bool opaque_water              = g_settings->getBool("opaque_water");
801         bool enable_shaders            = g_settings->getBool("enable_shaders");
802         bool enable_bumpmapping        = g_settings->getBool("enable_bumpmapping");
803         bool enable_parallax_occlusion = g_settings->getBool("enable_parallax_occlusion");
804         bool enable_mesh_cache         = g_settings->getBool("enable_mesh_cache");
805         bool enable_minimap            = g_settings->getBool("enable_minimap");
806         std::string leaves_style       = g_settings->get("leaves_style");
807
808         bool use_normal_texture = enable_shaders &&
809                 (enable_bumpmapping || enable_parallax_occlusion);
810
811         u32 size = m_content_features.size();
812
813         for (u32 i = 0; i < size; i++) {
814                 ContentFeatures *f = &m_content_features[i];
815
816                 // minimap pixel color - the average color of a texture
817                 if (enable_minimap && f->tiledef[0].name != "")
818                         f->minimap_color = tsrc->getTextureAverageColor(f->tiledef[0].name);
819
820                 // Figure out the actual tiles to use
821                 TileDef tiledef[6];
822                 for (u32 j = 0; j < 6; j++) {
823                         tiledef[j] = f->tiledef[j];
824                         if (tiledef[j].name == "")
825                                 tiledef[j].name = "unknown_node.png";
826                 }
827
828                 bool is_liquid = false;
829                 bool is_water_surface = false;
830
831                 u8 material_type = (f->alpha == 255) ?
832                         TILE_MATERIAL_BASIC : TILE_MATERIAL_ALPHA;
833
834                 switch (f->drawtype) {
835                 default:
836                 case NDT_NORMAL:
837                         f->solidness = 2;
838                         break;
839                 case NDT_AIRLIKE:
840                         f->solidness = 0;
841                         break;
842                 case NDT_LIQUID:
843                         assert(f->liquid_type == LIQUID_SOURCE);
844                         if (opaque_water)
845                                 f->alpha = 255;
846                         if (new_style_water){
847                                 f->solidness = 0;
848                         } else {
849                                 f->solidness = 1;
850                                 f->backface_culling = false;
851                         }
852                         is_liquid = true;
853                         break;
854                 case NDT_FLOWINGLIQUID:
855                         assert(f->liquid_type == LIQUID_FLOWING);
856                         f->solidness = 0;
857                         if (opaque_water)
858                                 f->alpha = 255;
859                         is_liquid = true;
860                         break;
861                 case NDT_GLASSLIKE:
862                         f->solidness = 0;
863                         f->visual_solidness = 1;
864                         break;
865                 case NDT_GLASSLIKE_FRAMED:
866                         f->solidness = 0;
867                         f->visual_solidness = 1;
868                         break;
869                 case NDT_GLASSLIKE_FRAMED_OPTIONAL:
870                         f->solidness = 0;
871                         f->visual_solidness = 1;
872                         f->drawtype = connected_glass ? NDT_GLASSLIKE_FRAMED : NDT_GLASSLIKE;
873                         break;
874                 case NDT_ALLFACES:
875                         f->solidness = 0;
876                         f->visual_solidness = 1;
877                         break;
878                 case NDT_ALLFACES_OPTIONAL:
879                         if (leaves_style == "fancy") {
880                                 f->drawtype = NDT_ALLFACES;
881                                 f->solidness = 0;
882                                 f->visual_solidness = 1;
883                         } else if (leaves_style == "simple") {
884                                 for (u32 j = 0; j < 6; j++) {
885                                         if (f->tiledef_special[j].name != "")
886                                                 tiledef[j].name = f->tiledef_special[j].name;
887                                 }
888                                 f->drawtype = NDT_GLASSLIKE;
889                                 f->solidness = 0;
890                                 f->visual_solidness = 1;
891                         } else {
892                                 f->drawtype = NDT_NORMAL;
893                                 f->solidness = 2;
894                                 for (u32 i = 0; i < 6; i++)
895                                         tiledef[i].name += std::string("^[noalpha");
896                         }
897                         if (f->waving == 1)
898                                 material_type = TILE_MATERIAL_WAVING_LEAVES;
899                         break;
900                 case NDT_PLANTLIKE:
901                         f->solidness = 0;
902                         f->backface_culling = false;
903                         if (f->waving == 1)
904                                 material_type = TILE_MATERIAL_WAVING_PLANTS;
905                         break;
906                 case NDT_FIRELIKE:
907                         f->backface_culling = false;
908                         f->solidness = 0;
909                         break;
910                 case NDT_MESH:
911                         f->solidness = 0;
912                         f->backface_culling = false;
913                         break;
914                 case NDT_TORCHLIKE:
915                 case NDT_SIGNLIKE:
916                 case NDT_FENCELIKE:
917                 case NDT_RAILLIKE:
918                 case NDT_NODEBOX:
919                         f->solidness = 0;
920                         break;
921                 }
922
923                 if (is_liquid) {
924                         material_type = (f->alpha == 255) ?
925                                 TILE_MATERIAL_LIQUID_OPAQUE : TILE_MATERIAL_LIQUID_TRANSPARENT;
926                         if (f->name == "default:water_source")
927                                 is_water_surface = true;
928                 }
929
930                 u32 tile_shader[6];
931                 for (u16 j = 0; j < 6; j++) {
932                         tile_shader[j] = shdsrc->getShader("nodes_shader",
933                                 material_type, f->drawtype);
934                 }
935
936                 if (is_water_surface) {
937                         tile_shader[0] = shdsrc->getShader("water_surface_shader",
938                                 material_type, f->drawtype);
939                 }
940
941                 // Tiles (fill in f->tiles[])
942                 for (u16 j = 0; j < 6; j++) {
943                         fillTileAttribs(tsrc, &f->tiles[j], &tiledef[j], tile_shader[j],
944                                 use_normal_texture, f->backface_culling, f->alpha, material_type);
945                 }
946
947                 // Special tiles (fill in f->special_tiles[])
948                 for (u16 j = 0; j < CF_SPECIAL_COUNT; j++) {
949                         fillTileAttribs(tsrc, &f->special_tiles[j], &f->tiledef_special[j],
950                                 tile_shader[j], use_normal_texture,
951                                 f->tiledef_special[j].backface_culling, f->alpha, material_type);
952                 }
953
954                 if ((f->drawtype == NDT_MESH) && (f->mesh != "")) {
955                         // Meshnode drawtype
956                         // Read the mesh and apply scale
957                         f->mesh_ptr[0] = gamedef->getMesh(f->mesh);
958                         if (f->mesh_ptr[0]){
959                                 v3f scale = v3f(1.0, 1.0, 1.0) * BS * f->visual_scale;
960                                 scaleMesh(f->mesh_ptr[0], scale);
961                                 recalculateBoundingBox(f->mesh_ptr[0]);
962                                 meshmanip->recalculateNormals(f->mesh_ptr[0], true, false);
963                         }
964                 } else if ((f->drawtype == NDT_NODEBOX) &&
965                                 ((f->node_box.type == NODEBOX_REGULAR) ||
966                                 (f->node_box.type == NODEBOX_FIXED)) &&
967                                 (!f->node_box.fixed.empty())) {
968                         //Convert regular nodebox nodes to meshnodes
969                         //Change the drawtype and apply scale
970                         f->drawtype = NDT_MESH;
971                         f->mesh_ptr[0] = convertNodeboxNodeToMesh(f);
972                         v3f scale = v3f(1.0, 1.0, 1.0) * f->visual_scale;
973                         scaleMesh(f->mesh_ptr[0], scale);
974                         recalculateBoundingBox(f->mesh_ptr[0]);
975                         meshmanip->recalculateNormals(f->mesh_ptr[0], true, false);
976                 }
977
978                 //Cache 6dfacedir and wallmounted rotated clones of meshes
979                 if (enable_mesh_cache && f->mesh_ptr[0] && (f->param_type_2 == CPT2_FACEDIR)) {
980                         for (u16 j = 1; j < 24; j++) {
981                                 f->mesh_ptr[j] = cloneMesh(f->mesh_ptr[0]);
982                                 rotateMeshBy6dFacedir(f->mesh_ptr[j], j);
983                                 recalculateBoundingBox(f->mesh_ptr[j]);
984                                 meshmanip->recalculateNormals(f->mesh_ptr[j], true, false);
985                         }
986                 } else if (enable_mesh_cache && f->mesh_ptr[0] && (f->param_type_2 == CPT2_WALLMOUNTED)) {
987                         static const u8 wm_to_6d[6] = {20, 0, 16+1, 12+3, 8, 4+2};
988                         for (u16 j = 1; j < 6; j++) {
989                                 f->mesh_ptr[j] = cloneMesh(f->mesh_ptr[0]);
990                                 rotateMeshBy6dFacedir(f->mesh_ptr[j], wm_to_6d[j]);
991                                 recalculateBoundingBox(f->mesh_ptr[j]);
992                                 meshmanip->recalculateNormals(f->mesh_ptr[j], true, false);
993                         }
994                         rotateMeshBy6dFacedir(f->mesh_ptr[0], wm_to_6d[0]);
995                         recalculateBoundingBox(f->mesh_ptr[0]);
996                         meshmanip->recalculateNormals(f->mesh_ptr[0], true, false);
997                 }
998
999                 progress_callback(progress_callback_args, i, size);
1000         }
1001 #endif
1002 }
1003
1004
1005 #ifndef SERVER
1006 void CNodeDefManager::fillTileAttribs(ITextureSource *tsrc, TileSpec *tile,
1007                 TileDef *tiledef, u32 shader_id, bool use_normal_texture,
1008                 bool backface_culling, u8 alpha, u8 material_type)
1009 {
1010         tile->shader_id     = shader_id;
1011         tile->texture       = tsrc->getTextureForMesh(tiledef->name, &tile->texture_id);
1012         tile->alpha         = alpha;
1013         tile->material_type = material_type;
1014
1015         // Normal texture and shader flags texture
1016         if (use_normal_texture) {
1017                 tile->normal_texture = tsrc->getNormalTexture(tiledef->name);
1018         }
1019         tile->flags_texture = tsrc->getShaderFlagsTexture(tile->normal_texture ? true : false);
1020
1021         // Material flags
1022         tile->material_flags = 0;
1023         if (backface_culling)
1024                 tile->material_flags |= MATERIAL_FLAG_BACKFACE_CULLING;
1025         if (tiledef->animation.type == TAT_VERTICAL_FRAMES)
1026                 tile->material_flags |= MATERIAL_FLAG_ANIMATION_VERTICAL_FRAMES;
1027         if (tiledef->tileable_horizontal)
1028                 tile->material_flags |= MATERIAL_FLAG_TILEABLE_HORIZONTAL;
1029         if (tiledef->tileable_vertical)
1030                 tile->material_flags |= MATERIAL_FLAG_TILEABLE_VERTICAL;
1031
1032         // Animation parameters
1033         int frame_count = 1;
1034         if (tile->material_flags & MATERIAL_FLAG_ANIMATION_VERTICAL_FRAMES) {
1035                 // Get texture size to determine frame count by aspect ratio
1036                 v2u32 size = tile->texture->getOriginalSize();
1037                 int frame_height = (float)size.X /
1038                                 (float)tiledef->animation.aspect_w *
1039                                 (float)tiledef->animation.aspect_h;
1040                 frame_count = size.Y / frame_height;
1041                 int frame_length_ms = 1000.0 * tiledef->animation.length / frame_count;
1042                 tile->animation_frame_count = frame_count;
1043                 tile->animation_frame_length_ms = frame_length_ms;
1044         }
1045
1046         if (frame_count == 1) {
1047                 tile->material_flags &= ~MATERIAL_FLAG_ANIMATION_VERTICAL_FRAMES;
1048         } else {
1049                 std::ostringstream os(std::ios::binary);
1050                 tile->frames.resize(frame_count);
1051
1052                 for (int i = 0; i < frame_count; i++) {
1053
1054                         FrameSpec frame;
1055
1056                         os.str("");
1057                         os << tiledef->name << "^[verticalframe:"
1058                                 << frame_count << ":" << i;
1059
1060                         frame.texture = tsrc->getTextureForMesh(os.str(), &frame.texture_id);
1061                         if (tile->normal_texture)
1062                                 frame.normal_texture = tsrc->getNormalTexture(os.str());
1063                         frame.flags_texture = tile->flags_texture;
1064                         tile->frames[i] = frame;
1065                 }
1066         }
1067 }
1068 #endif
1069
1070
1071 void CNodeDefManager::serialize(std::ostream &os, u16 protocol_version) const
1072 {
1073         writeU8(os, 1); // version
1074         u16 count = 0;
1075         std::ostringstream os2(std::ios::binary);
1076         for (u32 i = 0; i < m_content_features.size(); i++) {
1077                 if (i == CONTENT_IGNORE || i == CONTENT_AIR
1078                                 || i == CONTENT_UNKNOWN)
1079                         continue;
1080                 const ContentFeatures *f = &m_content_features[i];
1081                 if (f->name == "")
1082                         continue;
1083                 writeU16(os2, i);
1084                 // Wrap it in a string to allow different lengths without
1085                 // strict version incompatibilities
1086                 std::ostringstream wrapper_os(std::ios::binary);
1087                 f->serialize(wrapper_os, protocol_version);
1088                 os2<<serializeString(wrapper_os.str());
1089
1090                 // must not overflow
1091                 u16 next = count + 1;
1092                 FATAL_ERROR_IF(next < count, "Overflow");
1093                 count++;
1094         }
1095         writeU16(os, count);
1096         os << serializeLongString(os2.str());
1097 }
1098
1099
1100 void CNodeDefManager::deSerialize(std::istream &is)
1101 {
1102         clear();
1103         int version = readU8(is);
1104         if (version != 1)
1105                 throw SerializationError("unsupported NodeDefinitionManager version");
1106         u16 count = readU16(is);
1107         std::istringstream is2(deSerializeLongString(is), std::ios::binary);
1108         ContentFeatures f;
1109         for (u16 n = 0; n < count; n++) {
1110                 u16 i = readU16(is2);
1111
1112                 // Read it from the string wrapper
1113                 std::string wrapper = deSerializeString(is2);
1114                 std::istringstream wrapper_is(wrapper, std::ios::binary);
1115                 f.deSerialize(wrapper_is);
1116
1117                 // Check error conditions
1118                 if (i == CONTENT_IGNORE || i == CONTENT_AIR || i == CONTENT_UNKNOWN) {
1119                         warningstream << "NodeDefManager::deSerialize(): "
1120                                 "not changing builtin node " << i << std::endl;
1121                         continue;
1122                 }
1123                 if (f.name == "") {
1124                         warningstream << "NodeDefManager::deSerialize(): "
1125                                 "received empty name" << std::endl;
1126                         continue;
1127                 }
1128
1129                 // Ignore aliases
1130                 u16 existing_id;
1131                 if (m_name_id_mapping.getId(f.name, existing_id) && i != existing_id) {
1132                         warningstream << "NodeDefManager::deSerialize(): "
1133                                 "already defined with different ID: " << f.name << std::endl;
1134                         continue;
1135                 }
1136
1137                 // All is ok, add node definition with the requested ID
1138                 if (i >= m_content_features.size())
1139                         m_content_features.resize((u32)(i) + 1);
1140                 m_content_features[i] = f;
1141                 addNameIdMapping(i, f.name);
1142                 verbosestream << "deserialized " << f.name << std::endl;
1143         }
1144 }
1145
1146
1147 void CNodeDefManager::addNameIdMapping(content_t i, std::string name)
1148 {
1149         m_name_id_mapping.set(i, name);
1150         m_name_id_mapping_with_aliases.insert(std::make_pair(name, i));
1151 }
1152
1153
1154 IWritableNodeDefManager *createNodeDefManager()
1155 {
1156         return new CNodeDefManager();
1157 }
1158
1159
1160 //// Serialization of old ContentFeatures formats
1161 void ContentFeatures::serializeOld(std::ostream &os, u16 protocol_version) const
1162 {
1163         if (protocol_version == 13)
1164         {
1165                 writeU8(os, 5); // version
1166                 os<<serializeString(name);
1167                 writeU16(os, groups.size());
1168                 for (ItemGroupList::const_iterator
1169                                 i = groups.begin(); i != groups.end(); ++i) {
1170                         os<<serializeString(i->first);
1171                         writeS16(os, i->second);
1172                 }
1173                 writeU8(os, drawtype);
1174                 writeF1000(os, visual_scale);
1175                 writeU8(os, 6);
1176                 for (u32 i = 0; i < 6; i++)
1177                         tiledef[i].serialize(os, protocol_version);
1178                 //CF_SPECIAL_COUNT = 2 before cf ver. 7 and protocol ver. 24
1179                 writeU8(os, 2);
1180                 for (u32 i = 0; i < 2; i++)
1181                         tiledef_special[i].serialize(os, protocol_version);
1182                 writeU8(os, alpha);
1183                 writeU8(os, post_effect_color.getAlpha());
1184                 writeU8(os, post_effect_color.getRed());
1185                 writeU8(os, post_effect_color.getGreen());
1186                 writeU8(os, post_effect_color.getBlue());
1187                 writeU8(os, param_type);
1188                 writeU8(os, param_type_2);
1189                 writeU8(os, is_ground_content);
1190                 writeU8(os, light_propagates);
1191                 writeU8(os, sunlight_propagates);
1192                 writeU8(os, walkable);
1193                 writeU8(os, pointable);
1194                 writeU8(os, diggable);
1195                 writeU8(os, climbable);
1196                 writeU8(os, buildable_to);
1197                 os<<serializeString(""); // legacy: used to be metadata_name
1198                 writeU8(os, liquid_type);
1199                 os<<serializeString(liquid_alternative_flowing);
1200                 os<<serializeString(liquid_alternative_source);
1201                 writeU8(os, liquid_viscosity);
1202                 writeU8(os, light_source);
1203                 writeU32(os, damage_per_second);
1204                 node_box.serialize(os, protocol_version);
1205                 selection_box.serialize(os, protocol_version);
1206                 writeU8(os, legacy_facedir_simple);
1207                 writeU8(os, legacy_wallmounted);
1208                 serializeSimpleSoundSpec(sound_footstep, os);
1209                 serializeSimpleSoundSpec(sound_dig, os);
1210                 serializeSimpleSoundSpec(sound_dug, os);
1211         }
1212         else if (protocol_version > 13 && protocol_version < 24) {
1213                 writeU8(os, 6); // version
1214                 os<<serializeString(name);
1215                 writeU16(os, groups.size());
1216                 for (ItemGroupList::const_iterator
1217                         i = groups.begin(); i != groups.end(); ++i) {
1218                                 os<<serializeString(i->first);
1219                                 writeS16(os, i->second);
1220                 }
1221                 writeU8(os, drawtype);
1222                 writeF1000(os, visual_scale);
1223                 writeU8(os, 6);
1224                 for (u32 i = 0; i < 6; i++)
1225                         tiledef[i].serialize(os, protocol_version);
1226                 //CF_SPECIAL_COUNT = 2 before cf ver. 7 and protocol ver. 24
1227                 writeU8(os, 2);
1228                 for (u32 i = 0; i < 2; i++)
1229                         tiledef_special[i].serialize(os, protocol_version);
1230                 writeU8(os, alpha);
1231                 writeU8(os, post_effect_color.getAlpha());
1232                 writeU8(os, post_effect_color.getRed());
1233                 writeU8(os, post_effect_color.getGreen());
1234                 writeU8(os, post_effect_color.getBlue());
1235                 writeU8(os, param_type);
1236                 writeU8(os, param_type_2);
1237                 writeU8(os, is_ground_content);
1238                 writeU8(os, light_propagates);
1239                 writeU8(os, sunlight_propagates);
1240                 writeU8(os, walkable);
1241                 writeU8(os, pointable);
1242                 writeU8(os, diggable);
1243                 writeU8(os, climbable);
1244                 writeU8(os, buildable_to);
1245                 os<<serializeString(""); // legacy: used to be metadata_name
1246                 writeU8(os, liquid_type);
1247                 os<<serializeString(liquid_alternative_flowing);
1248                 os<<serializeString(liquid_alternative_source);
1249                 writeU8(os, liquid_viscosity);
1250                 writeU8(os, liquid_renewable);
1251                 writeU8(os, light_source);
1252                 writeU32(os, damage_per_second);
1253                 node_box.serialize(os, protocol_version);
1254                 selection_box.serialize(os, protocol_version);
1255                 writeU8(os, legacy_facedir_simple);
1256                 writeU8(os, legacy_wallmounted);
1257                 serializeSimpleSoundSpec(sound_footstep, os);
1258                 serializeSimpleSoundSpec(sound_dig, os);
1259                 serializeSimpleSoundSpec(sound_dug, os);
1260                 writeU8(os, rightclickable);
1261                 writeU8(os, drowning);
1262                 writeU8(os, leveled);
1263                 writeU8(os, liquid_range);
1264         } else
1265                 throw SerializationError("ContentFeatures::serialize(): "
1266                         "Unsupported version requested");
1267 }
1268
1269
1270 void ContentFeatures::deSerializeOld(std::istream &is, int version)
1271 {
1272         if (version == 5) // In PROTOCOL_VERSION 13
1273         {
1274                 name = deSerializeString(is);
1275                 groups.clear();
1276                 u32 groups_size = readU16(is);
1277                 for(u32 i=0; i<groups_size; i++){
1278                         std::string name = deSerializeString(is);
1279                         int value = readS16(is);
1280                         groups[name] = value;
1281                 }
1282                 drawtype = (enum NodeDrawType)readU8(is);
1283                 visual_scale = readF1000(is);
1284                 if (readU8(is) != 6)
1285                         throw SerializationError("unsupported tile count");
1286                 for (u32 i = 0; i < 6; i++)
1287                         tiledef[i].deSerialize(is);
1288                 if (readU8(is) != CF_SPECIAL_COUNT)
1289                         throw SerializationError("unsupported CF_SPECIAL_COUNT");
1290                 for (u32 i = 0; i < CF_SPECIAL_COUNT; i++)
1291                         tiledef_special[i].deSerialize(is);
1292                 alpha = readU8(is);
1293                 post_effect_color.setAlpha(readU8(is));
1294                 post_effect_color.setRed(readU8(is));
1295                 post_effect_color.setGreen(readU8(is));
1296                 post_effect_color.setBlue(readU8(is));
1297                 param_type = (enum ContentParamType)readU8(is);
1298                 param_type_2 = (enum ContentParamType2)readU8(is);
1299                 is_ground_content = readU8(is);
1300                 light_propagates = readU8(is);
1301                 sunlight_propagates = readU8(is);
1302                 walkable = readU8(is);
1303                 pointable = readU8(is);
1304                 diggable = readU8(is);
1305                 climbable = readU8(is);
1306                 buildable_to = readU8(is);
1307                 deSerializeString(is); // legacy: used to be metadata_name
1308                 liquid_type = (enum LiquidType)readU8(is);
1309                 liquid_alternative_flowing = deSerializeString(is);
1310                 liquid_alternative_source = deSerializeString(is);
1311                 liquid_viscosity = readU8(is);
1312                 light_source = readU8(is);
1313                 damage_per_second = readU32(is);
1314                 node_box.deSerialize(is);
1315                 selection_box.deSerialize(is);
1316                 legacy_facedir_simple = readU8(is);
1317                 legacy_wallmounted = readU8(is);
1318                 deSerializeSimpleSoundSpec(sound_footstep, is);
1319                 deSerializeSimpleSoundSpec(sound_dig, is);
1320                 deSerializeSimpleSoundSpec(sound_dug, is);
1321         } else if (version == 6) {
1322                 name = deSerializeString(is);
1323                 groups.clear();
1324                 u32 groups_size = readU16(is);
1325                 for (u32 i = 0; i < groups_size; i++) {
1326                         std::string name = deSerializeString(is);
1327                         int     value = readS16(is);
1328                         groups[name] = value;
1329                 }
1330                 drawtype = (enum NodeDrawType)readU8(is);
1331                 visual_scale = readF1000(is);
1332                 if (readU8(is) != 6)
1333                         throw SerializationError("unsupported tile count");
1334                 for (u32 i = 0; i < 6; i++)
1335                         tiledef[i].deSerialize(is);
1336                 // CF_SPECIAL_COUNT in version 6 = 2
1337                 if (readU8(is) != 2)
1338                         throw SerializationError("unsupported CF_SPECIAL_COUNT");
1339                 for (u32 i = 0; i < 2; i++)
1340                         tiledef_special[i].deSerialize(is);
1341                 alpha = readU8(is);
1342                 post_effect_color.setAlpha(readU8(is));
1343                 post_effect_color.setRed(readU8(is));
1344                 post_effect_color.setGreen(readU8(is));
1345                 post_effect_color.setBlue(readU8(is));
1346                 param_type = (enum ContentParamType)readU8(is);
1347                 param_type_2 = (enum ContentParamType2)readU8(is);
1348                 is_ground_content = readU8(is);
1349                 light_propagates = readU8(is);
1350                 sunlight_propagates = readU8(is);
1351                 walkable = readU8(is);
1352                 pointable = readU8(is);
1353                 diggable = readU8(is);
1354                 climbable = readU8(is);
1355                 buildable_to = readU8(is);
1356                 deSerializeString(is); // legacy: used to be metadata_name
1357                 liquid_type = (enum LiquidType)readU8(is);
1358                 liquid_alternative_flowing = deSerializeString(is);
1359                 liquid_alternative_source = deSerializeString(is);
1360                 liquid_viscosity = readU8(is);
1361                 liquid_renewable = readU8(is);
1362                 light_source = readU8(is);
1363                 damage_per_second = readU32(is);
1364                 node_box.deSerialize(is);
1365                 selection_box.deSerialize(is);
1366                 legacy_facedir_simple = readU8(is);
1367                 legacy_wallmounted = readU8(is);
1368                 deSerializeSimpleSoundSpec(sound_footstep, is);
1369                 deSerializeSimpleSoundSpec(sound_dig, is);
1370                 deSerializeSimpleSoundSpec(sound_dug, is);
1371                 rightclickable = readU8(is);
1372                 drowning = readU8(is);
1373                 leveled = readU8(is);
1374                 liquid_range = readU8(is);
1375         } else {
1376                 throw SerializationError("unsupported ContentFeatures version");
1377         }
1378 }
1379
1380
1381 inline bool CNodeDefManager::getNodeRegistrationStatus() const
1382 {
1383         return m_node_registration_complete;
1384 }
1385
1386
1387 inline void CNodeDefManager::setNodeRegistrationStatus(bool completed)
1388 {
1389         m_node_registration_complete = completed;
1390 }
1391
1392
1393 void CNodeDefManager::pendNodeResolve(NodeResolver *nr)
1394 {
1395         nr->m_ndef = this;
1396         if (m_node_registration_complete)
1397                 nr->nodeResolveInternal();
1398         else
1399                 m_pending_resolve_callbacks.push_back(nr);
1400 }
1401
1402
1403 bool CNodeDefManager::cancelNodeResolveCallback(NodeResolver *nr)
1404 {
1405         size_t len = m_pending_resolve_callbacks.size();
1406         for (size_t i = 0; i != len; i++) {
1407                 if (nr != m_pending_resolve_callbacks[i])
1408                         continue;
1409
1410                 len--;
1411                 m_pending_resolve_callbacks[i] = m_pending_resolve_callbacks[len];
1412                 m_pending_resolve_callbacks.resize(len);
1413                 return true;
1414         }
1415
1416         return false;
1417 }
1418
1419
1420 void CNodeDefManager::runNodeResolveCallbacks()
1421 {
1422         for (size_t i = 0; i != m_pending_resolve_callbacks.size(); i++) {
1423                 NodeResolver *nr = m_pending_resolve_callbacks[i];
1424                 nr->nodeResolveInternal();
1425         }
1426
1427         m_pending_resolve_callbacks.clear();
1428 }
1429
1430
1431 void CNodeDefManager::resetNodeResolveState()
1432 {
1433         m_node_registration_complete = false;
1434         m_pending_resolve_callbacks.clear();
1435 }
1436
1437
1438 ////
1439 //// NodeResolver
1440 ////
1441
1442 NodeResolver::NodeResolver()
1443 {
1444         m_ndef            = NULL;
1445         m_nodenames_idx   = 0;
1446         m_nnlistsizes_idx = 0;
1447         m_resolve_done    = false;
1448
1449         m_nodenames.reserve(16);
1450         m_nnlistsizes.reserve(4);
1451 }
1452
1453
1454 NodeResolver::~NodeResolver()
1455 {
1456         if (!m_resolve_done && m_ndef)
1457                 m_ndef->cancelNodeResolveCallback(this);
1458 }
1459
1460
1461 void NodeResolver::nodeResolveInternal()
1462 {
1463         m_nodenames_idx   = 0;
1464         m_nnlistsizes_idx = 0;
1465
1466         resolveNodeNames();
1467         m_resolve_done = true;
1468
1469         m_nodenames.clear();
1470         m_nnlistsizes.clear();
1471 }
1472
1473
1474 bool NodeResolver::getIdFromNrBacklog(content_t *result_out,
1475         const std::string &node_alt, content_t c_fallback)
1476 {
1477         if (m_nodenames_idx == m_nodenames.size()) {
1478                 *result_out = c_fallback;
1479                 errorstream << "NodeResolver: no more nodes in list" << std::endl;
1480                 return false;
1481         }
1482
1483         content_t c;
1484         std::string name = m_nodenames[m_nodenames_idx++];
1485
1486         bool success = m_ndef->getId(name, c);
1487         if (!success && node_alt != "") {
1488                 name = node_alt;
1489                 success = m_ndef->getId(name, c);
1490         }
1491
1492         if (!success) {
1493                 errorstream << "NodeResolver: failed to resolve node name '" << name
1494                         << "'." << std::endl;
1495                 c = c_fallback;
1496         }
1497
1498         *result_out = c;
1499         return success;
1500 }
1501
1502
1503 bool NodeResolver::getIdsFromNrBacklog(std::vector<content_t> *result_out,
1504         bool all_required, content_t c_fallback)
1505 {
1506         bool success = true;
1507
1508         if (m_nnlistsizes_idx == m_nnlistsizes.size()) {
1509                 errorstream << "NodeResolver: no more node lists" << std::endl;
1510                 return false;
1511         }
1512
1513         size_t length = m_nnlistsizes[m_nnlistsizes_idx++];
1514
1515         while (length--) {
1516                 if (m_nodenames_idx == m_nodenames.size()) {
1517                         errorstream << "NodeResolver: no more nodes in list" << std::endl;
1518                         return false;
1519                 }
1520
1521                 content_t c;
1522                 std::string &name = m_nodenames[m_nodenames_idx++];
1523
1524                 if (name.substr(0,6) != "group:") {
1525                         if (m_ndef->getId(name, c)) {
1526                                 result_out->push_back(c);
1527                         } else if (all_required) {
1528                                 errorstream << "NodeResolver: failed to resolve node name '"
1529                                         << name << "'." << std::endl;
1530                                 result_out->push_back(c_fallback);
1531                                 success = false;
1532                         }
1533                 } else {
1534                         std::set<content_t> cids;
1535                         std::set<content_t>::iterator it;
1536                         m_ndef->getIds(name, cids);
1537                         for (it = cids.begin(); it != cids.end(); ++it)
1538                                 result_out->push_back(*it);
1539                 }
1540         }
1541
1542         return success;
1543 }