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