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;
54 enum ContentParamType2
59 // Flowing liquid properties
61 // Direction for chests and furnaces and such
63 // Direction for signs, torches and such
65 // Block level like FLOWINGLIQUID
67 // 2D rotation for things like plants
69 // Mesh options for plants
73 // 3 bits of palette index, then facedir
75 // 5 bits of palette index, then wallmounted
76 CPT2_COLORED_WALLMOUNTED,
77 // Glasslike framed drawtype internal liquid level, param2 values 0 to 63
78 CPT2_GLASSLIKE_LIQUID_LEVEL,
90 NODEBOX_REGULAR, // Regular block; allows buildable_to
91 NODEBOX_FIXED, // Static separately defined box(es)
92 NODEBOX_WALLMOUNTED, // Box for wall mounted nodes; (top, bottom, side)
93 NODEBOX_LEVELED, // Same as fixed, but with dynamic height from param2. for snow, ...
94 NODEBOX_CONNECTED, // optionally draws nodeboxes if a neighbor node attaches
99 enum NodeBoxType type;
100 // NODEBOX_REGULAR (no parameters)
102 std::vector<aabb3f> fixed;
103 // NODEBOX_WALLMOUNTED
106 aabb3f wall_side; // being at the -X side
108 std::vector<aabb3f> connect_top;
109 std::vector<aabb3f> connect_bottom;
110 std::vector<aabb3f> connect_front;
111 std::vector<aabb3f> connect_left;
112 std::vector<aabb3f> connect_back;
113 std::vector<aabb3f> connect_right;
114 std::vector<aabb3f> disconnected_top;
115 std::vector<aabb3f> disconnected_bottom;
116 std::vector<aabb3f> disconnected_front;
117 std::vector<aabb3f> disconnected_left;
118 std::vector<aabb3f> disconnected_back;
119 std::vector<aabb3f> disconnected_right;
120 std::vector<aabb3f> disconnected;
121 std::vector<aabb3f> disconnected_sides;
127 void serialize(std::ostream &os, u16 protocol_version) const;
128 void deSerialize(std::istream &is);
140 enum AutoScale : u8 {
146 enum WorldAlignMode : u8 {
150 WORLDALIGN_FORCE_NODEBOX,
153 class TextureSettings {
155 LeavesStyle leaves_style;
156 WorldAlignMode world_aligned_mode;
157 AutoScale autoscale_mode;
158 int node_texture_size;
160 bool connected_glass;
161 bool use_normal_texture;
162 bool enable_mesh_cache;
165 TextureSettings() = default;
172 // A basic solid block
176 // Do not draw face towards same kind of flowing/source liquid
178 // A very special kind of thing
180 // Glass-like, don't draw faces towards other glass
182 // Leaves-like, draw all faces no matter what
184 // Enabled -> ndt_allfaces, disabled -> ndt_normal
185 NDT_ALLFACES_OPTIONAL,
186 // Single plane perpendicular to a surface
188 // Single plane parallel to a surface
190 // 2 vertical planes in a 'X' shape diagonal to XZ axes.
191 // paramtype2 = "meshoptions" allows various forms, sizes and
192 // vertical and horizontal random offsets.
194 // Fenceposts that connect to neighbouring fenceposts with horizontal bars
196 // Selects appropriate junction texture to connect like rails to
197 // neighbouring raillikes.
199 // Custom Lua-definable structure of multiple cuboids
201 // Glass-like, draw connected frames and all visible faces.
202 // param2 > 0 defines 64 levels of internal liquid
203 // Uses 3 textures, one for frames, second for faces,
204 // optional third is a 'special tile' for the liquid.
205 NDT_GLASSLIKE_FRAMED,
206 // Draw faces slightly rotated and only on neighbouring nodes
208 // Enabled -> ndt_glasslike_framed, disabled -> ndt_glasslike
209 NDT_GLASSLIKE_FRAMED_OPTIONAL,
210 // Uses static meshes
212 // Combined plantlike-on-solid
213 NDT_PLANTLIKE_ROOTED,
216 // Mesh options for NDT_PLANTLIKE with CPT2_MESHOPTIONS
217 static const u8 MO_MASK_STYLE = 0x07;
218 static const u8 MO_BIT_RANDOM_OFFSET = 0x08;
219 static const u8 MO_BIT_SCALE_SQRT2 = 0x10;
220 static const u8 MO_BIT_RANDOM_OFFSET_Y = 0x20;
221 enum PlantlikeStyle {
229 enum AlignStyle : u8 {
232 ALIGN_STYLE_USER_DEFINED,
236 Stand-alone definition of a TileSpec (basically a server-side TileSpec)
241 std::string name = "";
242 bool backface_culling = true; // Takes effect only in special cases
243 bool tileable_horizontal = true;
244 bool tileable_vertical = true;
245 //! If true, the tile has its own color.
246 bool has_color = false;
247 //! The color of the tile.
248 video::SColor color = video::SColor(0xFFFFFFFF);
249 AlignStyle align_style = ALIGN_STYLE_NODE;
252 struct TileAnimationParams animation;
256 animation.type = TAT_NONE;
259 void serialize(std::ostream &os, u16 protocol_version) const;
260 void deSerialize(std::istream &is, u8 contentfeatures_version,
261 NodeDrawType drawtype);
264 // Defines the number of special tiles per nodedef
266 // NOTE: When changing this value, the enum entries of OverrideTarget and
267 // parser in TextureOverrideSource must be updated so that all special
268 // tiles can be overridden.
269 #define CF_SPECIAL_COUNT 6
271 struct ContentFeatures
278 // up down right left back front
281 // - Currently used for flowing liquids
282 TileSpec special_tiles[CF_SPECIAL_COUNT];
283 u8 solidness; // Used when choosing which face is drawn
284 u8 visual_solidness; // When solidness=0, this tells how it looks like
285 bool backface_culling;
288 // Server-side cached callback existence for fast skipping
289 bool has_on_construct;
290 bool has_on_destruct;
291 bool has_after_destruct;
297 // --- GENERAL PROPERTIES ---
299 std::string name; // "" = undefined node
300 ItemGroupList groups; // Same as in itemdef
301 // Type of MapNode::param1
302 ContentParamType param_type;
303 // Type of MapNode::param2
304 ContentParamType2 param_type_2;
306 // --- VISUAL PROPERTIES ---
308 enum NodeDrawType drawtype;
311 scene::IMesh *mesh_ptr[24];
312 video::SColor minimap_color;
314 float visual_scale; // Misc. scale parameter
316 // These will be drawn over the base tiles.
317 TileDef tiledef_overlay[6];
318 TileDef tiledef_special[CF_SPECIAL_COUNT]; // eg. flowing liquid
319 // If 255, the node is opaque.
320 // Otherwise it uses texture alpha.
322 // The color of the node.
324 std::string palette_name;
325 std::vector<video::SColor> *palette;
326 // Used for waving leaves/plants
328 // for NDT_CONNECTED pairing
330 std::vector<std::string> connects_to;
331 std::vector<content_t> connects_to_ids;
332 // Post effect color, drawn when the camera is inside the node.
333 video::SColor post_effect_color;
334 // Flowing liquid or leveled nodebox, value = default level
336 // Maximum value for leveled nodes
339 // --- LIGHTING-RELATED ---
341 bool light_propagates;
342 bool sunlight_propagates;
343 // Amount of light the node emits
346 // --- MAP GENERATION ---
348 // True for all ground-like things like stone and mud, false for eg. trees
349 bool is_ground_content;
351 // --- INTERACTION PROPERTIES ---
353 // This is used for collision detection.
354 // Also for general solidness queries.
356 // Player can point to these
358 // Player can dig these
360 // Player can climb these
362 // Player can build on these
364 // Player cannot build to these (placement prediction disabled)
366 u32 damage_per_second;
367 // client dig prediction
368 std::string node_dig_prediction;
370 // --- LIQUID PROPERTIES ---
372 // Whether the node is non-liquid, source liquid or flowing liquid
373 enum LiquidType liquid_type;
374 // If the content is liquid, this is the flowing version of the liquid.
375 std::string liquid_alternative_flowing;
376 content_t liquid_alternative_flowing_id;
377 // If the content is liquid, this is the source version of the liquid.
378 std::string liquid_alternative_source;
379 content_t liquid_alternative_source_id;
380 // Viscosity for fluid flow, ranging from 1 to 7, with
381 // 1 giving almost instantaneous propagation and 7 being
382 // the slowest possible
384 // Is liquid renewable (new liquid source will be created between 2 existing)
385 bool liquid_renewable;
386 // Number of flowing liquids surrounding source
389 // Liquids flow into and replace node
395 NodeBox selection_box;
396 NodeBox collision_box;
398 // --- SOUND PROPERTIES ---
400 SimpleSoundSpec sound_footstep;
401 SimpleSoundSpec sound_dig;
402 SimpleSoundSpec sound_dug;
406 // Compatibility with old maps
407 // Set to true if paramtype used to be 'facedir_simple'
408 bool legacy_facedir_simple;
409 // Set to true if wall_mounted used to be set to true
410 bool legacy_wallmounted;
419 void serialize(std::ostream &os, u16 protocol_version) const;
420 void deSerialize(std::istream &is);
423 * Since vertex alpha is no longer supported, this method
424 * adds opacity directly to the texture pixels.
426 * \param tiles array of the tile definitions.
427 * \param length length of tiles
429 void correctAlpha(TileDef *tiles, int length);
433 * Checks if any tile texture has any transparent pixels.
434 * Prints a warning and returns true if that is the case, false otherwise.
435 * This is supposed to be used for use_texture_alpha backwards compatibility.
437 bool textureAlphaCheck(ITextureSource *tsrc, const TileDef *tiles,
445 bool needsBackfaceCulling() const
453 case NDT_PLANTLIKE_ROOTED:
461 bool isLiquid() const{
462 return (liquid_type != LIQUID_NONE);
464 bool sameLiquid(const ContentFeatures &f) const{
465 if(!isLiquid() || !f.isLiquid()) return false;
466 return (liquid_alternative_flowing_id == f.liquid_alternative_flowing_id);
469 int getGroup(const std::string &group) const
471 return itemgroup_get(groups, group);
475 void updateTextures(ITextureSource *tsrc, IShaderSource *shdsrc,
476 scene::IMeshManipulator *meshmanip, Client *client, const TextureSettings &tsettings);
481 * @brief This class is for getting the actual properties of nodes from their
484 * @details The nodes on the map are represented by three numbers (see MapNode).
485 * The first number (param0) is the type of a node. All node types have own
486 * properties (see ContentFeatures). This class is for storing and getting the
487 * properties of nodes.
488 * The manager is first filled with registered nodes, then as the game begins,
489 * functions only get `const` pointers to it, to prevent modification of
492 class NodeDefManager {
495 * Creates a NodeDefManager, and registers three ContentFeatures:
496 * \ref CONTENT_AIR, \ref CONTENT_UNKNOWN and \ref CONTENT_IGNORE.
502 * Returns the properties for the given content type.
503 * @param c content type of a node
504 * @return properties of the given content type, or \ref CONTENT_UNKNOWN
505 * if the given content type is not registered.
507 inline const ContentFeatures& get(content_t c) const {
509 c < m_content_features.size() ?
510 m_content_features[c] : m_content_features[CONTENT_UNKNOWN];
514 * Returns the properties of the given node.
515 * @param n a map node
516 * @return properties of the given node or @ref CONTENT_UNKNOWN if the
517 * given content type is not registered.
519 inline const ContentFeatures& get(const MapNode &n) const {
520 return get(n.getContent());
524 * Returns the node properties for a node name.
525 * @param name name of a node
526 * @return properties of the given node or @ref CONTENT_UNKNOWN if
529 const ContentFeatures& get(const std::string &name) const;
532 * Returns the content ID for the given name.
533 * @param name a node name
534 * @param[out] result will contain the content ID if found, otherwise
536 * @return true if the ID was found, false otherwise
538 bool getId(const std::string &name, content_t &result) const;
541 * Returns the content ID for the given name.
542 * @param name a node name
543 * @return ID of the node or @ref CONTENT_IGNORE if not found
545 content_t getId(const std::string &name) const;
548 * Returns the content IDs of the given node name or node group name.
549 * Group names start with "group:".
550 * @param name a node name or node group name
551 * @param[out] result will be appended with matching IDs
552 * @return true if `name` is a valid node name or a (not necessarily
555 bool getIds(const std::string &name, std::vector<content_t> &result) const;
558 * Returns the smallest box in integer node coordinates that
559 * contains all nodes' selection boxes. The returned box might be larger
560 * than the minimal size if the largest node is removed from the manager.
562 inline core::aabbox3d<s16> getSelectionBoxIntUnion() const {
563 return m_selection_box_int_union;
567 * Checks whether a node connects to an adjacent node.
568 * @param from the node to be checked
569 * @param to the adjacent node
570 * @param connect_face a bit field indicating which face of the node is
571 * adjacent to the other node.
572 * Bits: +y (least significant), -y, -z, -x, +z, +x (most significant).
573 * @return true if the node connects, false otherwise
575 bool nodeboxConnects(MapNode from, MapNode to,
576 u8 connect_face) const;
579 * Registers a NodeResolver to wait for the registration of
580 * ContentFeatures. Once the node registration finishes, all
581 * listeners are notified.
583 void pendNodeResolve(NodeResolver *nr) const;
586 * Stops listening to the NodeDefManager.
587 * @return true if the listener was registered before, false otherwise
589 bool cancelNodeResolveCallback(NodeResolver *nr) const;
592 * Registers a new node type with the given name and allocates a new
594 * Should not be called with an already existing name.
595 * @param name name of the node, must match with `def.name`.
596 * @param def definition of the registered node type.
597 * @return ID of the registered node or @ref CONTENT_IGNORE if
598 * the function could not allocate an ID.
600 content_t set(const std::string &name, const ContentFeatures &def);
603 * Allocates a blank node ID for the given name.
604 * @param name name of a node
605 * @return allocated ID or @ref CONTENT_IGNORE if could not allocate
608 content_t allocateDummy(const std::string &name);
611 * Removes the given node name from the manager.
612 * The node ID will remain in the manager, but won't be linked to any name.
613 * @param name name to be removed
615 void removeNode(const std::string &name);
618 * Regenerates the alias list (a map from names to node IDs).
619 * @param idef the item definition manager containing alias information
621 void updateAliases(IItemDefManager *idef);
624 * Replaces the textures of registered nodes with the ones specified in
625 * the texturepack's override.txt file
627 * @param overrides the texture overrides
629 void applyTextureOverrides(const std::vector<TextureOverride> &overrides);
632 * Only the client uses this. Loads textures and shaders required for
633 * rendering the nodes.
634 * @param gamedef must be a Client.
635 * @param progress_cbk called each time a node is loaded. Arguments:
636 * `progress_cbk_args`, number of loaded ContentFeatures, number of
637 * total ContentFeatures.
638 * @param progress_cbk_args passed to the callback function
640 void updateTextures(IGameDef *gamedef,
641 void (*progress_cbk)(void *progress_args, u32 progress, u32 max_progress),
642 void *progress_cbk_args);
645 * Writes the content of this manager to the given output stream.
646 * @param protocol_version serialization version of ContentFeatures
648 void serialize(std::ostream &os, u16 protocol_version) const;
651 * Restores the manager from a serialized stream.
652 * This clears the previous state.
653 * @param is input stream containing a serialized NodeDefManager
655 void deSerialize(std::istream &is);
658 * Used to indicate that node registration has finished.
659 * @param completed tells whether registration is complete
661 inline void setNodeRegistrationStatus(bool completed) {
662 m_node_registration_complete = completed;
666 * Notifies the registered NodeResolver instances that node registration
667 * has finished, then unregisters all listeners.
668 * Must be called after node registration has finished!
670 void runNodeResolveCallbacks();
673 * Sets the registration completion flag to false and unregisters all
674 * NodeResolver instances listening to the manager.
676 void resetNodeResolveState();
679 * Resolves (caches the IDs) cross-references between nodes,
680 * like liquid alternatives.
681 * Must be called after node registration has finished!
683 void resolveCrossrefs();
687 * Resets the manager to its initial state.
688 * See the documentation of the constructor.
693 * Allocates a new content ID, and returns it.
694 * @return the allocated ID or \ref CONTENT_IGNORE if could not allocate
696 content_t allocateId();
699 * Binds the given content ID and node name.
700 * Registers them in \ref m_name_id_mapping and
701 * \ref m_name_id_mapping_with_aliases.
702 * @param i a content ID
703 * @param name a node name
705 void addNameIdMapping(content_t i, std::string name);
708 * Removes a content ID from all groups.
709 * Erases content IDs from vectors in \ref m_group_to_items and
710 * removes empty vectors.
711 * @param id Content ID
713 void eraseIdFromGroups(content_t id);
716 * Recalculates m_selection_box_int_union based on
717 * m_selection_box_union.
719 void fixSelectionBoxIntUnion();
721 //! Features indexed by ID.
722 std::vector<ContentFeatures> m_content_features;
724 //! A mapping for fast conversion between names and IDs
725 NameIdMapping m_name_id_mapping;
728 * Like @ref m_name_id_mapping, but maps only from names to IDs, and
729 * includes aliases too. Updated by \ref updateAliases().
730 * Note: Not serialized.
732 std::unordered_map<std::string, content_t> m_name_id_mapping_with_aliases;
735 * A mapping from group names to a vector of content types that belong
736 * to it. Necessary for a direct lookup in \ref getIds().
737 * Note: Not serialized.
739 std::unordered_map<std::string, std::vector<content_t>> m_group_to_items;
742 * The next ID that might be free to allocate.
743 * It can be allocated already, because \ref CONTENT_AIR,
744 * \ref CONTENT_UNKNOWN and \ref CONTENT_IGNORE are registered when the
745 * manager is initialized, and new IDs are allocated from 0.
749 //! True if all nodes have been registered.
750 bool m_node_registration_complete;
753 * The union of all nodes' selection boxes.
754 * Might be larger if big nodes are removed from the manager.
756 aabb3f m_selection_box_union;
759 * The smallest box in integer node coordinates that
760 * contains all nodes' selection boxes.
761 * Might be larger if big nodes are removed from the manager.
763 core::aabbox3d<s16> m_selection_box_int_union;
766 * NodeResolver instances to notify once node registration has finished.
767 * Even constant NodeDefManager instances can register listeners.
769 mutable std::vector<NodeResolver *> m_pending_resolve_callbacks;
772 NodeDefManager *createNodeDefManager();
777 virtual ~NodeResolver();
778 virtual void resolveNodeNames() = 0;
780 // required because this class is used as mixin for ObjDef
781 void cloneTo(NodeResolver *res) const;
783 bool getIdFromNrBacklog(content_t *result_out,
784 const std::string &node_alt, content_t c_fallback,
785 bool error_on_fallback = true);
786 bool getIdsFromNrBacklog(std::vector<content_t> *result_out,
787 bool all_required = false, content_t c_fallback = CONTENT_IGNORE);
789 void nodeResolveInternal();
791 u32 m_nodenames_idx = 0;
792 u32 m_nnlistsizes_idx = 0;
793 std::vector<std::string> m_nodenames;
794 std::vector<size_t> m_nnlistsizes;
795 const NodeDefManager *m_ndef = nullptr;
796 bool m_resolve_done = false;