3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
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.
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.
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.
22 #include "irrlichttypes_bloated.h"
27 #include "nameidmapping.h"
29 #include "client/tile.h"
30 #include <IMeshManipulator.h>
33 #include "itemgroup.h"
34 #include "sound.h" // SimpleSoundSpec
35 #include "constants.h" // BS
36 #include "texture_override.h" // TextureOverride
37 #include "tileanimation.h"
39 // PROTOCOL_VERSION >= 37
40 static const u8 CONTENTFEATURES_VERSION = 13;
42 class IItemDefManager;
57 enum ContentParamType2
62 // Flowing liquid properties
64 // Direction for chests and furnaces and such
66 // Direction for signs, torches and such
68 // Block level like FLOWINGLIQUID
72 // Mesh options for plants
76 // 3 bits of palette index, then facedir
78 // 5 bits of palette index, then wallmounted
79 CPT2_COLORED_WALLMOUNTED,
80 // Glasslike framed drawtype internal liquid level, param2 values 0 to 63
81 CPT2_GLASSLIKE_LIQUID_LEVEL,
82 // 3 bits of palette index, then degrotate
83 CPT2_COLORED_DEGROTATE,
95 NODEBOX_REGULAR, // Regular block; allows buildable_to
96 NODEBOX_FIXED, // Static separately defined box(es)
97 NODEBOX_WALLMOUNTED, // Box for wall mounted nodes; (top, bottom, side)
98 NODEBOX_LEVELED, // Same as fixed, but with dynamic height from param2. for snow, ...
99 NODEBOX_CONNECTED, // optionally draws nodeboxes if a neighbor node attaches
104 enum NodeBoxType type;
105 // NODEBOX_REGULAR (no parameters)
107 std::vector<aabb3f> fixed;
108 // NODEBOX_WALLMOUNTED
111 aabb3f wall_side; // being at the -X side
113 std::vector<aabb3f> connect_top;
114 std::vector<aabb3f> connect_bottom;
115 std::vector<aabb3f> connect_front;
116 std::vector<aabb3f> connect_left;
117 std::vector<aabb3f> connect_back;
118 std::vector<aabb3f> connect_right;
119 std::vector<aabb3f> disconnected_top;
120 std::vector<aabb3f> disconnected_bottom;
121 std::vector<aabb3f> disconnected_front;
122 std::vector<aabb3f> disconnected_left;
123 std::vector<aabb3f> disconnected_back;
124 std::vector<aabb3f> disconnected_right;
125 std::vector<aabb3f> disconnected;
126 std::vector<aabb3f> disconnected_sides;
132 void serialize(std::ostream &os, u16 protocol_version) const;
133 void deSerialize(std::istream &is);
145 enum AutoScale : u8 {
151 enum WorldAlignMode : u8 {
155 WORLDALIGN_FORCE_NODEBOX,
158 class TextureSettings {
160 LeavesStyle leaves_style;
161 WorldAlignMode world_aligned_mode;
162 AutoScale autoscale_mode;
163 int node_texture_size;
165 bool connected_glass;
166 bool enable_mesh_cache;
169 TextureSettings() = default;
176 // A basic solid block
180 // Do not draw face towards same kind of flowing/source liquid
182 // A very special kind of thing
184 // Glass-like, don't draw faces towards other glass
186 // Leaves-like, draw all faces no matter what
188 // Enabled -> ndt_allfaces, disabled -> ndt_normal
189 NDT_ALLFACES_OPTIONAL,
190 // Single plane perpendicular to a surface
192 // Single plane parallel to a surface
194 // 2 vertical planes in a 'X' shape diagonal to XZ axes.
195 // paramtype2 = "meshoptions" allows various forms, sizes and
196 // vertical and horizontal random offsets.
198 // Fenceposts that connect to neighbouring fenceposts with horizontal bars
200 // Selects appropriate junction texture to connect like rails to
201 // neighbouring raillikes.
203 // Custom Lua-definable structure of multiple cuboids
205 // Glass-like, draw connected frames and all visible faces.
206 // param2 > 0 defines 64 levels of internal liquid
207 // Uses 3 textures, one for frames, second for faces,
208 // optional third is a 'special tile' for the liquid.
209 NDT_GLASSLIKE_FRAMED,
210 // Draw faces slightly rotated and only on neighbouring nodes
212 // Enabled -> ndt_glasslike_framed, disabled -> ndt_glasslike
213 NDT_GLASSLIKE_FRAMED_OPTIONAL,
214 // Uses static meshes
216 // Combined plantlike-on-solid
217 NDT_PLANTLIKE_ROOTED,
220 // Mesh options for NDT_PLANTLIKE with CPT2_MESHOPTIONS
221 static const u8 MO_MASK_STYLE = 0x07;
222 static const u8 MO_BIT_RANDOM_OFFSET = 0x08;
223 static const u8 MO_BIT_SCALE_SQRT2 = 0x10;
224 static const u8 MO_BIT_RANDOM_OFFSET_Y = 0x20;
225 enum PlantlikeStyle {
233 enum AlignStyle : u8 {
236 ALIGN_STYLE_USER_DEFINED,
239 enum AlphaMode : u8 {
243 ALPHAMODE_LEGACY_COMPAT, /* means either opaque or clip */
248 Stand-alone definition of a TileSpec (basically a server-side TileSpec)
253 std::string name = "";
254 bool backface_culling = true; // Takes effect only in special cases
255 bool tileable_horizontal = true;
256 bool tileable_vertical = true;
257 //! If true, the tile has its own color.
258 bool has_color = false;
259 //! The color of the tile.
260 video::SColor color = video::SColor(0xFFFFFFFF);
261 AlignStyle align_style = ALIGN_STYLE_NODE;
264 struct TileAnimationParams animation;
268 animation.type = TAT_NONE;
271 void serialize(std::ostream &os, u16 protocol_version) const;
272 void deSerialize(std::istream &is, u8 contentfeatures_version,
273 NodeDrawType drawtype);
276 // Defines the number of special tiles per nodedef
278 // NOTE: When changing this value, the enum entries of OverrideTarget and
279 // parser in TextureOverrideSource must be updated so that all special
280 // tiles can be overridden.
281 #define CF_SPECIAL_COUNT 6
283 struct ContentFeatures
290 // up down right left back front
293 // - Currently used for flowing liquids
294 TileSpec special_tiles[CF_SPECIAL_COUNT];
295 u8 solidness; // Used when choosing which face is drawn
296 u8 visual_solidness; // When solidness=0, this tells how it looks like
297 bool backface_culling;
300 // Server-side cached callback existence for fast skipping
301 bool has_on_construct;
302 bool has_on_destruct;
303 bool has_after_destruct;
309 // --- GENERAL PROPERTIES ---
311 std::string name; // "" = undefined node
312 ItemGroupList groups; // Same as in itemdef
313 // Type of MapNode::param1
314 ContentParamType param_type;
315 // Type of MapNode::param2
316 ContentParamType2 param_type_2;
318 // --- VISUAL PROPERTIES ---
320 enum NodeDrawType drawtype;
323 scene::IMesh *mesh_ptr[24];
324 video::SColor minimap_color;
326 float visual_scale; // Misc. scale parameter
328 // These will be drawn over the base tiles.
329 TileDef tiledef_overlay[6];
330 TileDef tiledef_special[CF_SPECIAL_COUNT]; // eg. flowing liquid
332 // The color of the node.
334 std::string palette_name;
335 std::vector<video::SColor> *palette;
336 // Used for waving leaves/plants
338 // for NDT_CONNECTED pairing
340 std::vector<std::string> connects_to;
341 std::vector<content_t> connects_to_ids;
342 // Post effect color, drawn when the camera is inside the node.
343 video::SColor post_effect_color;
344 // Flowing liquid or leveled nodebox, value = default level
346 // Maximum value for leveled nodes
349 // --- LIGHTING-RELATED ---
351 bool light_propagates;
352 bool sunlight_propagates;
353 // Amount of light the node emits
356 // --- MAP GENERATION ---
358 // True for all ground-like things like stone and mud, false for eg. trees
359 bool is_ground_content;
361 // --- INTERACTION PROPERTIES ---
363 // This is used for collision detection.
364 // Also for general solidness queries.
366 // Player can point to these
368 // Player can dig these
370 // Player can climb these
372 // Player can build on these
374 // Player cannot build to these (placement prediction disabled)
376 u32 damage_per_second;
377 // client dig prediction
378 std::string node_dig_prediction;
380 // --- LIQUID PROPERTIES ---
382 // Whether the node is non-liquid, source liquid or flowing liquid
383 enum LiquidType liquid_type;
384 // If the content is liquid, this is the flowing version of the liquid.
385 std::string liquid_alternative_flowing;
386 content_t liquid_alternative_flowing_id;
387 // If the content is liquid, this is the source version of the liquid.
388 std::string liquid_alternative_source;
389 content_t liquid_alternative_source_id;
390 // Viscosity for fluid flow, ranging from 1 to 7, with
391 // 1 giving almost instantaneous propagation and 7 being
392 // the slowest possible
394 // Is liquid renewable (new liquid source will be created between 2 existing)
395 bool liquid_renewable;
396 // Number of flowing liquids surrounding source
399 // Liquids flow into and replace node
405 NodeBox selection_box;
406 NodeBox collision_box;
408 // --- SOUND PROPERTIES ---
410 SimpleSoundSpec sound_footstep;
411 SimpleSoundSpec sound_dig;
412 SimpleSoundSpec sound_dug;
416 // Compatibility with old maps
417 // Set to true if paramtype used to be 'facedir_simple'
418 bool legacy_facedir_simple;
419 // Set to true if wall_mounted used to be set to true
420 bool legacy_wallmounted;
429 void serialize(std::ostream &os, u16 protocol_version) const;
430 void deSerialize(std::istream &is);
435 void setDefaultAlphaMode()
440 case NDT_FLOWINGLIQUID:
441 alpha = ALPHAMODE_OPAQUE;
445 alpha = ALPHAMODE_LEGACY_COMPAT; // this should eventually be OPAQUE
448 alpha = ALPHAMODE_CLIP;
453 bool needsBackfaceCulling() const
461 case NDT_PLANTLIKE_ROOTED:
469 bool isLiquid() const{
470 return (liquid_type != LIQUID_NONE);
472 bool sameLiquid(const ContentFeatures &f) const{
473 if(!isLiquid() || !f.isLiquid()) return false;
474 return (liquid_alternative_flowing_id == f.liquid_alternative_flowing_id);
477 int getGroup(const std::string &group) const
479 return itemgroup_get(groups, group);
483 void updateTextures(ITextureSource *tsrc, IShaderSource *shdsrc,
484 scene::IMeshManipulator *meshmanip, Client *client, const TextureSettings &tsettings);
490 * Checks if any tile texture has any transparent pixels.
491 * Prints a warning and returns true if that is the case, false otherwise.
492 * This is supposed to be used for use_texture_alpha backwards compatibility.
494 bool textureAlphaCheck(ITextureSource *tsrc, const TileDef *tiles,
498 void setAlphaFromLegacy(u8 legacy_alpha);
500 u8 getAlphaForLegacy() const;
504 * @brief This class is for getting the actual properties of nodes from their
507 * @details The nodes on the map are represented by three numbers (see MapNode).
508 * The first number (param0) is the type of a node. All node types have own
509 * properties (see ContentFeatures). This class is for storing and getting the
510 * properties of nodes.
511 * The manager is first filled with registered nodes, then as the game begins,
512 * functions only get `const` pointers to it, to prevent modification of
515 class NodeDefManager {
518 * Creates a NodeDefManager, and registers three ContentFeatures:
519 * \ref CONTENT_AIR, \ref CONTENT_UNKNOWN and \ref CONTENT_IGNORE.
525 * Returns the properties for the given content type.
526 * @param c content type of a node
527 * @return properties of the given content type, or \ref CONTENT_UNKNOWN
528 * if the given content type is not registered.
530 inline const ContentFeatures& get(content_t c) const {
532 c < m_content_features.size() ?
533 m_content_features[c] : m_content_features[CONTENT_UNKNOWN];
537 * Returns the properties of the given node.
538 * @param n a map node
539 * @return properties of the given node or @ref CONTENT_UNKNOWN if the
540 * given content type is not registered.
542 inline const ContentFeatures& get(const MapNode &n) const {
543 return get(n.getContent());
547 * Returns the node properties for a node name.
548 * @param name name of a node
549 * @return properties of the given node or @ref CONTENT_UNKNOWN if
552 const ContentFeatures& get(const std::string &name) const;
555 * Returns the content ID for the given name.
556 * @param name a node name
557 * @param[out] result will contain the content ID if found, otherwise
559 * @return true if the ID was found, false otherwise
561 bool getId(const std::string &name, content_t &result) const;
564 * Returns the content ID for the given name.
565 * @param name a node name
566 * @return ID of the node or @ref CONTENT_IGNORE if not found
568 content_t getId(const std::string &name) const;
571 * Returns the content IDs of the given node name or node group name.
572 * Group names start with "group:".
573 * @param name a node name or node group name
574 * @param[out] result will be appended with matching IDs
575 * @return true if `name` is a valid node name or a (not necessarily
578 bool getIds(const std::string &name, std::vector<content_t> &result) const;
581 * Returns the smallest box in integer node coordinates that
582 * contains all nodes' selection boxes. The returned box might be larger
583 * than the minimal size if the largest node is removed from the manager.
585 inline core::aabbox3d<s16> getSelectionBoxIntUnion() const {
586 return m_selection_box_int_union;
590 * Checks whether a node connects to an adjacent node.
591 * @param from the node to be checked
592 * @param to the adjacent node
593 * @param connect_face a bit field indicating which face of the node is
594 * adjacent to the other node.
595 * Bits: +y (least significant), -y, -z, -x, +z, +x (most significant).
596 * @return true if the node connects, false otherwise
598 bool nodeboxConnects(MapNode from, MapNode to,
599 u8 connect_face) const;
602 * Registers a NodeResolver to wait for the registration of
603 * ContentFeatures. Once the node registration finishes, all
604 * listeners are notified.
606 void pendNodeResolve(NodeResolver *nr) const;
609 * Stops listening to the NodeDefManager.
610 * @return true if the listener was registered before, false otherwise
612 bool cancelNodeResolveCallback(NodeResolver *nr) const;
615 * Registers a new node type with the given name and allocates a new
617 * Should not be called with an already existing name.
618 * @param name name of the node, must match with `def.name`.
619 * @param def definition of the registered node type.
620 * @return ID of the registered node or @ref CONTENT_IGNORE if
621 * the function could not allocate an ID.
623 content_t set(const std::string &name, const ContentFeatures &def);
626 * Allocates a blank node ID for the given name.
627 * @param name name of a node
628 * @return allocated ID or @ref CONTENT_IGNORE if could not allocate
631 content_t allocateDummy(const std::string &name);
634 * Removes the given node name from the manager.
635 * The node ID will remain in the manager, but won't be linked to any name.
636 * @param name name to be removed
638 void removeNode(const std::string &name);
641 * Regenerates the alias list (a map from names to node IDs).
642 * @param idef the item definition manager containing alias information
644 void updateAliases(IItemDefManager *idef);
647 * Replaces the textures of registered nodes with the ones specified in
648 * the texturepack's override.txt file
650 * @param overrides the texture overrides
652 void applyTextureOverrides(const std::vector<TextureOverride> &overrides);
655 * Only the client uses this. Loads textures and shaders required for
656 * rendering the nodes.
657 * @param gamedef must be a Client.
658 * @param progress_cbk called each time a node is loaded. Arguments:
659 * `progress_cbk_args`, number of loaded ContentFeatures, number of
660 * total ContentFeatures.
661 * @param progress_cbk_args passed to the callback function
663 void updateTextures(IGameDef *gamedef,
664 void (*progress_cbk)(void *progress_args, u32 progress, u32 max_progress),
665 void *progress_cbk_args);
668 * Writes the content of this manager to the given output stream.
669 * @param protocol_version serialization version of ContentFeatures
671 void serialize(std::ostream &os, u16 protocol_version) const;
674 * Restores the manager from a serialized stream.
675 * This clears the previous state.
676 * @param is input stream containing a serialized NodeDefManager
678 void deSerialize(std::istream &is);
681 * Used to indicate that node registration has finished.
682 * @param completed tells whether registration is complete
684 inline void setNodeRegistrationStatus(bool completed) {
685 m_node_registration_complete = completed;
689 * Notifies the registered NodeResolver instances that node registration
690 * has finished, then unregisters all listeners.
691 * Must be called after node registration has finished!
693 void runNodeResolveCallbacks();
696 * Sets the registration completion flag to false and unregisters all
697 * NodeResolver instances listening to the manager.
699 void resetNodeResolveState();
702 * Resolves (caches the IDs) cross-references between nodes,
703 * like liquid alternatives.
704 * Must be called after node registration has finished!
706 void resolveCrossrefs();
710 * Resets the manager to its initial state.
711 * See the documentation of the constructor.
716 * Allocates a new content ID, and returns it.
717 * @return the allocated ID or \ref CONTENT_IGNORE if could not allocate
719 content_t allocateId();
722 * Binds the given content ID and node name.
723 * Registers them in \ref m_name_id_mapping and
724 * \ref m_name_id_mapping_with_aliases.
725 * @param i a content ID
726 * @param name a node name
728 void addNameIdMapping(content_t i, const std::string &name);
731 * Removes a content ID from all groups.
732 * Erases content IDs from vectors in \ref m_group_to_items and
733 * removes empty vectors.
734 * @param id Content ID
736 void eraseIdFromGroups(content_t id);
739 * Recalculates m_selection_box_int_union based on
740 * m_selection_box_union.
742 void fixSelectionBoxIntUnion();
744 //! Features indexed by ID.
745 std::vector<ContentFeatures> m_content_features;
747 //! A mapping for fast conversion between names and IDs
748 NameIdMapping m_name_id_mapping;
751 * Like @ref m_name_id_mapping, but maps only from names to IDs, and
752 * includes aliases too. Updated by \ref updateAliases().
753 * Note: Not serialized.
755 std::unordered_map<std::string, content_t> m_name_id_mapping_with_aliases;
758 * A mapping from group names to a vector of content types that belong
759 * to it. Necessary for a direct lookup in \ref getIds().
760 * Note: Not serialized.
762 std::unordered_map<std::string, std::vector<content_t>> m_group_to_items;
765 * The next ID that might be free to allocate.
766 * It can be allocated already, because \ref CONTENT_AIR,
767 * \ref CONTENT_UNKNOWN and \ref CONTENT_IGNORE are registered when the
768 * manager is initialized, and new IDs are allocated from 0.
772 //! True if all nodes have been registered.
773 bool m_node_registration_complete;
776 * The union of all nodes' selection boxes.
777 * Might be larger if big nodes are removed from the manager.
779 aabb3f m_selection_box_union;
782 * The smallest box in integer node coordinates that
783 * contains all nodes' selection boxes.
784 * Might be larger if big nodes are removed from the manager.
786 core::aabbox3d<s16> m_selection_box_int_union;
789 * NodeResolver instances to notify once node registration has finished.
790 * Even constant NodeDefManager instances can register listeners.
792 mutable std::vector<NodeResolver *> m_pending_resolve_callbacks;
795 NodeDefManager *createNodeDefManager();
797 // NodeResolver: Queue for node names which are then translated
798 // to content_t after the NodeDefManager was initialized
802 virtual ~NodeResolver();
803 // Callback which is run as soon NodeDefManager is ready
804 virtual void resolveNodeNames() = 0;
806 // required because this class is used as mixin for ObjDef
807 void cloneTo(NodeResolver *res) const;
809 bool getIdFromNrBacklog(content_t *result_out,
810 const std::string &node_alt, content_t c_fallback,
811 bool error_on_fallback = true);
812 bool getIdsFromNrBacklog(std::vector<content_t> *result_out,
813 bool all_required = false, content_t c_fallback = CONTENT_IGNORE);
815 inline bool isResolveDone() const { return m_resolve_done; }
816 void reset(bool resolve_done = false);
818 // Vector containing all node names in the resolve "queue"
819 std::vector<std::string> m_nodenames;
820 // Specifies the "set size" of node names which are to be processed
821 // this is used for getIdsFromNrBacklog
822 // TODO: replace or remove
823 std::vector<size_t> m_nnlistsizes;
826 friend class NodeDefManager; // m_ndef
828 const NodeDefManager *m_ndef = nullptr;
829 // Index of the next "m_nodenames" entry to resolve
830 u32 m_nodenames_idx = 0;
834 // Unittest requires access to m_resolve_done
835 friend class TestSchematic;
837 void nodeResolveInternal();
839 // Index of the next "m_nnlistsizes" entry to process
840 u32 m_nnlistsizes_idx = 0;
841 bool m_resolve_done = false;