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.
20 #include "content_cao.h"
21 #include <IBillboardSceneNode.h>
22 #include <ICameraSceneNode.h>
23 #include <IMeshManipulator.h>
24 #include <IAnimatedMeshSceneNode.h>
25 #include "client/client.h"
26 #include "client/renderingengine.h"
27 #include "client/sound.h"
28 #include "client/tile.h"
29 #include "util/basic_macros.h"
30 #include "util/numeric.h"
31 #include "util/serialize.h"
32 #include "camera.h" // CameraModes
33 #include "collision.h"
34 #include "content_cso.h"
35 #include "environment.h"
37 #include "localplayer.h"
41 #include "serialization.h" // For decompressZlib
45 #include "wieldmesh.h"
48 #include "client/shader.h"
49 #include "script/scripting_client.h"
50 #include "client/minimap.h"
53 struct ToolCapabilities;
55 std::unordered_map<u16, ClientActiveObject::Factory> ClientActiveObject::m_types;
58 void SmoothTranslator<T>::init(T current)
61 val_current = current;
64 anim_time_counter = 0;
69 void SmoothTranslator<T>::update(T new_target, bool is_end_position, float update_interval)
71 aim_is_end = is_end_position;
72 val_old = val_current;
73 val_target = new_target;
74 if (update_interval > 0) {
75 anim_time = update_interval;
77 if (anim_time < 0.001 || anim_time > 1.0)
78 anim_time = anim_time_counter;
80 anim_time = anim_time * 0.9 + anim_time_counter * 0.1;
82 anim_time_counter = 0;
86 void SmoothTranslator<T>::translate(f32 dtime)
88 anim_time_counter = anim_time_counter + dtime;
89 T val_diff = val_target - val_old;
91 if (anim_time > 0.001)
92 moveratio = anim_time_counter / anim_time;
93 f32 move_end = aim_is_end ? 1.0 : 1.5;
95 // Move a bit less than should, to avoid oscillation
96 moveratio = std::min(moveratio * 0.8f, move_end);
97 val_current = val_old + val_diff * moveratio;
100 void SmoothTranslatorWrapped::translate(f32 dtime)
102 anim_time_counter = anim_time_counter + dtime;
103 f32 val_diff = std::abs(val_target - val_old);
104 if (val_diff > 180.f)
105 val_diff = 360.f - val_diff;
108 if (anim_time > 0.001)
109 moveratio = anim_time_counter / anim_time;
110 f32 move_end = aim_is_end ? 1.0 : 1.5;
112 // Move a bit less than should, to avoid oscillation
113 moveratio = std::min(moveratio * 0.8f, move_end);
114 wrappedApproachShortest(val_current, val_target,
115 val_diff * moveratio, 360.f);
118 void SmoothTranslatorWrappedv3f::translate(f32 dtime)
120 anim_time_counter = anim_time_counter + dtime;
123 val_diff_v3f.X = std::abs(val_target.X - val_old.X);
124 val_diff_v3f.Y = std::abs(val_target.Y - val_old.Y);
125 val_diff_v3f.Z = std::abs(val_target.Z - val_old.Z);
127 if (val_diff_v3f.X > 180.f)
128 val_diff_v3f.X = 360.f - val_diff_v3f.X;
130 if (val_diff_v3f.Y > 180.f)
131 val_diff_v3f.Y = 360.f - val_diff_v3f.Y;
133 if (val_diff_v3f.Z > 180.f)
134 val_diff_v3f.Z = 360.f - val_diff_v3f.Z;
137 if (anim_time > 0.001)
138 moveratio = anim_time_counter / anim_time;
139 f32 move_end = aim_is_end ? 1.0 : 1.5;
141 // Move a bit less than should, to avoid oscillation
142 moveratio = std::min(moveratio * 0.8f, move_end);
143 wrappedApproachShortest(val_current.X, val_target.X,
144 val_diff_v3f.X * moveratio, 360.f);
146 wrappedApproachShortest(val_current.Y, val_target.Y,
147 val_diff_v3f.Y * moveratio, 360.f);
149 wrappedApproachShortest(val_current.Z, val_target.Z,
150 val_diff_v3f.Z * moveratio, 360.f);
157 static void setBillboardTextureMatrix(scene::IBillboardSceneNode *bill,
158 float txs, float tys, int col, int row)
160 video::SMaterial& material = bill->getMaterial(0);
161 core::matrix4& matrix = material.getTextureMatrix(0);
162 matrix.setTextureTranslate(txs*col, tys*row);
163 matrix.setTextureScale(txs, tys);
166 // Evaluate transform chain recursively; irrlicht does not do this for us
167 static void updatePositionRecursive(scene::ISceneNode *node)
169 scene::ISceneNode *parent = node->getParent();
171 updatePositionRecursive(parent);
172 node->updateAbsolutePosition();
175 static bool logOnce(const std::ostringstream &from, std::ostream &log_to)
177 thread_local std::vector<u64> logged;
179 std::string message = from.str();
180 u64 hash = murmur_hash_64_ua(message.data(), message.length(), 0xBADBABE);
182 if (std::find(logged.begin(), logged.end(), hash) != logged.end())
184 logged.push_back(hash);
185 log_to << message << std::endl;
193 class TestCAO : public ClientActiveObject
196 TestCAO(Client *client, ClientEnvironment *env);
197 virtual ~TestCAO() = default;
199 ActiveObjectType getType() const
201 return ACTIVEOBJECT_TYPE_TEST;
204 static ClientActiveObject* create(Client *client, ClientEnvironment *env);
206 void addToScene(ITextureSource *tsrc, scene::ISceneManager *smgr);
207 void removeFromScene(bool permanent);
208 void updateLight(u32 day_night_ratio);
209 void updateNodePos();
211 void step(float dtime, ClientEnvironment *env);
213 void processMessage(const std::string &data);
215 bool getCollisionBox(aabb3f *toset) const { return false; }
217 scene::IMeshSceneNode *m_node;
222 TestCAO proto_TestCAO(NULL, NULL);
224 TestCAO::TestCAO(Client *client, ClientEnvironment *env):
225 ClientActiveObject(0, client, env),
227 m_position(v3f(0,10*BS,0))
229 ClientActiveObject::registerType(getType(), create);
232 ClientActiveObject* TestCAO::create(Client *client, ClientEnvironment *env)
234 return new TestCAO(client, env);
237 void TestCAO::addToScene(ITextureSource *tsrc, scene::ISceneManager *smgr)
242 //video::IVideoDriver* driver = smgr->getVideoDriver();
244 scene::SMesh *mesh = new scene::SMesh();
245 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
246 video::SColor c(255,255,255,255);
247 video::S3DVertex vertices[4] =
249 video::S3DVertex(-BS/2,-BS/4,0, 0,0,0, c, 0,1),
250 video::S3DVertex(BS/2,-BS/4,0, 0,0,0, c, 1,1),
251 video::S3DVertex(BS/2,BS/4,0, 0,0,0, c, 1,0),
252 video::S3DVertex(-BS/2,BS/4,0, 0,0,0, c, 0,0),
254 u16 indices[] = {0,1,2,2,3,0};
255 buf->append(vertices, 4, indices, 6);
257 buf->getMaterial().setFlag(video::EMF_LIGHTING, true); // false
258 buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false);
259 buf->getMaterial().setTexture(0, tsrc->getTextureForMesh("rat.png"));
260 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
261 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
262 buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
264 mesh->addMeshBuffer(buf);
266 m_node = smgr->addMeshSceneNode(mesh, NULL);
271 void TestCAO::removeFromScene(bool permanent)
280 void TestCAO::updateLight(u32 day_night_ratio)
284 void TestCAO::updateNodePos()
289 m_node->setPosition(m_position);
290 //m_node->setRotation(v3f(0, 45, 0));
293 void TestCAO::step(float dtime, ClientEnvironment *env)
297 v3f rot = m_node->getRotation();
298 //infostream<<"dtime="<<dtime<<", rot.Y="<<rot.Y<<std::endl;
299 rot.Y += dtime * 180;
300 m_node->setRotation(rot);
304 void TestCAO::processMessage(const std::string &data)
306 infostream<<"TestCAO: Got data: "<<data<<std::endl;
307 std::istringstream is(data, std::ios::binary);
325 #include "clientobject.h"
327 GenericCAO::GenericCAO(Client *client, ClientEnvironment *env):
328 ClientActiveObject(0, client, env)
330 if (client == NULL) {
331 ClientActiveObject::registerType(getType(), create);
337 bool GenericCAO::getCollisionBox(aabb3f *toset) const
341 //update collision box
342 toset->MinEdge = m_prop.collisionbox.MinEdge * BS;
343 toset->MaxEdge = m_prop.collisionbox.MaxEdge * BS;
345 toset->MinEdge += m_position;
346 toset->MaxEdge += m_position;
354 bool GenericCAO::collideWithObjects() const
356 return m_prop.collideWithObjects;
359 void GenericCAO::initialize(const std::string &data)
361 infostream<<"GenericCAO: Got init data"<<std::endl;
362 processInitData(data);
364 m_enable_shaders = g_settings->getBool("enable_shaders");
367 void GenericCAO::processInitData(const std::string &data)
369 std::istringstream is(data, std::ios::binary);
370 const u8 version = readU8(is);
373 errorstream << "GenericCAO: Unsupported init data version"
378 // PROTOCOL_VERSION >= 37
379 m_name = deSerializeString16(is);
380 m_is_player = readU8(is);
382 m_position = readV3F32(is);
383 m_rotation = readV3F32(is);
387 // Check if it's the current player
388 LocalPlayer *player = m_env->getLocalPlayer();
389 if (player && strcmp(player->getName(), m_name.c_str()) == 0) {
390 m_is_local_player = true;
391 m_is_visible = false;
392 player->setCAO(this);
396 const u8 num_messages = readU8(is);
398 for (int i = 0; i < num_messages; i++) {
399 std::string message = deSerializeString32(is);
400 processMessage(message);
403 m_rotation = wrapDegrees_0_360_v3f(m_rotation);
404 pos_translator.init(m_position);
405 rot_translator.init(m_rotation);
409 GenericCAO::~GenericCAO()
411 removeFromScene(true);
414 bool GenericCAO::getSelectionBox(aabb3f *toset) const
416 if (!m_prop.is_visible || !m_is_visible || m_is_local_player
417 || !m_prop.pointable) {
420 *toset = m_selection_box;
424 const v3f GenericCAO::getPosition() const
427 return pos_translator.val_current;
429 // Calculate real position in world based on MatrixNode
431 v3s16 camera_offset = m_env->getCameraOffset();
432 return m_matrixnode->getAbsolutePosition() +
433 intToFloat(camera_offset, BS);
439 bool GenericCAO::isImmortal() const
441 return itemgroup_get(getGroups(), "immortal");
444 scene::ISceneNode *GenericCAO::getSceneNode() const
450 if (m_animated_meshnode) {
451 return m_animated_meshnode;
454 if (m_wield_meshnode) {
455 return m_wield_meshnode;
464 scene::IAnimatedMeshSceneNode *GenericCAO::getAnimatedMeshSceneNode() const
466 return m_animated_meshnode;
469 void GenericCAO::setChildrenVisible(bool toset)
471 for (u16 cao_id : m_attachment_child_ids) {
472 GenericCAO *obj = m_env->getGenericCAO(cao_id);
474 // Check if the entity is forced to appear in first person.
475 obj->setVisible(obj->m_force_visible ? true : toset);
480 void GenericCAO::setAttachment(int parent_id, const std::string &bone,
481 v3f position, v3f rotation, bool force_visible)
483 int old_parent = m_attachment_parent_id;
484 m_attachment_parent_id = parent_id;
485 m_attachment_bone = bone;
486 m_attachment_position = position;
487 m_attachment_rotation = rotation;
488 m_force_visible = force_visible;
490 ClientActiveObject *parent = m_env->getActiveObject(parent_id);
492 if (parent_id != old_parent) {
494 m_waiting_for_reattach = 10;
495 if (auto *o = m_env->getActiveObject(old_parent))
496 o->removeAttachmentChild(m_id);
498 parent->addAttachmentChild(m_id);
503 // Forcibly show attachments if required by set_attach
504 if (m_force_visible) {
506 } else if (!m_is_local_player) {
507 // Objects attached to the local player should be hidden in first person
508 m_is_visible = !m_attached_to_local ||
509 m_client->getCamera()->getCameraMode() != CAMERA_MODE_FIRST || g_settings->getBool("freecam");
510 m_force_visible = false;
512 // Local players need to have this set,
513 // otherwise first person attachments fail.
518 void GenericCAO::getAttachment(int *parent_id, std::string *bone, v3f *position,
519 v3f *rotation, bool *force_visible) const
521 *parent_id = m_attachment_parent_id;
522 *bone = m_attachment_bone;
523 *position = m_attachment_position;
524 *rotation = m_attachment_rotation;
525 *force_visible = m_force_visible;
528 void GenericCAO::clearChildAttachments()
530 // Cannot use for-loop here: setAttachment() modifies 'm_attachment_child_ids'!
531 while (!m_attachment_child_ids.empty()) {
532 int child_id = *m_attachment_child_ids.begin();
534 if (ClientActiveObject *child = m_env->getActiveObject(child_id))
535 child->setAttachment(0, "", v3f(), v3f(), false);
537 removeAttachmentChild(child_id);
541 void GenericCAO::clearParentAttachment()
543 if (m_attachment_parent_id)
544 setAttachment(0, "", m_attachment_position, m_attachment_rotation, false);
546 setAttachment(0, "", v3f(), v3f(), false);
549 void GenericCAO::addAttachmentChild(int child_id)
551 m_attachment_child_ids.insert(child_id);
554 void GenericCAO::removeAttachmentChild(int child_id)
556 m_attachment_child_ids.erase(child_id);
559 ClientActiveObject* GenericCAO::getParent() const
561 return m_attachment_parent_id ? m_env->getActiveObject(m_attachment_parent_id) :
565 void GenericCAO::removeFromScene(bool permanent)
567 // Should be true when removing the object permanently
568 // and false when refreshing (eg: updating visuals)
569 if (m_env && permanent) {
570 // The client does not know whether this object does re-appear to
571 // a later time, thus do not clear child attachments.
573 clearParentAttachment();
576 if (auto shadow = RenderingEngine::get_shadow_renderer())
577 shadow->removeNodeFromShadowList(getSceneNode());
580 m_meshnode->remove();
582 m_meshnode = nullptr;
583 } else if (m_animated_meshnode) {
584 m_animated_meshnode->remove();
585 m_animated_meshnode->drop();
586 m_animated_meshnode = nullptr;
587 } else if (m_wield_meshnode) {
588 m_wield_meshnode->remove();
589 m_wield_meshnode->drop();
590 m_wield_meshnode = nullptr;
591 } else if (m_spritenode) {
592 m_spritenode->remove();
593 m_spritenode->drop();
594 m_spritenode = nullptr;
598 m_matrixnode->remove();
599 m_matrixnode->drop();
600 m_matrixnode = nullptr;
604 m_client->getCamera()->removeNametag(m_nametag);
608 if (m_marker && m_client->getMinimap())
609 m_client->getMinimap()->removeMarker(&m_marker);
612 void GenericCAO::addToScene(ITextureSource *tsrc, scene::ISceneManager *smgr)
616 if (getSceneNode() != NULL) {
620 m_visuals_expired = false;
622 if (!m_prop.is_visible)
625 infostream << "GenericCAO::addToScene(): " << m_prop.visual << std::endl;
627 if (m_enable_shaders) {
628 IShaderSource *shader_source = m_client->getShaderSource();
629 MaterialType material_type;
631 if (m_prop.shaded && m_prop.glow == 0)
632 material_type = (m_prop.use_texture_alpha) ?
633 TILE_MATERIAL_ALPHA : TILE_MATERIAL_BASIC;
635 material_type = (m_prop.use_texture_alpha) ?
636 TILE_MATERIAL_PLAIN_ALPHA : TILE_MATERIAL_PLAIN;
638 u32 shader_id = shader_source->getShader("object_shader", material_type, NDT_NORMAL);
639 m_material_type = shader_source->getShaderInfo(shader_id).material;
641 m_material_type = (m_prop.use_texture_alpha) ?
642 video::EMT_TRANSPARENT_ALPHA_CHANNEL : video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
645 auto grabMatrixNode = [this] {
646 m_matrixnode = m_smgr->addDummyTransformationSceneNode();
647 m_matrixnode->grab();
650 auto setSceneNodeMaterial = [this] (scene::ISceneNode *node) {
651 node->setMaterialFlag(video::EMF_LIGHTING, false);
652 node->setMaterialFlag(video::EMF_BILINEAR_FILTER, false);
653 node->setMaterialFlag(video::EMF_FOG_ENABLE, true);
654 node->setMaterialType(m_material_type);
656 if (m_enable_shaders) {
657 node->setMaterialFlag(video::EMF_GOURAUD_SHADING, false);
658 node->setMaterialFlag(video::EMF_NORMALIZE_NORMALS, true);
662 if (m_prop.visual == "sprite") {
664 m_spritenode = m_smgr->addBillboardSceneNode(
665 m_matrixnode, v2f(1, 1), v3f(0,0,0), -1);
666 m_spritenode->grab();
667 m_spritenode->setMaterialTexture(0,
668 tsrc->getTextureForMesh("no_texture.png"));
670 setSceneNodeMaterial(m_spritenode);
672 m_spritenode->setSize(v2f(m_prop.visual_size.X,
673 m_prop.visual_size.Y) * BS);
675 const float txs = 1.0 / 1;
676 const float tys = 1.0 / 1;
677 setBillboardTextureMatrix(m_spritenode,
680 } else if (m_prop.visual == "upright_sprite") {
682 scene::SMesh *mesh = new scene::SMesh();
683 double dx = BS * m_prop.visual_size.X / 2;
684 double dy = BS * m_prop.visual_size.Y / 2;
685 video::SColor c(0xFFFFFFFF);
688 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
689 video::S3DVertex vertices[4] = {
690 video::S3DVertex(-dx, -dy, 0, 0,0,1, c, 1,1),
691 video::S3DVertex( dx, -dy, 0, 0,0,1, c, 0,1),
692 video::S3DVertex( dx, dy, 0, 0,0,1, c, 0,0),
693 video::S3DVertex(-dx, dy, 0, 0,0,1, c, 1,0),
696 // Move minimal Y position to 0 (feet position)
697 for (video::S3DVertex &vertex : vertices)
700 u16 indices[] = {0,1,2,2,3,0};
701 buf->append(vertices, 4, indices, 6);
703 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
704 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
705 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
706 buf->getMaterial().MaterialType = m_material_type;
708 if (m_enable_shaders) {
709 buf->getMaterial().EmissiveColor = c;
710 buf->getMaterial().setFlag(video::EMF_GOURAUD_SHADING, false);
711 buf->getMaterial().setFlag(video::EMF_NORMALIZE_NORMALS, true);
715 mesh->addMeshBuffer(buf);
719 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
720 video::S3DVertex vertices[4] = {
721 video::S3DVertex( dx,-dy, 0, 0,0,-1, c, 1,1),
722 video::S3DVertex(-dx,-dy, 0, 0,0,-1, c, 0,1),
723 video::S3DVertex(-dx, dy, 0, 0,0,-1, c, 0,0),
724 video::S3DVertex( dx, dy, 0, 0,0,-1, c, 1,0),
727 // Move minimal Y position to 0 (feet position)
728 for (video::S3DVertex &vertex : vertices)
731 u16 indices[] = {0,1,2,2,3,0};
732 buf->append(vertices, 4, indices, 6);
734 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
735 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
736 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
737 buf->getMaterial().MaterialType = m_material_type;
739 if (m_enable_shaders) {
740 buf->getMaterial().EmissiveColor = c;
741 buf->getMaterial().setFlag(video::EMF_GOURAUD_SHADING, false);
742 buf->getMaterial().setFlag(video::EMF_NORMALIZE_NORMALS, true);
746 mesh->addMeshBuffer(buf);
749 m_meshnode = m_smgr->addMeshSceneNode(mesh, m_matrixnode);
752 } else if (m_prop.visual == "cube") {
754 scene::IMesh *mesh = createCubeMesh(v3f(BS,BS,BS));
755 m_meshnode = m_smgr->addMeshSceneNode(mesh, m_matrixnode);
759 m_meshnode->setScale(m_prop.visual_size);
760 m_meshnode->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
761 m_prop.backface_culling);
763 setSceneNodeMaterial(m_meshnode);
764 } else if (m_prop.visual == "mesh") {
766 scene::IAnimatedMesh *mesh = m_client->getMesh(m_prop.mesh, true);
768 if (!checkMeshNormals(mesh)) {
769 infostream << "GenericCAO: recalculating normals for mesh "
770 << m_prop.mesh << std::endl;
771 m_smgr->getMeshManipulator()->
772 recalculateNormals(mesh, true, false);
775 m_animated_meshnode = m_smgr->addAnimatedMeshSceneNode(mesh, m_matrixnode);
776 m_animated_meshnode->grab();
777 mesh->drop(); // The scene node took hold of it
778 m_animated_meshnode->animateJoints(); // Needed for some animations
779 m_animated_meshnode->setScale(m_prop.visual_size);
781 // set vertex colors to ensure alpha is set
782 setMeshColor(m_animated_meshnode->getMesh(), video::SColor(0xFFFFFFFF));
784 setAnimatedMeshColor(m_animated_meshnode, video::SColor(0xFFFFFFFF));
786 setSceneNodeMaterial(m_animated_meshnode);
788 m_animated_meshnode->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
789 m_prop.backface_culling);
791 errorstream<<"GenericCAO::addToScene(): Could not load mesh "<<m_prop.mesh<<std::endl;
792 } else if (m_prop.visual == "wielditem" || m_prop.visual == "item") {
795 if (m_prop.wield_item.empty()) {
796 // Old format, only textures are specified.
797 infostream << "textures: " << m_prop.textures.size() << std::endl;
798 if (!m_prop.textures.empty()) {
799 infostream << "textures[0]: " << m_prop.textures[0]
801 IItemDefManager *idef = m_client->idef();
802 item = ItemStack(m_prop.textures[0], 1, 0, idef);
805 infostream << "serialized form: " << m_prop.wield_item << std::endl;
806 item.deSerialize(m_prop.wield_item, m_client->idef());
808 m_wield_meshnode = new WieldMeshSceneNode(m_smgr, -1);
809 m_wield_meshnode->setItem(item, m_client,
810 (m_prop.visual == "wielditem"));
812 m_wield_meshnode->setScale(m_prop.visual_size / 2.0f);
813 m_wield_meshnode->setColor(video::SColor(0xFFFFFFFF));
815 infostream<<"GenericCAO::addToScene(): \""<<m_prop.visual
816 <<"\" not supported"<<std::endl;
819 /* don't update while punch texture modifier is active */
820 if (m_reset_textures_timer < 0)
821 updateTextures(m_current_texture_modifier);
823 if (scene::ISceneNode *node = getSceneNode()) {
825 node->setParent(m_matrixnode);
827 if (auto shadow = RenderingEngine::get_shadow_renderer())
828 shadow->addNodeToShadowList(node);
835 updateBonePosition();
837 setNodeLight(m_last_light);
840 if (m_animated_meshnode) {
841 u32 mat_count = m_animated_meshnode->getMaterialCount();
842 if (mat_count == 0 || m_prop.textures.empty()) {
844 } else if (mat_count > m_prop.textures.size()) {
845 std::ostringstream oss;
846 oss << "GenericCAO::addToScene(): Model "
847 << m_prop.mesh << " loaded with " << mat_count
848 << " mesh buffers but only " << m_prop.textures.size()
849 << " texture(s) specifed, this is deprecated.";
850 logOnce(oss, warningstream);
852 video::ITexture *last = m_animated_meshnode->getMaterial(0).TextureLayer[0].Texture;
853 for (u32 i = 1; i < mat_count; i++) {
854 auto &layer = m_animated_meshnode->getMaterial(i).TextureLayer[0];
856 layer.Texture = last;
857 last = layer.Texture;
862 if (m_client->modsLoaded() && m_client->getScript()->on_object_add(m_id)) {
863 removeFromScene(false);
867 if (m_client->modsLoaded())
868 m_client->getScript()->on_object_properties_change(m_id);
871 void GenericCAO::updateLight(u32 day_night_ratio)
876 u16 light_at_pos = 0;
877 u8 light_at_pos_intensity = 0;
881 u16 npos = getLightPosition(pos);
882 for (u16 i = 0; i < npos; i++) {
884 MapNode n = m_env->getMap().getNode(pos[i], &this_ok);
886 u16 this_light = getInteriorLight(n, 0, m_client->ndef());
887 u8 this_light_intensity = MYMAX(this_light & 0xFF, (this_light >> 8) && 0xFF);
888 if (this_light_intensity > light_at_pos_intensity) {
889 light_at_pos = this_light;
890 light_at_pos_intensity = this_light_intensity;
896 light_at_pos = LIGHT_SUN;
898 video::SColor light = encode_light(light_at_pos, m_glow);
899 if (!m_enable_shaders)
900 final_color_blend(&light, light_at_pos, day_night_ratio);
902 if (g_settings->getBool("fullbright"))
903 light = video::SColor(0xFFFFFFFF);
905 if (light != m_last_light) {
906 m_last_light = light;
911 void GenericCAO::setNodeLight(const video::SColor &light_color)
913 if (m_prop.visual == "wielditem" || m_prop.visual == "item") {
914 if (m_wield_meshnode)
915 m_wield_meshnode->setNodeLightColor(light_color);
919 if (m_enable_shaders) {
920 if (m_prop.visual == "upright_sprite") {
923 for (u32 i = 0; i < m_meshnode->getMaterialCount(); ++i)
924 m_meshnode->getMaterial(i).EmissiveColor = light_color;
926 scene::ISceneNode *node = getSceneNode();
930 for (u32 i = 0; i < node->getMaterialCount(); ++i) {
931 video::SMaterial &material = node->getMaterial(i);
932 material.EmissiveColor = light_color;
937 setMeshColor(m_meshnode->getMesh(), light_color);
938 } else if (m_animated_meshnode) {
939 setAnimatedMeshColor(m_animated_meshnode, light_color);
940 } else if (m_spritenode) {
941 m_spritenode->setColor(light_color);
946 u16 GenericCAO::getLightPosition(v3s16 *pos)
948 const auto &box = m_prop.collisionbox;
949 pos[0] = floatToInt(m_position + box.MinEdge * BS, BS);
950 pos[1] = floatToInt(m_position + box.MaxEdge * BS, BS);
952 // Skip center pos if it falls into the same node as Min or MaxEdge
953 if ((box.MaxEdge - box.MinEdge).getLengthSQ() < 3.0f)
955 pos[2] = floatToInt(m_position + box.getCenter() * BS, BS);
959 void GenericCAO::updateMarker()
961 if (!m_client->getMinimap())
964 if (!m_prop.show_on_minimap) {
966 m_client->getMinimap()->removeMarker(&m_marker);
973 scene::ISceneNode *node = getSceneNode();
976 m_marker = m_client->getMinimap()->addMarker(node);
979 void GenericCAO::updateNametag()
981 //if (m_is_local_player && ! g_settings->getBool("freecam")) // No nametag for local player
984 if (m_prop.nametag.empty() || m_prop.nametag_color.getAlpha() == 0) {
987 m_client->getCamera()->removeNametag(m_nametag);
993 scene::ISceneNode *node = getSceneNode();
998 pos.Y = m_prop.selectionbox.MaxEdge.Y + 0.3f;
1001 m_nametag = m_client->getCamera()->addNametag(node,
1002 m_prop.nametag, m_prop.nametag_color,
1003 m_prop.nametag_bgcolor, pos, nametag_images);
1006 m_nametag->text = m_prop.nametag;
1007 m_nametag->textcolor = m_prop.nametag_color;
1008 m_nametag->bgcolor = m_prop.nametag_bgcolor;
1009 m_nametag->pos = pos;
1010 m_nametag->setImages(nametag_images);
1014 void GenericCAO::updateNodePos()
1016 if (getParent() != NULL)
1019 scene::ISceneNode *node = getSceneNode();
1022 v3s16 camera_offset = m_env->getCameraOffset();
1023 v3f pos = pos_translator.val_current -
1024 intToFloat(camera_offset, BS);
1025 getPosRotMatrix().setTranslation(pos);
1026 if (node != m_spritenode) { // rotate if not a sprite
1027 v3f rot = m_is_local_player ? -m_rotation : -rot_translator.val_current;
1028 setPitchYawRoll(getPosRotMatrix(), rot);
1033 void GenericCAO::step(float dtime, ClientEnvironment *env)
1035 // Handle model animations and update positions instantly to prevent lags
1036 if (m_is_local_player) {
1037 LocalPlayer *player = m_env->getLocalPlayer();
1038 m_position = player->getLegitPosition();
1039 pos_translator.val_current = m_position;
1040 if (! g_settings->getBool("freecam")) {
1041 m_rotation.Y = wrapDegrees_0_360(player->getYaw());
1042 rot_translator.val_current = m_rotation;
1046 int old_anim = player->last_animation;
1047 float old_anim_speed = player->last_animation_speed;
1048 m_velocity = v3f(0,0,0);
1049 m_acceleration = v3f(0,0,0);
1050 const PlayerControl &controls = player->getPlayerControl();
1051 f32 new_speed = player->local_animation_speed;
1053 bool walking = false;
1054 if (controls.movement_speed > 0.001f && ! g_settings->getBool("freecam")) {
1055 new_speed *= controls.movement_speed;
1059 v2s32 new_anim = v2s32(0,0);
1060 bool allow_update = false;
1062 // increase speed if using fast or flying fast
1063 if(((g_settings->getBool("fast_move") &&
1064 m_client->checkLocalPrivilege("fast")) &&
1066 (!player->touching_ground &&
1067 g_settings->getBool("free_move") &&
1068 m_client->checkLocalPrivilege("fly")))) || g_settings->getBool("freecam"))
1070 // slowdown speed if sneaking
1071 if (controls.sneak && walking && ! g_settings->getBool("no_slow"))
1074 if (walking && (controls.dig || controls.place)) {
1075 new_anim = player->local_animations[3];
1076 player->last_animation = WD_ANIM;
1077 } else if (walking) {
1078 new_anim = player->local_animations[1];
1079 player->last_animation = WALK_ANIM;
1080 } else if (controls.dig || controls.place) {
1081 new_anim = player->local_animations[2];
1082 player->last_animation = DIG_ANIM;
1085 // Apply animations if input detected and not attached
1086 // or set idle animation
1087 if ((new_anim.X + new_anim.Y) > 0 && !getParent()) {
1088 allow_update = true;
1089 m_animation_range = new_anim;
1090 m_animation_speed = new_speed;
1091 player->last_animation_speed = m_animation_speed;
1093 player->last_animation = NO_ANIM;
1095 if (old_anim != NO_ANIM) {
1096 m_animation_range = player->local_animations[0];
1101 // Update local player animations
1102 if ((player->last_animation != old_anim ||
1103 m_animation_speed != old_anim_speed) &&
1104 player->last_animation != NO_ANIM && allow_update)
1110 if (m_visuals_expired && m_smgr) {
1111 m_visuals_expired = false;
1113 // Attachments, part 1: All attached objects must be unparented first,
1114 // or Irrlicht causes a segmentation fault
1115 for (u16 cao_id : m_attachment_child_ids) {
1116 ClientActiveObject *obj = m_env->getActiveObject(cao_id);
1118 scene::ISceneNode *child_node = obj->getSceneNode();
1119 // The node's parent is always an IDummyTraformationSceneNode,
1120 // so we need to reparent that one instead.
1122 child_node->getParent()->setParent(m_smgr->getRootSceneNode());
1126 removeFromScene(false);
1127 addToScene(m_client->tsrc(), m_smgr);
1129 // Attachments, part 2: Now that the parent has been refreshed, put its attachments back
1130 for (u16 cao_id : m_attachment_child_ids) {
1131 ClientActiveObject *obj = m_env->getActiveObject(cao_id);
1133 obj->updateAttachments();
1137 // Make sure m_is_visible is always applied
1138 scene::ISceneNode *node = getSceneNode();
1140 node->setVisible(m_is_visible);
1142 if(getParent() != NULL) // Attachments should be glued to their parent by Irrlicht
1144 // Set these for later
1145 m_position = getPosition();
1146 m_velocity = v3f(0,0,0);
1147 m_acceleration = v3f(0,0,0);
1148 pos_translator.val_current = m_position;
1149 pos_translator.val_target = m_position;
1151 rot_translator.translate(dtime);
1152 v3f lastpos = pos_translator.val_current;
1156 aabb3f box = m_prop.collisionbox;
1159 collisionMoveResult moveresult;
1160 f32 pos_max_d = BS*0.125; // Distance per iteration
1161 v3f p_pos = m_position;
1162 v3f p_velocity = m_velocity;
1163 moveresult = collisionMoveSimple(env,env->getGameDef(),
1164 pos_max_d, box, m_prop.stepheight, dtime,
1165 &p_pos, &p_velocity, m_acceleration,
1166 this, m_prop.collideWithObjects);
1169 m_velocity = p_velocity;
1171 bool is_end_position = moveresult.collides;
1172 pos_translator.update(m_position, is_end_position, dtime);
1174 m_position += dtime * m_velocity + 0.5 * dtime * dtime * m_acceleration;
1175 m_velocity += dtime * m_acceleration;
1176 pos_translator.update(m_position, pos_translator.aim_is_end,
1177 pos_translator.anim_time);
1179 pos_translator.translate(dtime);
1182 float moved = lastpos.getDistanceFrom(pos_translator.val_current);
1183 m_step_distance_counter += moved;
1184 if (m_step_distance_counter > 1.5f * BS) {
1185 m_step_distance_counter = 0.0f;
1186 if (!m_is_local_player && m_prop.makes_footstep_sound) {
1187 const NodeDefManager *ndef = m_client->ndef();
1188 v3s16 p = floatToInt(getPosition() +
1189 v3f(0.0f, (m_prop.collisionbox.MinEdge.Y - 0.5f) * BS, 0.0f), BS);
1190 MapNode n = m_env->getMap().getNode(p);
1191 SimpleSoundSpec spec = ndef->get(n).sound_footstep;
1192 // Reduce footstep gain, as non-local-player footsteps are
1195 m_client->sound()->playSoundAt(spec, false, getPosition());
1200 m_anim_timer += dtime;
1201 if(m_anim_timer >= m_anim_framelength)
1203 m_anim_timer -= m_anim_framelength;
1205 if(m_anim_frame >= m_anim_num_frames)
1211 if(m_reset_textures_timer >= 0)
1213 m_reset_textures_timer -= dtime;
1214 if(m_reset_textures_timer <= 0) {
1215 m_reset_textures_timer = -1;
1216 updateTextures(m_previous_texture_modifier);
1220 if (!getParent() && node && fabs(m_prop.automatic_rotate) > 0.001f) {
1221 // This is the child node's rotation. It is only used for automatic_rotate.
1222 v3f local_rot = node->getRotation();
1223 local_rot.Y = modulo360f(local_rot.Y - dtime * core::RADTODEG *
1224 m_prop.automatic_rotate);
1225 node->setRotation(local_rot);
1228 if (!getParent() && m_prop.automatic_face_movement_dir &&
1229 (fabs(m_velocity.Z) > 0.001f || fabs(m_velocity.X) > 0.001f)) {
1230 float target_yaw = atan2(m_velocity.Z, m_velocity.X) * 180 / M_PI
1231 + m_prop.automatic_face_movement_dir_offset;
1232 float max_rotation_per_sec =
1233 m_prop.automatic_face_movement_max_rotation_per_sec;
1235 if (max_rotation_per_sec > 0) {
1236 wrappedApproachShortest(m_rotation.Y, target_yaw,
1237 dtime * max_rotation_per_sec, 360.f);
1239 // Negative values of max_rotation_per_sec mean disabled.
1240 m_rotation.Y = target_yaw;
1243 rot_translator.val_current = m_rotation;
1247 if (m_animated_meshnode) {
1248 // Everything must be updated; the whole transform
1249 // chain as well as the animated mesh node.
1250 // Otherwise, bone attachments would be relative to
1251 // a position that's one frame old.
1253 updatePositionRecursive(m_matrixnode);
1254 m_animated_meshnode->updateAbsolutePosition();
1255 m_animated_meshnode->animateJoints();
1256 updateBonePosition();
1260 void GenericCAO::updateTexturePos()
1264 scene::ICameraSceneNode* camera =
1265 m_spritenode->getSceneManager()->getActiveCamera();
1268 v3f cam_to_entity = m_spritenode->getAbsolutePosition()
1269 - camera->getAbsolutePosition();
1270 cam_to_entity.normalize();
1272 int row = m_tx_basepos.Y;
1273 int col = m_tx_basepos.X;
1275 // Yawpitch goes rightwards
1276 if (m_tx_select_horiz_by_yawpitch) {
1277 if (cam_to_entity.Y > 0.75)
1279 else if (cam_to_entity.Y < -0.75)
1283 atan2(cam_to_entity.Z, cam_to_entity.X) / M_PI * 180.;
1284 float dir = mob_dir - m_rotation.Y;
1285 dir = wrapDegrees_180(dir);
1286 if (std::fabs(wrapDegrees_180(dir - 0)) <= 45.1f)
1288 else if(std::fabs(wrapDegrees_180(dir - 90)) <= 45.1f)
1290 else if(std::fabs(wrapDegrees_180(dir - 180)) <= 45.1f)
1292 else if(std::fabs(wrapDegrees_180(dir + 90)) <= 45.1f)
1299 // Animation goes downwards
1300 row += m_anim_frame;
1302 float txs = m_tx_size.X;
1303 float tys = m_tx_size.Y;
1304 setBillboardTextureMatrix(m_spritenode, txs, tys, col, row);
1307 else if (m_meshnode) {
1308 if (m_prop.visual == "upright_sprite") {
1309 int row = m_tx_basepos.Y;
1310 int col = m_tx_basepos.X;
1312 // Animation goes downwards
1313 row += m_anim_frame;
1315 const auto &tx = m_tx_size;
1316 v2f t[4] = { // cf. vertices in GenericCAO::addToScene()
1317 tx * v2f(col+1, row+1),
1318 tx * v2f(col, row+1),
1320 tx * v2f(col+1, row),
1322 auto mesh = m_meshnode->getMesh();
1323 setMeshBufferTextureCoords(mesh->getMeshBuffer(0), t, 4);
1324 setMeshBufferTextureCoords(mesh->getMeshBuffer(1), t, 4);
1329 // Do not pass by reference, see header.
1330 void GenericCAO::updateTextures(std::string mod)
1332 ITextureSource *tsrc = m_client->tsrc();
1334 bool use_trilinear_filter = g_settings->getBool("trilinear_filter");
1335 bool use_bilinear_filter = g_settings->getBool("bilinear_filter");
1336 bool use_anisotropic_filter = g_settings->getBool("anisotropic_filter");
1338 m_previous_texture_modifier = m_current_texture_modifier;
1339 m_current_texture_modifier = mod;
1340 m_glow = m_prop.glow;
1342 video::ITexture *shadow_texture = nullptr;
1343 if (auto shadow = RenderingEngine::get_shadow_renderer())
1344 shadow_texture = shadow->get_texture();
1346 const u32 TEXTURE_LAYER_SHADOW = 3;
1349 if (m_prop.visual == "sprite") {
1350 std::string texturestring = "no_texture.png";
1351 if (!m_prop.textures.empty())
1352 texturestring = m_prop.textures[0];
1353 texturestring += mod;
1354 m_spritenode->getMaterial(0).MaterialType = m_material_type;
1355 m_spritenode->getMaterial(0).MaterialTypeParam = 0.5f;
1356 m_spritenode->setMaterialTexture(0,
1357 tsrc->getTextureForMesh(texturestring));
1358 m_spritenode->setMaterialTexture(TEXTURE_LAYER_SHADOW, shadow_texture);
1360 // This allows setting per-material colors. However, until a real lighting
1361 // system is added, the code below will have no effect. Once MineTest
1362 // has directional lighting, it should work automatically.
1363 if (!m_prop.colors.empty()) {
1364 m_spritenode->getMaterial(0).AmbientColor = m_prop.colors[0];
1365 m_spritenode->getMaterial(0).DiffuseColor = m_prop.colors[0];
1366 m_spritenode->getMaterial(0).SpecularColor = m_prop.colors[0];
1369 m_spritenode->getMaterial(0).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1370 m_spritenode->getMaterial(0).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1371 m_spritenode->getMaterial(0).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1375 else if (m_animated_meshnode) {
1376 if (m_prop.visual == "mesh") {
1377 for (u32 i = 0; i < m_prop.textures.size() &&
1378 i < m_animated_meshnode->getMaterialCount(); ++i) {
1379 std::string texturestring = m_prop.textures[i];
1380 if (texturestring.empty())
1381 continue; // Empty texture string means don't modify that material
1382 texturestring += mod;
1383 video::ITexture* texture = tsrc->getTextureForMesh(texturestring);
1385 errorstream<<"GenericCAO::updateTextures(): Could not load texture "<<texturestring<<std::endl;
1389 // Set material flags and texture
1390 video::SMaterial& material = m_animated_meshnode->getMaterial(i);
1391 material.MaterialType = m_material_type;
1392 material.MaterialTypeParam = 0.5f;
1393 material.TextureLayer[0].Texture = texture;
1394 material.TextureLayer[TEXTURE_LAYER_SHADOW].Texture = shadow_texture;
1395 material.setFlag(video::EMF_LIGHTING, true);
1396 material.setFlag(video::EMF_BILINEAR_FILTER, false);
1397 material.setFlag(video::EMF_BACK_FACE_CULLING, m_prop.backface_culling);
1399 // don't filter low-res textures, makes them look blurry
1400 // player models have a res of 64
1401 const core::dimension2d<u32> &size = texture->getOriginalSize();
1402 const u32 res = std::min(size.Height, size.Width);
1403 use_trilinear_filter &= res > 64;
1404 use_bilinear_filter &= res > 64;
1406 m_animated_meshnode->getMaterial(i)
1407 .setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1408 m_animated_meshnode->getMaterial(i)
1409 .setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1410 m_animated_meshnode->getMaterial(i)
1411 .setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1413 for (u32 i = 0; i < m_prop.colors.size() &&
1414 i < m_animated_meshnode->getMaterialCount(); ++i)
1416 // This allows setting per-material colors. However, until a real lighting
1417 // system is added, the code below will have no effect. Once MineTest
1418 // has directional lighting, it should work automatically.
1419 m_animated_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i];
1420 m_animated_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i];
1421 m_animated_meshnode->getMaterial(i).SpecularColor = m_prop.colors[i];
1426 else if (m_meshnode) {
1427 if(m_prop.visual == "cube")
1429 for (u32 i = 0; i < 6; ++i)
1431 std::string texturestring = "no_texture.png";
1432 if(m_prop.textures.size() > i)
1433 texturestring = m_prop.textures[i];
1434 texturestring += mod;
1437 // Set material flags and texture
1438 video::SMaterial& material = m_meshnode->getMaterial(i);
1439 material.MaterialType = m_material_type;
1440 material.MaterialTypeParam = 0.5f;
1441 material.setFlag(video::EMF_LIGHTING, false);
1442 material.setFlag(video::EMF_BILINEAR_FILTER, false);
1443 material.setTexture(0,
1444 tsrc->getTextureForMesh(texturestring));
1445 material.setTexture(TEXTURE_LAYER_SHADOW, shadow_texture);
1446 material.getTextureMatrix(0).makeIdentity();
1448 // This allows setting per-material colors. However, until a real lighting
1449 // system is added, the code below will have no effect. Once MineTest
1450 // has directional lighting, it should work automatically.
1451 if(m_prop.colors.size() > i)
1453 m_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i];
1454 m_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i];
1455 m_meshnode->getMaterial(i).SpecularColor = m_prop.colors[i];
1458 m_meshnode->getMaterial(i).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1459 m_meshnode->getMaterial(i).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1460 m_meshnode->getMaterial(i).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1462 } else if (m_prop.visual == "upright_sprite") {
1463 scene::IMesh *mesh = m_meshnode->getMesh();
1465 std::string tname = "no_texture.png";
1466 if (!m_prop.textures.empty())
1467 tname = m_prop.textures[0];
1469 auto& material = m_meshnode->getMaterial(0);
1470 material.setTexture(0,
1471 tsrc->getTextureForMesh(tname));
1472 material.setTexture(TEXTURE_LAYER_SHADOW, shadow_texture);
1474 // This allows setting per-material colors. However, until a real lighting
1475 // system is added, the code below will have no effect. Once MineTest
1476 // has directional lighting, it should work automatically.
1477 if(!m_prop.colors.empty()) {
1478 material.AmbientColor = m_prop.colors[0];
1479 material.DiffuseColor = m_prop.colors[0];
1480 material.SpecularColor = m_prop.colors[0];
1483 material.setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1484 material.setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1485 material.setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1488 std::string tname = "no_texture.png";
1489 if (m_prop.textures.size() >= 2)
1490 tname = m_prop.textures[1];
1491 else if (!m_prop.textures.empty())
1492 tname = m_prop.textures[0];
1494 auto& material = m_meshnode->getMaterial(1);
1495 material.setTexture(0,
1496 tsrc->getTextureForMesh(tname));
1497 material.setTexture(TEXTURE_LAYER_SHADOW, shadow_texture);
1499 // This allows setting per-material colors. However, until a real lighting
1500 // system is added, the code below will have no effect. Once MineTest
1501 // has directional lighting, it should work automatically.
1502 if (m_prop.colors.size() >= 2) {
1503 material.AmbientColor = m_prop.colors[1];
1504 material.DiffuseColor = m_prop.colors[1];
1505 material.SpecularColor = m_prop.colors[1];
1506 } else if (!m_prop.colors.empty()) {
1507 material.AmbientColor = m_prop.colors[0];
1508 material.DiffuseColor = m_prop.colors[0];
1509 material.SpecularColor = m_prop.colors[0];
1512 material.setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1513 material.setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1514 material.setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1516 // Set mesh color (only if lighting is disabled)
1517 if (!m_prop.colors.empty() && m_glow < 0)
1518 setMeshColor(mesh, m_prop.colors[0]);
1521 // Prevent showing the player after changing texture
1522 if (m_is_local_player)
1523 updateMeshCulling();
1526 void GenericCAO::updateAnimation()
1528 if (!m_animated_meshnode)
1531 if (m_animated_meshnode->getStartFrame() != m_animation_range.X ||
1532 m_animated_meshnode->getEndFrame() != m_animation_range.Y)
1533 m_animated_meshnode->setFrameLoop(m_animation_range.X, m_animation_range.Y);
1534 if (m_animated_meshnode->getAnimationSpeed() != m_animation_speed)
1535 m_animated_meshnode->setAnimationSpeed(m_animation_speed);
1536 m_animated_meshnode->setTransitionTime(m_animation_blend);
1537 if (m_animated_meshnode->getLoopMode() != m_animation_loop)
1538 m_animated_meshnode->setLoopMode(m_animation_loop);
1541 void GenericCAO::updateAnimationSpeed()
1543 if (!m_animated_meshnode)
1546 m_animated_meshnode->setAnimationSpeed(m_animation_speed);
1549 void GenericCAO::updateBonePosition()
1551 if (m_bone_position.empty() || !m_animated_meshnode)
1554 m_animated_meshnode->setJointMode(scene::EJUOR_CONTROL); // To write positions to the mesh on render
1555 for (auto &it : m_bone_position) {
1556 std::string bone_name = it.first;
1557 scene::IBoneSceneNode* bone = m_animated_meshnode->getJointNode(bone_name.c_str());
1559 bone->setPosition(it.second.X);
1560 bone->setRotation(it.second.Y);
1564 // search through bones to find mistakenly rotated bones due to bug in Irrlicht
1565 for (u32 i = 0; i < m_animated_meshnode->getJointCount(); ++i) {
1566 scene::IBoneSceneNode *bone = m_animated_meshnode->getJointNode(i);
1570 //If bone is manually positioned there is no need to perform the bug check
1572 for (auto &it : m_bone_position) {
1573 if (it.first == bone->getName()) {
1581 // Workaround for Irrlicht bug
1582 // We check each bone to see if it has been rotated ~180deg from its expected position due to a bug in Irricht
1583 // when using EJUOR_CONTROL joint control. If the bug is detected we update the bone to the proper position
1584 // and update the bones transformation.
1585 v3f bone_rot = bone->getRelativeTransformation().getRotationDegrees();
1586 float offset = fabsf(bone_rot.X - bone->getRotation().X);
1587 if (offset > 179.9f && offset < 180.1f) {
1588 bone->setRotation(bone_rot);
1589 bone->updateAbsolutePosition();
1592 // The following is needed for set_bone_pos to propagate to
1593 // attached objects correctly.
1594 // Irrlicht ought to do this, but doesn't when using EJUOR_CONTROL.
1595 for (u32 i = 0; i < m_animated_meshnode->getJointCount(); ++i) {
1596 auto bone = m_animated_meshnode->getJointNode(i);
1597 // Look for the root bone.
1598 if (bone && bone->getParent() == m_animated_meshnode) {
1599 // Update entire skeleton.
1600 bone->updateAbsolutePositionOfAllChildren();
1606 void GenericCAO::updateAttachments()
1608 ClientActiveObject *parent = getParent();
1610 m_attached_to_local = parent && parent->isLocalPlayer();
1613 Following cases exist:
1614 m_attachment_parent_id == 0 && !parent
1615 This object is not attached
1616 m_attachment_parent_id != 0 && parent
1617 This object is attached
1618 m_attachment_parent_id != 0 && !parent
1619 This object will be attached as soon the parent is known
1620 m_attachment_parent_id == 0 && parent
1624 if (!parent) { // Detach or don't attach
1626 v3s16 camera_offset = m_env->getCameraOffset();
1627 v3f old_pos = getPosition();
1629 m_matrixnode->setParent(m_smgr->getRootSceneNode());
1630 getPosRotMatrix().setTranslation(old_pos - intToFloat(camera_offset, BS));
1631 m_matrixnode->updateAbsolutePosition();
1636 parent->updateAttachments();
1637 scene::ISceneNode *parent_node = parent->getSceneNode();
1638 scene::IAnimatedMeshSceneNode *parent_animated_mesh_node =
1639 parent->getAnimatedMeshSceneNode();
1640 if (parent_animated_mesh_node && !m_attachment_bone.empty()) {
1641 parent_node = parent_animated_mesh_node->getJointNode(m_attachment_bone.c_str());
1644 if (m_matrixnode && parent_node) {
1645 m_matrixnode->setParent(parent_node);
1646 parent_node->updateAbsolutePosition();
1647 getPosRotMatrix().setTranslation(m_attachment_position);
1648 //setPitchYawRoll(getPosRotMatrix(), m_attachment_rotation);
1649 // use Irrlicht eulers instead
1650 getPosRotMatrix().setRotationDegrees(m_attachment_rotation);
1651 m_matrixnode->updateAbsolutePosition();
1656 bool GenericCAO::visualExpiryRequired(const ObjectProperties &new_) const
1658 const ObjectProperties &old = m_prop;
1659 /* Visuals do not need to be expired for:
1660 * - nametag props: handled by updateNametag()
1661 * - textures: handled by updateTextures()
1662 * - sprite props: handled by updateTexturePos()
1663 * - glow: handled by updateLight()
1664 * - any other properties that do not change appearance
1667 bool uses_legacy_texture = new_.wield_item.empty() &&
1668 (new_.visual == "wielditem" || new_.visual == "item");
1669 // Ordered to compare primitive types before std::vectors
1670 return old.backface_culling != new_.backface_culling ||
1671 old.is_visible != new_.is_visible ||
1672 old.mesh != new_.mesh ||
1673 old.shaded != new_.shaded ||
1674 old.use_texture_alpha != new_.use_texture_alpha ||
1675 old.visual != new_.visual ||
1676 old.visual_size != new_.visual_size ||
1677 old.wield_item != new_.wield_item ||
1678 old.colors != new_.colors ||
1679 (uses_legacy_texture && old.textures != new_.textures);
1682 void GenericCAO::setProperties(ObjectProperties newprops)
1684 // Check what exactly changed
1685 bool expire_visuals = visualExpiryRequired(newprops);
1686 bool textures_changed = m_prop.textures != newprops.textures;
1689 m_prop = std::move(newprops);
1691 m_selection_box = m_prop.selectionbox;
1692 m_selection_box.MinEdge *= BS;
1693 m_selection_box.MaxEdge *= BS;
1695 m_tx_size.X = 1.0f / m_prop.spritediv.X;
1696 m_tx_size.Y = 1.0f / m_prop.spritediv.Y;
1698 if(!m_initial_tx_basepos_set){
1699 m_initial_tx_basepos_set = true;
1700 m_tx_basepos = m_prop.initial_sprite_basepos;
1702 if (m_is_local_player) {
1703 LocalPlayer *player = m_env->getLocalPlayer();
1704 player->makes_footstep_sound = m_prop.makes_footstep_sound;
1705 aabb3f collision_box = m_prop.collisionbox;
1706 collision_box.MinEdge *= BS;
1707 collision_box.MaxEdge *= BS;
1708 player->setCollisionbox(collision_box);
1709 player->setEyeHeight(m_prop.eye_height);
1710 player->setZoomFOV(m_prop.zoom_fov);
1713 if ((m_is_player && !m_is_local_player) && m_prop.nametag.empty())
1714 m_prop.nametag = m_name;
1715 if (m_is_local_player)
1716 m_prop.show_on_minimap = false;
1718 if (expire_visuals) {
1721 infostream << "GenericCAO: properties updated but expiring visuals"
1722 << " not necessary" << std::endl;
1723 if (textures_changed) {
1724 // don't update while punch texture modifier is active
1725 if (m_reset_textures_timer < 0)
1726 updateTextures(m_current_texture_modifier);
1733 void GenericCAO::processMessage(const std::string &data)
1735 //infostream<<"GenericCAO: Got message"<<std::endl;
1736 std::istringstream is(data, std::ios::binary);
1738 u8 cmd = readU8(is);
1739 if (cmd == AO_CMD_SET_PROPERTIES) {
1740 ObjectProperties newprops;
1741 newprops.show_on_minimap = m_is_player; // default
1743 newprops.deSerialize(is);
1744 setProperties(newprops);
1747 if (m_client->modsLoaded())
1748 m_client->getScript()->on_object_properties_change(m_id);
1750 } else if (cmd == AO_CMD_UPDATE_POSITION) {
1751 // Not sent by the server if this object is an attachment.
1752 // We might however get here if the server notices the object being detached before the client.
1753 m_position = readV3F32(is);
1754 m_velocity = readV3F32(is);
1755 m_acceleration = readV3F32(is);
1756 m_rotation = readV3F32(is);
1758 m_rotation = wrapDegrees_0_360_v3f(m_rotation);
1759 bool do_interpolate = readU8(is);
1760 bool is_end_position = readU8(is);
1761 float update_interval = readF32(is);
1763 // Place us a bit higher if we're physical, to not sink into
1764 // the ground due to sucky collision detection...
1766 m_position += v3f(0,0.002,0);
1768 if(getParent() != NULL) // Just in case
1773 if(!m_prop.physical)
1774 pos_translator.update(m_position, is_end_position, update_interval);
1776 pos_translator.init(m_position);
1778 rot_translator.update(m_rotation, false, update_interval);
1780 } else if (cmd == AO_CMD_SET_TEXTURE_MOD) {
1781 std::string mod = deSerializeString16(is);
1783 // immediately reset a engine issued texture modifier if a mod sends a different one
1784 if (m_reset_textures_timer > 0) {
1785 m_reset_textures_timer = -1;
1786 updateTextures(m_previous_texture_modifier);
1788 updateTextures(mod);
1789 } else if (cmd == AO_CMD_SET_SPRITE) {
1790 v2s16 p = readV2S16(is);
1791 int num_frames = readU16(is);
1792 float framelength = readF32(is);
1793 bool select_horiz_by_yawpitch = readU8(is);
1796 m_anim_num_frames = num_frames;
1798 m_anim_framelength = framelength;
1799 m_tx_select_horiz_by_yawpitch = select_horiz_by_yawpitch;
1802 } else if (cmd == AO_CMD_SET_PHYSICS_OVERRIDE) {
1803 float override_speed = readF32(is);
1804 float override_jump = readF32(is);
1805 float override_gravity = readF32(is);
1806 // these are sent inverted so we get true when the server sends nothing
1807 bool sneak = !readU8(is);
1808 bool sneak_glitch = !readU8(is);
1809 bool new_move = !readU8(is);
1812 if(m_is_local_player)
1814 Client *client = m_env->getGameDef();
1816 if (client->modsLoaded() && client->getScript()->on_recieve_physics_override(override_speed, override_jump, override_gravity, sneak, sneak_glitch, new_move))
1819 LocalPlayer *player = m_env->getLocalPlayer();
1820 player->physics_override_speed = override_speed;
1821 player->physics_override_jump = override_jump;
1822 player->physics_override_gravity = override_gravity;
1823 player->physics_override_sneak = sneak;
1824 player->physics_override_sneak_glitch = sneak_glitch;
1825 player->physics_override_new_move = new_move;
1827 } else if (cmd == AO_CMD_SET_ANIMATION) {
1828 // TODO: change frames send as v2s32 value
1829 v2f range = readV2F32(is);
1830 if (!m_is_local_player) {
1831 m_animation_range = v2s32((s32)range.X, (s32)range.Y);
1832 m_animation_speed = readF32(is);
1833 m_animation_blend = readF32(is);
1834 // these are sent inverted so we get true when the server sends nothing
1835 m_animation_loop = !readU8(is);
1838 LocalPlayer *player = m_env->getLocalPlayer();
1839 if(player->last_animation == NO_ANIM)
1841 m_animation_range = v2s32((s32)range.X, (s32)range.Y);
1842 m_animation_speed = readF32(is);
1843 m_animation_blend = readF32(is);
1844 // these are sent inverted so we get true when the server sends nothing
1845 m_animation_loop = !readU8(is);
1847 // update animation only if local animations present
1848 // and received animation is unknown (except idle animation)
1849 bool is_known = false;
1850 for (int i = 1;i<4;i++)
1852 if(m_animation_range.Y == player->local_animations[i].Y)
1856 (player->local_animations[1].Y + player->local_animations[2].Y < 1))
1860 // FIXME: ^ This code is trash. It's also broken.
1862 } else if (cmd == AO_CMD_SET_ANIMATION_SPEED) {
1863 m_animation_speed = readF32(is);
1864 updateAnimationSpeed();
1865 } else if (cmd == AO_CMD_SET_BONE_POSITION) {
1866 std::string bone = deSerializeString16(is);
1867 v3f position = readV3F32(is);
1868 v3f rotation = readV3F32(is);
1869 m_bone_position[bone] = core::vector2d<v3f>(position, rotation);
1871 // updateBonePosition(); now called every step
1872 } else if (cmd == AO_CMD_ATTACH_TO) {
1873 u16 parent_id = readS16(is);
1874 std::string bone = deSerializeString16(is);
1875 v3f position = readV3F32(is);
1876 v3f rotation = readV3F32(is);
1877 bool force_visible = readU8(is); // Returns false for EOF
1879 setAttachment(parent_id, bone, position, rotation, force_visible);
1880 } else if (cmd == AO_CMD_PUNCHED) {
1881 u16 result_hp = readU16(is);
1883 // Use this instead of the send damage to not interfere with prediction
1884 s32 damage = (s32)m_hp - (s32)result_hp;
1888 if (m_is_local_player)
1889 m_env->getLocalPlayer()->hp = m_hp;
1895 // TODO: Execute defined fast response
1896 // As there is no definition, make a smoke puff
1897 ClientSimpleObject *simple = createSmokePuff(
1898 m_smgr, m_env, m_position,
1899 v2f(m_prop.visual_size.X, m_prop.visual_size.Y) * BS);
1900 m_env->addSimpleObject(simple);
1901 } else if (m_reset_textures_timer < 0 && !m_prop.damage_texture_modifier.empty()) {
1902 m_reset_textures_timer = 0.05;
1904 m_reset_textures_timer += 0.05 * damage;
1905 // Cap damage overlay to 1 second
1906 m_reset_textures_timer = std::min(m_reset_textures_timer, 1.0f);
1907 updateTextures(m_current_texture_modifier + m_prop.damage_texture_modifier);
1912 // Same as 'Server::DiePlayer'
1913 clearParentAttachment();
1914 // Same as 'ObjectRef::l_remove'
1916 clearChildAttachments();
1918 if (m_client->modsLoaded())
1919 m_client->getScript()->on_object_hp_change(m_id);
1921 } else if (cmd == AO_CMD_UPDATE_ARMOR_GROUPS) {
1922 m_armor_groups.clear();
1923 int armor_groups_size = readU16(is);
1924 for(int i=0; i<armor_groups_size; i++)
1926 std::string name = deSerializeString16(is);
1927 int rating = readS16(is);
1928 m_armor_groups[name] = rating;
1930 } else if (cmd == AO_CMD_SPAWN_INFANT) {
1931 u16 child_id = readU16(is);
1932 u8 type = readU8(is); // maybe this will be useful later
1935 addAttachmentChild(child_id);
1936 } else if (cmd == AO_CMD_OBSOLETE1) {
1937 // Don't do anything and also don't log a warning
1939 warningstream << FUNCTION_NAME
1940 << ": unknown command or outdated client \""
1941 << +cmd << "\"" << std::endl;
1945 /* \pre punchitem != NULL
1947 bool GenericCAO::directReportPunch(v3f dir, const ItemStack *punchitem,
1948 float time_from_last_punch)
1950 assert(punchitem); // pre-condition
1951 const ToolCapabilities *toolcap =
1952 &punchitem->getToolCapabilities(m_client->idef());
1953 PunchDamageResult result = getPunchDamage(
1957 time_from_last_punch,
1960 if(result.did_punch && result.damage != 0)
1962 if(result.damage < m_hp)
1964 m_hp -= result.damage;
1967 // TODO: Execute defined fast response
1968 // As there is no definition, make a smoke puff
1969 ClientSimpleObject *simple = createSmokePuff(
1970 m_smgr, m_env, m_position,
1971 v2f(m_prop.visual_size.X, m_prop.visual_size.Y) * BS);
1972 m_env->addSimpleObject(simple);
1974 if (m_reset_textures_timer < 0 && !m_prop.damage_texture_modifier.empty()) {
1975 m_reset_textures_timer = 0.05;
1976 if (result.damage >= 2)
1977 m_reset_textures_timer += 0.05 * result.damage;
1978 // Cap damage overlay to 1 second
1979 m_reset_textures_timer = std::min(m_reset_textures_timer, 1.0f);
1980 updateTextures(m_current_texture_modifier + m_prop.damage_texture_modifier);
1987 std::string GenericCAO::debugInfoText()
1989 std::ostringstream os(std::ios::binary);
1990 os<<"GenericCAO hp="<<m_hp<<"\n";
1992 for(ItemGroupList::const_iterator i = m_armor_groups.begin();
1993 i != m_armor_groups.end(); ++i)
1995 os<<i->first<<"="<<i->second<<", ";
2001 void GenericCAO::updateMeshCulling()
2003 if (!m_is_local_player)
2006 const bool hidden = m_client->getCamera()->getCameraMode() == CAMERA_MODE_FIRST && ! g_settings->getBool("freecam");
2008 scene::ISceneNode *node = getSceneNode();
2013 if (m_prop.visual == "upright_sprite") {
2014 // upright sprite has no backface culling
2015 node->setMaterialFlag(video::EMF_FRONT_FACE_CULLING, hidden);
2020 // Hide the mesh by culling both front and
2021 // back faces. Serious hackyness but it works for our
2022 // purposes. This also preserves the skeletal armature.
2023 node->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
2025 node->setMaterialFlag(video::EMF_FRONT_FACE_CULLING,
2028 // Restore mesh visibility.
2029 node->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
2030 m_prop.backface_culling);
2031 node->setMaterialFlag(video::EMF_FRONT_FACE_CULLING,
2037 GenericCAO proto_GenericCAO(NULL, NULL);