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 <ITextSceneNode.h>
24 #include <IMeshManipulator.h>
25 #include <IAnimatedMeshSceneNode.h>
26 #include "client/client.h"
27 #include "client/renderingengine.h"
28 #include "client/sound.h"
29 #include "client/tile.h"
30 #include "util/basic_macros.h"
31 #include "util/numeric.h" // For IntervalLimiter & setPitchYawRoll
32 #include "util/serialize.h"
33 #include "camera.h" // CameraModes
34 #include "collision.h"
35 #include "content_cso.h"
36 #include "environment.h"
38 #include "localplayer.h"
42 #include "serialization.h" // For decompressZlib
46 #include "wieldmesh.h"
49 #include "client/shader.h"
50 #include "script/scripting_client.h"
51 #include "client/minimap.h"
54 struct ToolCapabilities;
56 std::unordered_map<u16, ClientActiveObject::Factory> ClientActiveObject::m_types;
59 void SmoothTranslator<T>::init(T current)
62 val_current = current;
65 anim_time_counter = 0;
70 void SmoothTranslator<T>::update(T new_target, bool is_end_position, float update_interval)
72 aim_is_end = is_end_position;
73 val_old = val_current;
74 val_target = new_target;
75 if (update_interval > 0) {
76 anim_time = update_interval;
78 if (anim_time < 0.001 || anim_time > 1.0)
79 anim_time = anim_time_counter;
81 anim_time = anim_time * 0.9 + anim_time_counter * 0.1;
83 anim_time_counter = 0;
87 void SmoothTranslator<T>::translate(f32 dtime)
89 anim_time_counter = anim_time_counter + dtime;
90 T val_diff = val_target - val_old;
92 if (anim_time > 0.001)
93 moveratio = anim_time_counter / anim_time;
94 f32 move_end = aim_is_end ? 1.0 : 1.5;
96 // Move a bit less than should, to avoid oscillation
97 moveratio = std::min(moveratio * 0.8f, move_end);
98 val_current = val_old + val_diff * moveratio;
101 void SmoothTranslatorWrapped::translate(f32 dtime)
103 anim_time_counter = anim_time_counter + dtime;
104 f32 val_diff = std::abs(val_target - val_old);
105 if (val_diff > 180.f)
106 val_diff = 360.f - val_diff;
109 if (anim_time > 0.001)
110 moveratio = anim_time_counter / anim_time;
111 f32 move_end = aim_is_end ? 1.0 : 1.5;
113 // Move a bit less than should, to avoid oscillation
114 moveratio = std::min(moveratio * 0.8f, move_end);
115 wrappedApproachShortest(val_current, val_target,
116 val_diff * moveratio, 360.f);
119 void SmoothTranslatorWrappedv3f::translate(f32 dtime)
121 anim_time_counter = anim_time_counter + dtime;
124 val_diff_v3f.X = std::abs(val_target.X - val_old.X);
125 val_diff_v3f.Y = std::abs(val_target.Y - val_old.Y);
126 val_diff_v3f.Z = std::abs(val_target.Z - val_old.Z);
128 if (val_diff_v3f.X > 180.f)
129 val_diff_v3f.X = 360.f - val_diff_v3f.X;
131 if (val_diff_v3f.Y > 180.f)
132 val_diff_v3f.Y = 360.f - val_diff_v3f.Y;
134 if (val_diff_v3f.Z > 180.f)
135 val_diff_v3f.Z = 360.f - val_diff_v3f.Z;
138 if (anim_time > 0.001)
139 moveratio = anim_time_counter / anim_time;
140 f32 move_end = aim_is_end ? 1.0 : 1.5;
142 // Move a bit less than should, to avoid oscillation
143 moveratio = std::min(moveratio * 0.8f, move_end);
144 wrappedApproachShortest(val_current.X, val_target.X,
145 val_diff_v3f.X * moveratio, 360.f);
147 wrappedApproachShortest(val_current.Y, val_target.Y,
148 val_diff_v3f.Y * moveratio, 360.f);
150 wrappedApproachShortest(val_current.Z, val_target.Z,
151 val_diff_v3f.Z * moveratio, 360.f);
158 static void setBillboardTextureMatrix(scene::IBillboardSceneNode *bill,
159 float txs, float tys, int col, int row)
161 video::SMaterial& material = bill->getMaterial(0);
162 core::matrix4& matrix = material.getTextureMatrix(0);
163 matrix.setTextureTranslate(txs*col, tys*row);
164 matrix.setTextureScale(txs, tys);
167 // Evaluate transform chain recursively; irrlicht does not do this for us
168 static void updatePositionRecursive(scene::ISceneNode *node)
170 scene::ISceneNode *parent = node->getParent();
172 updatePositionRecursive(parent);
173 node->updateAbsolutePosition();
180 class TestCAO : public ClientActiveObject
183 TestCAO(Client *client, ClientEnvironment *env);
184 virtual ~TestCAO() = default;
186 ActiveObjectType getType() const
188 return ACTIVEOBJECT_TYPE_TEST;
191 static ClientActiveObject* create(Client *client, ClientEnvironment *env);
193 void addToScene(ITextureSource *tsrc);
194 void removeFromScene(bool permanent);
195 void updateLight(u32 day_night_ratio);
196 void updateNodePos();
198 void step(float dtime, ClientEnvironment *env);
200 void processMessage(const std::string &data);
202 bool getCollisionBox(aabb3f *toset) const { return false; }
204 scene::IMeshSceneNode *m_node;
209 TestCAO proto_TestCAO(NULL, NULL);
211 TestCAO::TestCAO(Client *client, ClientEnvironment *env):
212 ClientActiveObject(0, client, env),
214 m_position(v3f(0,10*BS,0))
216 ClientActiveObject::registerType(getType(), create);
219 ClientActiveObject* TestCAO::create(Client *client, ClientEnvironment *env)
221 return new TestCAO(client, env);
224 void TestCAO::addToScene(ITextureSource *tsrc)
229 //video::IVideoDriver* driver = smgr->getVideoDriver();
231 scene::SMesh *mesh = new scene::SMesh();
232 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
233 video::SColor c(255,255,255,255);
234 video::S3DVertex vertices[4] =
236 video::S3DVertex(-BS/2,-BS/4,0, 0,0,0, c, 0,1),
237 video::S3DVertex(BS/2,-BS/4,0, 0,0,0, c, 1,1),
238 video::S3DVertex(BS/2,BS/4,0, 0,0,0, c, 1,0),
239 video::S3DVertex(-BS/2,BS/4,0, 0,0,0, c, 0,0),
241 u16 indices[] = {0,1,2,2,3,0};
242 buf->append(vertices, 4, indices, 6);
244 buf->getMaterial().setFlag(video::EMF_LIGHTING, true); // false
245 buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false);
246 buf->getMaterial().setTexture(0, tsrc->getTextureForMesh("rat.png"));
247 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
248 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
249 buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
251 mesh->addMeshBuffer(buf);
253 m_node = RenderingEngine::get_scene_manager()->addMeshSceneNode(mesh, NULL);
258 void TestCAO::removeFromScene(bool permanent)
267 void TestCAO::updateLight(u32 day_night_ratio)
271 void TestCAO::updateNodePos()
276 m_node->setPosition(m_position);
277 //m_node->setRotation(v3f(0, 45, 0));
280 void TestCAO::step(float dtime, ClientEnvironment *env)
284 v3f rot = m_node->getRotation();
285 //infostream<<"dtime="<<dtime<<", rot.Y="<<rot.Y<<std::endl;
286 rot.Y += dtime * 180;
287 m_node->setRotation(rot);
291 void TestCAO::processMessage(const std::string &data)
293 infostream<<"TestCAO: Got data: "<<data<<std::endl;
294 std::istringstream is(data, std::ios::binary);
312 #include "clientobject.h"
314 GenericCAO::GenericCAO(Client *client, ClientEnvironment *env):
315 ClientActiveObject(0, client, env)
317 if (client == NULL) {
318 ClientActiveObject::registerType(getType(), create);
324 bool GenericCAO::getCollisionBox(aabb3f *toset) const
328 //update collision box
329 toset->MinEdge = m_prop.collisionbox.MinEdge * BS;
330 toset->MaxEdge = m_prop.collisionbox.MaxEdge * BS;
332 toset->MinEdge += m_position;
333 toset->MaxEdge += m_position;
341 bool GenericCAO::collideWithObjects() const
343 return m_prop.collideWithObjects;
346 void GenericCAO::initialize(const std::string &data)
348 infostream<<"GenericCAO: Got init data"<<std::endl;
349 processInitData(data);
352 // Check if it's the current player
353 LocalPlayer *player = m_env->getLocalPlayer();
354 if (player && strcmp(player->getName(), m_name.c_str()) == 0) {
355 m_is_local_player = true;
356 m_is_visible = false;
357 player->setCAO(this);
359 m_prop.show_on_minimap = false;
363 m_enable_shaders = g_settings->getBool("enable_shaders");
366 void GenericCAO::processInitData(const std::string &data)
368 std::istringstream is(data, std::ios::binary);
369 const u8 version = readU8(is);
372 errorstream << "GenericCAO: Unsupported init data version"
377 // PROTOCOL_VERSION >= 37
378 m_name = deSerializeString16(is);
379 m_is_player = readU8(is);
381 m_position = readV3F32(is);
382 m_rotation = readV3F32(is);
385 const u8 num_messages = readU8(is);
387 for (int i = 0; i < num_messages; i++) {
388 std::string message = deSerializeString32(is);
389 processMessage(message);
392 m_rotation = wrapDegrees_0_360_v3f(m_rotation);
393 pos_translator.init(m_position);
394 rot_translator.init(m_rotation);
398 GenericCAO::~GenericCAO()
400 removeFromScene(true);
403 bool GenericCAO::getSelectionBox(aabb3f *toset) const
405 if (!m_prop.is_visible || !m_is_visible || m_is_local_player
406 || !m_prop.pointable) {
409 *toset = m_selection_box;
413 const v3f GenericCAO::getPosition() const
416 return pos_translator.val_current;
418 // Calculate real position in world based on MatrixNode
420 v3s16 camera_offset = m_env->getCameraOffset();
421 return m_matrixnode->getAbsolutePosition() +
422 intToFloat(camera_offset, BS);
428 const bool GenericCAO::isImmortal()
430 return itemgroup_get(getGroups(), "immortal");
433 scene::ISceneNode *GenericCAO::getSceneNode() const
439 if (m_animated_meshnode) {
440 return m_animated_meshnode;
443 if (m_wield_meshnode) {
444 return m_wield_meshnode;
453 scene::IAnimatedMeshSceneNode *GenericCAO::getAnimatedMeshSceneNode() const
455 return m_animated_meshnode;
458 void GenericCAO::setChildrenVisible(bool toset)
460 for (u16 cao_id : m_attachment_child_ids) {
461 GenericCAO *obj = m_env->getGenericCAO(cao_id);
463 // Check if the entity is forced to appear in first person.
464 obj->setVisible(obj->m_force_visible ? true : toset);
469 void GenericCAO::setAttachment(int parent_id, const std::string &bone,
470 v3f position, v3f rotation, bool force_visible)
472 int old_parent = m_attachment_parent_id;
473 m_attachment_parent_id = parent_id;
474 m_attachment_bone = bone;
475 m_attachment_position = position;
476 m_attachment_rotation = rotation;
477 m_force_visible = force_visible;
479 ClientActiveObject *parent = m_env->getActiveObject(parent_id);
481 if (parent_id != old_parent) {
483 m_waiting_for_reattach = 10;
484 if (auto *o = m_env->getActiveObject(old_parent))
485 o->removeAttachmentChild(m_id);
487 parent->addAttachmentChild(m_id);
492 // Forcibly show attachments if required by set_attach
493 if (m_force_visible) {
495 } else if (!m_is_local_player) {
496 // Objects attached to the local player should be hidden in first person
497 m_is_visible = !m_attached_to_local ||
498 m_client->getCamera()->getCameraMode() != CAMERA_MODE_FIRST || g_settings->getBool("freecam");
499 m_force_visible = false;
501 // Local players need to have this set,
502 // otherwise first person attachments fail.
507 void GenericCAO::getAttachment(int *parent_id, std::string *bone, v3f *position,
508 v3f *rotation, bool *force_visible) const
510 *parent_id = m_attachment_parent_id;
511 *bone = m_attachment_bone;
512 *position = m_attachment_position;
513 *rotation = m_attachment_rotation;
514 *force_visible = m_force_visible;
517 void GenericCAO::clearChildAttachments()
519 // Cannot use for-loop here: setAttachment() modifies 'm_attachment_child_ids'!
520 while (!m_attachment_child_ids.empty()) {
521 int child_id = *m_attachment_child_ids.begin();
523 if (ClientActiveObject *child = m_env->getActiveObject(child_id))
524 child->setAttachment(0, "", v3f(), v3f(), false);
526 removeAttachmentChild(child_id);
530 void GenericCAO::clearParentAttachment()
532 if (m_attachment_parent_id)
533 setAttachment(0, "", m_attachment_position, m_attachment_rotation, false);
535 setAttachment(0, "", v3f(), v3f(), false);
538 void GenericCAO::addAttachmentChild(int child_id)
540 m_attachment_child_ids.insert(child_id);
543 void GenericCAO::removeAttachmentChild(int child_id)
545 m_attachment_child_ids.erase(child_id);
548 ClientActiveObject* GenericCAO::getParent() const
550 return m_attachment_parent_id ? m_env->getActiveObject(m_attachment_parent_id) :
554 void GenericCAO::removeFromScene(bool permanent)
556 // Should be true when removing the object permanently
557 // and false when refreshing (eg: updating visuals)
558 if (m_env && permanent) {
559 // The client does not know whether this object does re-appear to
560 // a later time, thus do not clear child attachments.
562 clearParentAttachment();
566 m_meshnode->remove();
568 m_meshnode = nullptr;
569 } else if (m_animated_meshnode) {
570 m_animated_meshnode->remove();
571 m_animated_meshnode->drop();
572 m_animated_meshnode = nullptr;
573 } else if (m_wield_meshnode) {
574 m_wield_meshnode->remove();
575 m_wield_meshnode->drop();
576 m_wield_meshnode = nullptr;
577 } else if (m_spritenode) {
578 m_spritenode->remove();
579 m_spritenode->drop();
580 m_spritenode = nullptr;
584 m_matrixnode->remove();
585 m_matrixnode->drop();
586 m_matrixnode = nullptr;
590 m_client->getCamera()->removeNametag(m_nametag);
594 if (m_marker && m_client->getMinimap())
595 m_client->getMinimap()->removeMarker(&m_marker);
598 void GenericCAO::addToScene(ITextureSource *tsrc)
600 m_smgr = RenderingEngine::get_scene_manager();
602 if (getSceneNode() != NULL) {
606 m_visuals_expired = false;
608 if (!m_prop.is_visible)
611 infostream << "GenericCAO::addToScene(): " << m_prop.visual << std::endl;
613 if (m_enable_shaders) {
614 IShaderSource *shader_source = m_client->getShaderSource();
615 MaterialType material_type;
617 if (m_prop.shaded && m_prop.glow == 0)
618 material_type = (m_prop.use_texture_alpha) ?
619 TILE_MATERIAL_ALPHA : TILE_MATERIAL_BASIC;
621 material_type = (m_prop.use_texture_alpha) ?
622 TILE_MATERIAL_PLAIN_ALPHA : TILE_MATERIAL_PLAIN;
624 u32 shader_id = shader_source->getShader("object_shader", material_type, NDT_NORMAL);
625 m_material_type = shader_source->getShaderInfo(shader_id).material;
627 m_material_type = (m_prop.use_texture_alpha) ?
628 video::EMT_TRANSPARENT_ALPHA_CHANNEL : video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
631 auto grabMatrixNode = [this] {
632 m_matrixnode = RenderingEngine::get_scene_manager()->
633 addDummyTransformationSceneNode();
634 m_matrixnode->grab();
637 auto setSceneNodeMaterial = [this] (scene::ISceneNode *node) {
638 node->setMaterialFlag(video::EMF_LIGHTING, false);
639 node->setMaterialFlag(video::EMF_BILINEAR_FILTER, false);
640 node->setMaterialFlag(video::EMF_FOG_ENABLE, true);
641 node->setMaterialType(m_material_type);
643 if (m_enable_shaders) {
644 node->setMaterialFlag(video::EMF_GOURAUD_SHADING, false);
645 node->setMaterialFlag(video::EMF_NORMALIZE_NORMALS, true);
649 if (m_prop.visual == "sprite") {
651 m_spritenode = RenderingEngine::get_scene_manager()->addBillboardSceneNode(
652 m_matrixnode, v2f(1, 1), v3f(0,0,0), -1);
653 m_spritenode->grab();
654 m_spritenode->setMaterialTexture(0,
655 tsrc->getTextureForMesh("unknown_node.png"));
657 setSceneNodeMaterial(m_spritenode);
659 m_spritenode->setSize(v2f(m_prop.visual_size.X,
660 m_prop.visual_size.Y) * BS);
662 const float txs = 1.0 / 1;
663 const float tys = 1.0 / 1;
664 setBillboardTextureMatrix(m_spritenode,
667 } else if (m_prop.visual == "upright_sprite") {
669 scene::SMesh *mesh = new scene::SMesh();
670 double dx = BS * m_prop.visual_size.X / 2;
671 double dy = BS * m_prop.visual_size.Y / 2;
672 video::SColor c(0xFFFFFFFF);
675 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
676 video::S3DVertex vertices[4] = {
677 video::S3DVertex(-dx, -dy, 0, 0,0,1, c, 1,1),
678 video::S3DVertex( dx, -dy, 0, 0,0,1, c, 0,1),
679 video::S3DVertex( dx, dy, 0, 0,0,1, c, 0,0),
680 video::S3DVertex(-dx, dy, 0, 0,0,1, c, 1,0),
683 // Move minimal Y position to 0 (feet position)
684 for (video::S3DVertex &vertex : vertices)
687 u16 indices[] = {0,1,2,2,3,0};
688 buf->append(vertices, 4, indices, 6);
690 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
691 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
692 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
693 buf->getMaterial().MaterialType = m_material_type;
695 if (m_enable_shaders) {
696 buf->getMaterial().EmissiveColor = c;
697 buf->getMaterial().setFlag(video::EMF_GOURAUD_SHADING, false);
698 buf->getMaterial().setFlag(video::EMF_NORMALIZE_NORMALS, true);
702 mesh->addMeshBuffer(buf);
706 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
707 video::S3DVertex vertices[4] = {
708 video::S3DVertex( dx,-dy, 0, 0,0,-1, c, 1,1),
709 video::S3DVertex(-dx,-dy, 0, 0,0,-1, c, 0,1),
710 video::S3DVertex(-dx, dy, 0, 0,0,-1, c, 0,0),
711 video::S3DVertex( dx, dy, 0, 0,0,-1, c, 1,0),
714 // Move minimal Y position to 0 (feet position)
715 for (video::S3DVertex &vertex : vertices)
718 u16 indices[] = {0,1,2,2,3,0};
719 buf->append(vertices, 4, indices, 6);
721 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
722 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
723 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
724 buf->getMaterial().MaterialType = m_material_type;
726 if (m_enable_shaders) {
727 buf->getMaterial().EmissiveColor = c;
728 buf->getMaterial().setFlag(video::EMF_GOURAUD_SHADING, false);
729 buf->getMaterial().setFlag(video::EMF_NORMALIZE_NORMALS, true);
733 mesh->addMeshBuffer(buf);
736 m_meshnode = RenderingEngine::get_scene_manager()->
737 addMeshSceneNode(mesh, m_matrixnode);
740 // Set it to use the materials of the meshbuffers directly.
741 // This is needed for changing the texture in the future
742 m_meshnode->setReadOnlyMaterials(true);
743 } else if (m_prop.visual == "cube") {
745 scene::IMesh *mesh = createCubeMesh(v3f(BS,BS,BS));
746 m_meshnode = RenderingEngine::get_scene_manager()->
747 addMeshSceneNode(mesh, m_matrixnode);
751 m_meshnode->setScale(m_prop.visual_size);
752 m_meshnode->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
753 m_prop.backface_culling);
755 setSceneNodeMaterial(m_meshnode);
756 } else if (m_prop.visual == "mesh") {
758 scene::IAnimatedMesh *mesh = m_client->getMesh(m_prop.mesh, true);
760 m_animated_meshnode = RenderingEngine::get_scene_manager()->
761 addAnimatedMeshSceneNode(mesh, m_matrixnode);
762 m_animated_meshnode->grab();
763 mesh->drop(); // The scene node took hold of it
765 if (!checkMeshNormals(mesh)) {
766 infostream << "GenericCAO: recalculating normals for mesh "
767 << m_prop.mesh << std::endl;
768 m_smgr->getMeshManipulator()->
769 recalculateNormals(mesh, true, false);
772 m_animated_meshnode->animateJoints(); // Needed for some animations
773 m_animated_meshnode->setScale(m_prop.visual_size);
775 // set vertex colors to ensure alpha is set
776 setMeshColor(m_animated_meshnode->getMesh(), video::SColor(0xFFFFFFFF));
778 setAnimatedMeshColor(m_animated_meshnode, video::SColor(0xFFFFFFFF));
780 setSceneNodeMaterial(m_animated_meshnode);
782 m_animated_meshnode->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
783 m_prop.backface_culling);
785 errorstream<<"GenericCAO::addToScene(): Could not load mesh "<<m_prop.mesh<<std::endl;
786 } else if (m_prop.visual == "wielditem" || m_prop.visual == "item") {
789 if (m_prop.wield_item.empty()) {
790 // Old format, only textures are specified.
791 infostream << "textures: " << m_prop.textures.size() << std::endl;
792 if (!m_prop.textures.empty()) {
793 infostream << "textures[0]: " << m_prop.textures[0]
795 IItemDefManager *idef = m_client->idef();
796 item = ItemStack(m_prop.textures[0], 1, 0, idef);
799 infostream << "serialized form: " << m_prop.wield_item << std::endl;
800 item.deSerialize(m_prop.wield_item, m_client->idef());
802 m_wield_meshnode = new WieldMeshSceneNode(
803 RenderingEngine::get_scene_manager(), -1);
804 m_wield_meshnode->setItem(item, m_client,
805 (m_prop.visual == "wielditem"));
807 m_wield_meshnode->setScale(m_prop.visual_size / 2.0f);
808 m_wield_meshnode->setColor(video::SColor(0xFFFFFFFF));
810 infostream<<"GenericCAO::addToScene(): \""<<m_prop.visual
811 <<"\" not supported"<<std::endl;
814 /* don't update while punch texture modifier is active */
815 if (m_reset_textures_timer < 0)
816 updateTextures(m_current_texture_modifier);
818 scene::ISceneNode *node = getSceneNode();
820 if (node && m_matrixnode)
821 node->setParent(m_matrixnode);
827 updateBonePosition();
829 setNodeLight(m_last_light);
832 if (m_client->modsLoaded())
833 m_client->getScript()->on_object_add(m_id);
835 if (m_client->modsLoaded())
836 m_client->getScript()->on_object_properties_change(m_id);
839 void GenericCAO::updateLight(u32 day_night_ratio)
848 u16 npos = getLightPosition(pos);
849 for (u16 i = 0; i < npos; i++) {
851 MapNode n = m_env->getMap().getNode(pos[i], &this_ok);
853 u8 this_light = n.getLightBlend(day_night_ratio, m_client->ndef());
854 light_at_pos = MYMAX(light_at_pos, this_light);
859 light_at_pos = blend_light(day_night_ratio, LIGHT_SUN, 0);
861 u8 light = decode_light(light_at_pos + m_glow);
862 if (g_settings->getBool("fullbright"))
864 if (light != m_last_light) {
865 m_last_light = light;
870 void GenericCAO::setNodeLight(u8 light)
872 video::SColor color(255, light, light, light);
874 if (m_prop.visual == "wielditem" || m_prop.visual == "item") {
875 if (m_wield_meshnode)
876 m_wield_meshnode->setNodeLightColor(color);
880 if (m_enable_shaders) {
881 if (m_prop.visual == "upright_sprite") {
885 scene::IMesh *mesh = m_meshnode->getMesh();
886 for (u32 i = 0; i < mesh->getMeshBufferCount(); ++i) {
887 scene::IMeshBuffer *buf = mesh->getMeshBuffer(i);
888 buf->getMaterial().EmissiveColor = color;
891 scene::ISceneNode *node = getSceneNode();
895 for (u32 i = 0; i < node->getMaterialCount(); ++i) {
896 video::SMaterial &material = node->getMaterial(i);
897 material.EmissiveColor = color;
902 setMeshColor(m_meshnode->getMesh(), color);
903 } else if (m_animated_meshnode) {
904 setAnimatedMeshColor(m_animated_meshnode, color);
905 } else if (m_spritenode) {
906 m_spritenode->setColor(color);
911 u16 GenericCAO::getLightPosition(v3s16 *pos)
913 const auto &box = m_prop.collisionbox;
914 pos[0] = floatToInt(m_position + box.MinEdge * BS, BS);
915 pos[1] = floatToInt(m_position + box.MaxEdge * BS, BS);
917 // Skip center pos if it falls into the same node as Min or MaxEdge
918 if ((box.MaxEdge - box.MinEdge).getLengthSQ() < 3.0f)
920 pos[2] = floatToInt(m_position + box.getCenter() * BS, BS);
924 void GenericCAO::updateMarker()
926 if (!m_client->getMinimap())
929 if (!m_prop.show_on_minimap) {
931 m_client->getMinimap()->removeMarker(&m_marker);
938 scene::ISceneNode *node = getSceneNode();
941 m_marker = m_client->getMinimap()->addMarker(node);
944 void GenericCAO::updateNametag()
946 //if (m_is_local_player && ! g_settings->getBool("freecam")) // No nametag for local player
949 if (m_prop.nametag.empty() || m_prop.nametag_color.getAlpha() == 0) {
952 m_client->getCamera()->removeNametag(m_nametag);
958 scene::ISceneNode *node = getSceneNode();
963 pos.Y = m_prop.selectionbox.MaxEdge.Y + 0.3f;
966 m_nametag = m_client->getCamera()->addNametag(node,
967 m_prop.nametag, m_prop.nametag_color,
968 m_prop.nametag_bgcolor, pos, nametag_images);
971 m_nametag->text = m_prop.nametag;
972 m_nametag->textcolor = m_prop.nametag_color;
973 m_nametag->bgcolor = m_prop.nametag_bgcolor;
974 m_nametag->pos = pos;
975 m_nametag->setImages(nametag_images);
979 void GenericCAO::updateNodePos()
981 if (getParent() != NULL)
984 scene::ISceneNode *node = getSceneNode();
987 v3s16 camera_offset = m_env->getCameraOffset();
988 v3f pos = pos_translator.val_current -
989 intToFloat(camera_offset, BS);
990 getPosRotMatrix().setTranslation(pos);
991 if (node != m_spritenode) { // rotate if not a sprite
992 v3f rot = m_is_local_player ? -m_rotation : -rot_translator.val_current;
993 setPitchYawRoll(getPosRotMatrix(), rot);
998 void GenericCAO::step(float dtime, ClientEnvironment *env)
1000 // Handle model animations and update positions instantly to prevent lags
1001 if (m_is_local_player) {
1002 LocalPlayer *player = m_env->getLocalPlayer();
1003 m_position = player->getLegitPosition();
1004 pos_translator.val_current = m_position;
1005 if (! g_settings->getBool("freecam")) {
1006 m_rotation.Y = wrapDegrees_0_360(player->getYaw());
1007 rot_translator.val_current = m_rotation;
1011 int old_anim = player->last_animation;
1012 float old_anim_speed = player->last_animation_speed;
1013 m_velocity = v3f(0,0,0);
1014 m_acceleration = v3f(0,0,0);
1015 const PlayerControl &controls = player->getPlayerControl();
1017 bool walking = false;
1018 if ((controls.up || controls.down || controls.left || controls.right ||
1019 controls.forw_move_joystick_axis != 0.f ||
1020 controls.sidew_move_joystick_axis != 0.f) && ! g_settings->getBool("freecam"))
1023 f32 new_speed = player->local_animation_speed;
1024 v2s32 new_anim = v2s32(0,0);
1025 bool allow_update = false;
1027 // increase speed if using fast or flying fast
1028 if(((g_settings->getBool("fast_move") &&
1029 m_client->checkLocalPrivilege("fast")) &&
1031 (!player->touching_ground &&
1032 g_settings->getBool("free_move") &&
1033 m_client->checkLocalPrivilege("fly")))) || g_settings->getBool("freecam"))
1035 // slowdown speed if sneeking
1036 if (controls.sneak && walking && ! g_settings->getBool("no_slow"))
1039 if (walking && (controls.dig || controls.place)) {
1040 new_anim = player->local_animations[3];
1041 player->last_animation = WD_ANIM;
1042 } else if (walking) {
1043 new_anim = player->local_animations[1];
1044 player->last_animation = WALK_ANIM;
1045 } else if (controls.dig || controls.place) {
1046 new_anim = player->local_animations[2];
1047 player->last_animation = DIG_ANIM;
1050 // Apply animations if input detected and not attached
1051 // or set idle animation
1052 if ((new_anim.X + new_anim.Y) > 0 && !getParent()) {
1053 allow_update = true;
1054 m_animation_range = new_anim;
1055 m_animation_speed = new_speed;
1056 player->last_animation_speed = m_animation_speed;
1058 player->last_animation = NO_ANIM;
1060 if (old_anim != NO_ANIM) {
1061 m_animation_range = player->local_animations[0];
1066 // Update local player animations
1067 if ((player->last_animation != old_anim ||
1068 m_animation_speed != old_anim_speed) &&
1069 player->last_animation != NO_ANIM && allow_update)
1075 if (m_visuals_expired && m_smgr) {
1076 m_visuals_expired = false;
1078 // Attachments, part 1: All attached objects must be unparented first,
1079 // or Irrlicht causes a segmentation fault
1080 for (u16 cao_id : m_attachment_child_ids) {
1081 ClientActiveObject *obj = m_env->getActiveObject(cao_id);
1083 scene::ISceneNode *child_node = obj->getSceneNode();
1084 // The node's parent is always an IDummyTraformationSceneNode,
1085 // so we need to reparent that one instead.
1087 child_node->getParent()->setParent(m_smgr->getRootSceneNode());
1091 removeFromScene(false);
1092 addToScene(m_client->tsrc());
1094 // Attachments, part 2: Now that the parent has been refreshed, put its attachments back
1095 for (u16 cao_id : m_attachment_child_ids) {
1096 ClientActiveObject *obj = m_env->getActiveObject(cao_id);
1098 obj->updateAttachments();
1102 // Make sure m_is_visible is always applied
1103 scene::ISceneNode *node = getSceneNode();
1105 node->setVisible(m_is_visible);
1107 if(getParent() != NULL) // Attachments should be glued to their parent by Irrlicht
1109 // Set these for later
1110 m_position = getPosition();
1111 m_velocity = v3f(0,0,0);
1112 m_acceleration = v3f(0,0,0);
1113 pos_translator.val_current = m_position;
1114 pos_translator.val_target = m_position;
1116 rot_translator.translate(dtime);
1117 v3f lastpos = pos_translator.val_current;
1121 aabb3f box = m_prop.collisionbox;
1124 collisionMoveResult moveresult;
1125 f32 pos_max_d = BS*0.125; // Distance per iteration
1126 v3f p_pos = m_position;
1127 v3f p_velocity = m_velocity;
1128 moveresult = collisionMoveSimple(env,env->getGameDef(),
1129 pos_max_d, box, m_prop.stepheight, dtime,
1130 &p_pos, &p_velocity, m_acceleration,
1131 this, m_prop.collideWithObjects);
1134 m_velocity = p_velocity;
1136 bool is_end_position = moveresult.collides;
1137 pos_translator.update(m_position, is_end_position, dtime);
1139 m_position += dtime * m_velocity + 0.5 * dtime * dtime * m_acceleration;
1140 m_velocity += dtime * m_acceleration;
1141 pos_translator.update(m_position, pos_translator.aim_is_end,
1142 pos_translator.anim_time);
1144 pos_translator.translate(dtime);
1147 float moved = lastpos.getDistanceFrom(pos_translator.val_current);
1148 m_step_distance_counter += moved;
1149 if (m_step_distance_counter > 1.5f * BS) {
1150 m_step_distance_counter = 0.0f;
1151 if (!m_is_local_player && m_prop.makes_footstep_sound) {
1152 const NodeDefManager *ndef = m_client->ndef();
1153 v3s16 p = floatToInt(getPosition() +
1154 v3f(0.0f, (m_prop.collisionbox.MinEdge.Y - 0.5f) * BS, 0.0f), BS);
1155 MapNode n = m_env->getMap().getNode(p);
1156 SimpleSoundSpec spec = ndef->get(n).sound_footstep;
1157 // Reduce footstep gain, as non-local-player footsteps are
1160 m_client->sound()->playSoundAt(spec, false, getPosition());
1165 m_anim_timer += dtime;
1166 if(m_anim_timer >= m_anim_framelength)
1168 m_anim_timer -= m_anim_framelength;
1170 if(m_anim_frame >= m_anim_num_frames)
1176 if(m_reset_textures_timer >= 0)
1178 m_reset_textures_timer -= dtime;
1179 if(m_reset_textures_timer <= 0) {
1180 m_reset_textures_timer = -1;
1181 updateTextures(m_previous_texture_modifier);
1185 if (!getParent() && node && fabs(m_prop.automatic_rotate) > 0.001f) {
1186 // This is the child node's rotation. It is only used for automatic_rotate.
1187 v3f local_rot = node->getRotation();
1188 local_rot.Y = modulo360f(local_rot.Y - dtime * core::RADTODEG *
1189 m_prop.automatic_rotate);
1190 node->setRotation(local_rot);
1193 if (!getParent() && m_prop.automatic_face_movement_dir &&
1194 (fabs(m_velocity.Z) > 0.001f || fabs(m_velocity.X) > 0.001f)) {
1195 float target_yaw = atan2(m_velocity.Z, m_velocity.X) * 180 / M_PI
1196 + m_prop.automatic_face_movement_dir_offset;
1197 float max_rotation_per_sec =
1198 m_prop.automatic_face_movement_max_rotation_per_sec;
1200 if (max_rotation_per_sec > 0) {
1201 wrappedApproachShortest(m_rotation.Y, target_yaw,
1202 dtime * max_rotation_per_sec, 360.f);
1204 // Negative values of max_rotation_per_sec mean disabled.
1205 m_rotation.Y = target_yaw;
1208 rot_translator.val_current = m_rotation;
1212 if (m_animated_meshnode) {
1213 // Everything must be updated; the whole transform
1214 // chain as well as the animated mesh node.
1215 // Otherwise, bone attachments would be relative to
1216 // a position that's one frame old.
1218 updatePositionRecursive(m_matrixnode);
1219 m_animated_meshnode->updateAbsolutePosition();
1220 m_animated_meshnode->animateJoints();
1221 updateBonePosition();
1225 void GenericCAO::updateTexturePos()
1229 scene::ICameraSceneNode* camera =
1230 m_spritenode->getSceneManager()->getActiveCamera();
1233 v3f cam_to_entity = m_spritenode->getAbsolutePosition()
1234 - camera->getAbsolutePosition();
1235 cam_to_entity.normalize();
1237 int row = m_tx_basepos.Y;
1238 int col = m_tx_basepos.X;
1240 // Yawpitch goes rightwards
1241 if (m_tx_select_horiz_by_yawpitch) {
1242 if (cam_to_entity.Y > 0.75)
1244 else if (cam_to_entity.Y < -0.75)
1248 atan2(cam_to_entity.Z, cam_to_entity.X) / M_PI * 180.;
1249 float dir = mob_dir - m_rotation.Y;
1250 dir = wrapDegrees_180(dir);
1251 if (std::fabs(wrapDegrees_180(dir - 0)) <= 45.1f)
1253 else if(std::fabs(wrapDegrees_180(dir - 90)) <= 45.1f)
1255 else if(std::fabs(wrapDegrees_180(dir - 180)) <= 45.1f)
1257 else if(std::fabs(wrapDegrees_180(dir + 90)) <= 45.1f)
1264 // Animation goes downwards
1265 row += m_anim_frame;
1267 float txs = m_tx_size.X;
1268 float tys = m_tx_size.Y;
1269 setBillboardTextureMatrix(m_spritenode, txs, tys, col, row);
1272 else if (m_meshnode) {
1273 if (m_prop.visual == "upright_sprite") {
1274 int row = m_tx_basepos.Y;
1275 int col = m_tx_basepos.X;
1277 // Animation goes downwards
1278 row += m_anim_frame;
1280 const auto &tx = m_tx_size;
1281 v2f t[4] = { // cf. vertices in GenericCAO::addToScene()
1282 tx * v2f(col+1, row+1),
1283 tx * v2f(col, row+1),
1285 tx * v2f(col+1, row),
1287 auto mesh = m_meshnode->getMesh();
1288 setMeshBufferTextureCoords(mesh->getMeshBuffer(0), t, 4);
1289 setMeshBufferTextureCoords(mesh->getMeshBuffer(1), t, 4);
1294 // Do not pass by reference, see header.
1295 void GenericCAO::updateTextures(std::string mod)
1297 ITextureSource *tsrc = m_client->tsrc();
1299 bool use_trilinear_filter = g_settings->getBool("trilinear_filter");
1300 bool use_bilinear_filter = g_settings->getBool("bilinear_filter");
1301 bool use_anisotropic_filter = g_settings->getBool("anisotropic_filter");
1303 m_previous_texture_modifier = m_current_texture_modifier;
1304 m_current_texture_modifier = mod;
1305 m_glow = m_prop.glow;
1308 if (m_prop.visual == "sprite") {
1309 std::string texturestring = "unknown_node.png";
1310 if (!m_prop.textures.empty())
1311 texturestring = m_prop.textures[0];
1312 texturestring += mod;
1313 m_spritenode->getMaterial(0).MaterialType = m_material_type;
1314 m_spritenode->getMaterial(0).MaterialTypeParam = 0.5f;
1315 m_spritenode->setMaterialTexture(0,
1316 tsrc->getTextureForMesh(texturestring));
1318 // This allows setting per-material colors. However, until a real lighting
1319 // system is added, the code below will have no effect. Once MineTest
1320 // has directional lighting, it should work automatically.
1321 if (!m_prop.colors.empty()) {
1322 m_spritenode->getMaterial(0).AmbientColor = m_prop.colors[0];
1323 m_spritenode->getMaterial(0).DiffuseColor = m_prop.colors[0];
1324 m_spritenode->getMaterial(0).SpecularColor = m_prop.colors[0];
1327 m_spritenode->getMaterial(0).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1328 m_spritenode->getMaterial(0).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1329 m_spritenode->getMaterial(0).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1333 else if (m_animated_meshnode) {
1334 if (m_prop.visual == "mesh") {
1335 for (u32 i = 0; i < m_prop.textures.size() &&
1336 i < m_animated_meshnode->getMaterialCount(); ++i) {
1337 std::string texturestring = m_prop.textures[i];
1338 if (texturestring.empty())
1339 continue; // Empty texture string means don't modify that material
1340 texturestring += mod;
1341 video::ITexture* texture = tsrc->getTextureForMesh(texturestring);
1343 errorstream<<"GenericCAO::updateTextures(): Could not load texture "<<texturestring<<std::endl;
1347 // Set material flags and texture
1348 video::SMaterial& material = m_animated_meshnode->getMaterial(i);
1349 material.MaterialType = m_material_type;
1350 material.MaterialTypeParam = 0.5f;
1351 material.TextureLayer[0].Texture = texture;
1352 material.setFlag(video::EMF_LIGHTING, true);
1353 material.setFlag(video::EMF_BILINEAR_FILTER, false);
1354 material.setFlag(video::EMF_BACK_FACE_CULLING, m_prop.backface_culling);
1356 // don't filter low-res textures, makes them look blurry
1357 // player models have a res of 64
1358 const core::dimension2d<u32> &size = texture->getOriginalSize();
1359 const u32 res = std::min(size.Height, size.Width);
1360 use_trilinear_filter &= res > 64;
1361 use_bilinear_filter &= res > 64;
1363 m_animated_meshnode->getMaterial(i)
1364 .setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1365 m_animated_meshnode->getMaterial(i)
1366 .setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1367 m_animated_meshnode->getMaterial(i)
1368 .setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1370 for (u32 i = 0; i < m_prop.colors.size() &&
1371 i < m_animated_meshnode->getMaterialCount(); ++i)
1373 // This allows setting per-material colors. However, until a real lighting
1374 // system is added, the code below will have no effect. Once MineTest
1375 // has directional lighting, it should work automatically.
1376 m_animated_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i];
1377 m_animated_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i];
1378 m_animated_meshnode->getMaterial(i).SpecularColor = m_prop.colors[i];
1383 else if (m_meshnode) {
1384 if(m_prop.visual == "cube")
1386 for (u32 i = 0; i < 6; ++i)
1388 std::string texturestring = "unknown_node.png";
1389 if(m_prop.textures.size() > i)
1390 texturestring = m_prop.textures[i];
1391 texturestring += mod;
1394 // Set material flags and texture
1395 video::SMaterial& material = m_meshnode->getMaterial(i);
1396 material.MaterialType = m_material_type;
1397 material.MaterialTypeParam = 0.5f;
1398 material.setFlag(video::EMF_LIGHTING, false);
1399 material.setFlag(video::EMF_BILINEAR_FILTER, false);
1400 material.setTexture(0,
1401 tsrc->getTextureForMesh(texturestring));
1402 material.getTextureMatrix(0).makeIdentity();
1404 // This allows setting per-material colors. However, until a real lighting
1405 // system is added, the code below will have no effect. Once MineTest
1406 // has directional lighting, it should work automatically.
1407 if(m_prop.colors.size() > i)
1409 m_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i];
1410 m_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i];
1411 m_meshnode->getMaterial(i).SpecularColor = m_prop.colors[i];
1414 m_meshnode->getMaterial(i).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1415 m_meshnode->getMaterial(i).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1416 m_meshnode->getMaterial(i).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1418 } else if (m_prop.visual == "upright_sprite") {
1419 scene::IMesh *mesh = m_meshnode->getMesh();
1421 std::string tname = "unknown_object.png";
1422 if (!m_prop.textures.empty())
1423 tname = m_prop.textures[0];
1425 scene::IMeshBuffer *buf = mesh->getMeshBuffer(0);
1426 buf->getMaterial().setTexture(0,
1427 tsrc->getTextureForMesh(tname));
1429 // This allows setting per-material colors. However, until a real lighting
1430 // system is added, the code below will have no effect. Once MineTest
1431 // has directional lighting, it should work automatically.
1432 if(!m_prop.colors.empty()) {
1433 buf->getMaterial().AmbientColor = m_prop.colors[0];
1434 buf->getMaterial().DiffuseColor = m_prop.colors[0];
1435 buf->getMaterial().SpecularColor = m_prop.colors[0];
1438 buf->getMaterial().setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1439 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1440 buf->getMaterial().setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1443 std::string tname = "unknown_object.png";
1444 if (m_prop.textures.size() >= 2)
1445 tname = m_prop.textures[1];
1446 else if (!m_prop.textures.empty())
1447 tname = m_prop.textures[0];
1449 scene::IMeshBuffer *buf = mesh->getMeshBuffer(1);
1450 buf->getMaterial().setTexture(0,
1451 tsrc->getTextureForMesh(tname));
1453 // This allows setting per-material colors. However, until a real lighting
1454 // system is added, the code below will have no effect. Once MineTest
1455 // has directional lighting, it should work automatically.
1456 if (m_prop.colors.size() >= 2) {
1457 buf->getMaterial().AmbientColor = m_prop.colors[1];
1458 buf->getMaterial().DiffuseColor = m_prop.colors[1];
1459 buf->getMaterial().SpecularColor = m_prop.colors[1];
1460 } else if (!m_prop.colors.empty()) {
1461 buf->getMaterial().AmbientColor = m_prop.colors[0];
1462 buf->getMaterial().DiffuseColor = m_prop.colors[0];
1463 buf->getMaterial().SpecularColor = m_prop.colors[0];
1466 buf->getMaterial().setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1467 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1468 buf->getMaterial().setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1470 // Set mesh color (only if lighting is disabled)
1471 if (!m_prop.colors.empty() && m_glow < 0)
1472 setMeshColor(mesh, m_prop.colors[0]);
1475 // Prevent showing the player after changing texture
1476 if (m_is_local_player)
1477 updateMeshCulling();
1480 void GenericCAO::updateAnimation()
1482 if (!m_animated_meshnode)
1485 if (m_animated_meshnode->getStartFrame() != m_animation_range.X ||
1486 m_animated_meshnode->getEndFrame() != m_animation_range.Y)
1487 m_animated_meshnode->setFrameLoop(m_animation_range.X, m_animation_range.Y);
1488 if (m_animated_meshnode->getAnimationSpeed() != m_animation_speed)
1489 m_animated_meshnode->setAnimationSpeed(m_animation_speed);
1490 m_animated_meshnode->setTransitionTime(m_animation_blend);
1491 // Requires Irrlicht 1.8 or greater
1492 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR > 1
1493 if (m_animated_meshnode->getLoopMode() != m_animation_loop)
1494 m_animated_meshnode->setLoopMode(m_animation_loop);
1498 void GenericCAO::updateAnimationSpeed()
1500 if (!m_animated_meshnode)
1503 m_animated_meshnode->setAnimationSpeed(m_animation_speed);
1506 void GenericCAO::updateBonePosition()
1508 if (m_bone_position.empty() || !m_animated_meshnode)
1511 m_animated_meshnode->setJointMode(irr::scene::EJUOR_CONTROL); // To write positions to the mesh on render
1512 for (auto &it : m_bone_position) {
1513 std::string bone_name = it.first;
1514 irr::scene::IBoneSceneNode* bone = m_animated_meshnode->getJointNode(bone_name.c_str());
1516 bone->setPosition(it.second.X);
1517 bone->setRotation(it.second.Y);
1521 // search through bones to find mistakenly rotated bones due to bug in Irrlicht
1522 for (u32 i = 0; i < m_animated_meshnode->getJointCount(); ++i) {
1523 irr::scene::IBoneSceneNode *bone = m_animated_meshnode->getJointNode(i);
1527 //If bone is manually positioned there is no need to perform the bug check
1529 for (auto &it : m_bone_position) {
1530 if (it.first == bone->getName()) {
1538 // Workaround for Irrlicht bug
1539 // We check each bone to see if it has been rotated ~180deg from its expected position due to a bug in Irricht
1540 // when using EJUOR_CONTROL joint control. If the bug is detected we update the bone to the proper position
1541 // and update the bones transformation.
1542 v3f bone_rot = bone->getRelativeTransformation().getRotationDegrees();
1543 float offset = fabsf(bone_rot.X - bone->getRotation().X);
1544 if (offset > 179.9f && offset < 180.1f) {
1545 bone->setRotation(bone_rot);
1546 bone->updateAbsolutePosition();
1549 // The following is needed for set_bone_pos to propagate to
1550 // attached objects correctly.
1551 // Irrlicht ought to do this, but doesn't when using EJUOR_CONTROL.
1552 for (u32 i = 0; i < m_animated_meshnode->getJointCount(); ++i) {
1553 auto bone = m_animated_meshnode->getJointNode(i);
1554 // Look for the root bone.
1555 if (bone && bone->getParent() == m_animated_meshnode) {
1556 // Update entire skeleton.
1557 bone->updateAbsolutePositionOfAllChildren();
1563 void GenericCAO::updateAttachments()
1565 ClientActiveObject *parent = getParent();
1567 m_attached_to_local = parent && parent->isLocalPlayer();
1570 Following cases exist:
1571 m_attachment_parent_id == 0 && !parent
1572 This object is not attached
1573 m_attachment_parent_id != 0 && parent
1574 This object is attached
1575 m_attachment_parent_id != 0 && !parent
1576 This object will be attached as soon the parent is known
1577 m_attachment_parent_id == 0 && parent
1581 if (!parent) { // Detach or don't attach
1583 v3s16 camera_offset = m_env->getCameraOffset();
1584 v3f old_pos = getPosition();
1586 m_matrixnode->setParent(m_smgr->getRootSceneNode());
1587 getPosRotMatrix().setTranslation(old_pos - intToFloat(camera_offset, BS));
1588 m_matrixnode->updateAbsolutePosition();
1593 parent->updateAttachments();
1594 scene::ISceneNode *parent_node = parent->getSceneNode();
1595 scene::IAnimatedMeshSceneNode *parent_animated_mesh_node =
1596 parent->getAnimatedMeshSceneNode();
1597 if (parent_animated_mesh_node && !m_attachment_bone.empty()) {
1598 parent_node = parent_animated_mesh_node->getJointNode(m_attachment_bone.c_str());
1601 if (m_matrixnode && parent_node) {
1602 m_matrixnode->setParent(parent_node);
1603 parent_node->updateAbsolutePosition();
1604 getPosRotMatrix().setTranslation(m_attachment_position);
1605 //setPitchYawRoll(getPosRotMatrix(), m_attachment_rotation);
1606 // use Irrlicht eulers instead
1607 getPosRotMatrix().setRotationDegrees(m_attachment_rotation);
1608 m_matrixnode->updateAbsolutePosition();
1613 bool GenericCAO::visualExpiryRequired(const ObjectProperties &new_) const
1615 const ObjectProperties &old = m_prop;
1616 /* Visuals do not need to be expired for:
1617 * - nametag props: handled by updateNametag()
1618 * - textures: handled by updateTextures()
1619 * - sprite props: handled by updateTexturePos()
1620 * - glow: handled by updateLight()
1621 * - any other properties that do not change appearance
1624 bool uses_legacy_texture = new_.wield_item.empty() &&
1625 (new_.visual == "wielditem" || new_.visual == "item");
1626 // Ordered to compare primitive types before std::vectors
1627 return old.backface_culling != new_.backface_culling ||
1628 old.is_visible != new_.is_visible ||
1629 old.mesh != new_.mesh ||
1630 old.shaded != new_.shaded ||
1631 old.use_texture_alpha != new_.use_texture_alpha ||
1632 old.visual != new_.visual ||
1633 old.visual_size != new_.visual_size ||
1634 old.wield_item != new_.wield_item ||
1635 old.colors != new_.colors ||
1636 (uses_legacy_texture && old.textures != new_.textures);
1639 void GenericCAO::setProperties(ObjectProperties newprops)
1641 // Check what exactly changed
1642 bool expire_visuals = visualExpiryRequired(newprops);
1643 bool textures_changed = m_prop.textures != newprops.textures;
1646 m_prop = std::move(newprops);
1648 m_selection_box = m_prop.selectionbox;
1649 m_selection_box.MinEdge *= BS;
1650 m_selection_box.MaxEdge *= BS;
1652 m_tx_size.X = 1.0f / m_prop.spritediv.X;
1653 m_tx_size.Y = 1.0f / m_prop.spritediv.Y;
1655 if(!m_initial_tx_basepos_set){
1656 m_initial_tx_basepos_set = true;
1657 m_tx_basepos = m_prop.initial_sprite_basepos;
1659 if (m_is_local_player) {
1660 LocalPlayer *player = m_env->getLocalPlayer();
1661 player->makes_footstep_sound = m_prop.makes_footstep_sound;
1662 aabb3f collision_box = m_prop.collisionbox;
1663 collision_box.MinEdge *= BS;
1664 collision_box.MaxEdge *= BS;
1665 player->setCollisionbox(collision_box);
1666 player->setEyeHeight(m_prop.eye_height);
1667 player->setZoomFOV(m_prop.zoom_fov);
1670 if ((m_is_player && !m_is_local_player) && m_prop.nametag.empty())
1671 m_prop.nametag = m_name;
1672 if (m_is_local_player)
1673 m_prop.show_on_minimap = false;
1675 if (expire_visuals) {
1678 infostream << "GenericCAO: properties updated but expiring visuals"
1679 << " not necessary" << std::endl;
1680 if (textures_changed) {
1681 // don't update while punch texture modifier is active
1682 if (m_reset_textures_timer < 0)
1683 updateTextures(m_current_texture_modifier);
1690 void GenericCAO::processMessage(const std::string &data)
1692 //infostream<<"GenericCAO: Got message"<<std::endl;
1693 std::istringstream is(data, std::ios::binary);
1695 u8 cmd = readU8(is);
1696 if (cmd == AO_CMD_SET_PROPERTIES) {
1697 ObjectProperties newprops;
1698 newprops.show_on_minimap = m_is_player; // default
1700 newprops.deSerialize(is);
1701 setProperties(newprops);
1704 if (m_client->modsLoaded())
1705 m_client->getScript()->on_object_properties_change(m_id);
1707 } else if (cmd == AO_CMD_UPDATE_POSITION) {
1708 // Not sent by the server if this object is an attachment.
1709 // We might however get here if the server notices the object being detached before the client.
1710 m_position = readV3F32(is);
1711 m_velocity = readV3F32(is);
1712 m_acceleration = readV3F32(is);
1713 m_rotation = readV3F32(is);
1715 m_rotation = wrapDegrees_0_360_v3f(m_rotation);
1716 bool do_interpolate = readU8(is);
1717 bool is_end_position = readU8(is);
1718 float update_interval = readF32(is);
1720 // Place us a bit higher if we're physical, to not sink into
1721 // the ground due to sucky collision detection...
1723 m_position += v3f(0,0.002,0);
1725 if(getParent() != NULL) // Just in case
1730 if(!m_prop.physical)
1731 pos_translator.update(m_position, is_end_position, update_interval);
1733 pos_translator.init(m_position);
1735 rot_translator.update(m_rotation, false, update_interval);
1737 } else if (cmd == AO_CMD_SET_TEXTURE_MOD) {
1738 std::string mod = deSerializeString16(is);
1740 // immediately reset a engine issued texture modifier if a mod sends a different one
1741 if (m_reset_textures_timer > 0) {
1742 m_reset_textures_timer = -1;
1743 updateTextures(m_previous_texture_modifier);
1745 updateTextures(mod);
1746 } else if (cmd == AO_CMD_SET_SPRITE) {
1747 v2s16 p = readV2S16(is);
1748 int num_frames = readU16(is);
1749 float framelength = readF32(is);
1750 bool select_horiz_by_yawpitch = readU8(is);
1753 m_anim_num_frames = num_frames;
1754 m_anim_framelength = framelength;
1755 m_tx_select_horiz_by_yawpitch = select_horiz_by_yawpitch;
1758 } else if (cmd == AO_CMD_SET_PHYSICS_OVERRIDE) {
1759 float override_speed = readF32(is);
1760 float override_jump = readF32(is);
1761 float override_gravity = readF32(is);
1762 // these are sent inverted so we get true when the server sends nothing
1763 bool sneak = !readU8(is);
1764 bool sneak_glitch = !readU8(is);
1765 bool new_move = !readU8(is);
1768 if(m_is_local_player)
1770 Client *client = m_env->getGameDef();
1772 if (client->modsLoaded() && client->getScript()->on_recieve_physics_override(override_speed, override_jump, override_gravity, sneak, sneak_glitch, new_move))
1775 LocalPlayer *player = m_env->getLocalPlayer();
1776 player->physics_override_speed = override_speed;
1777 player->physics_override_jump = override_jump;
1778 player->physics_override_gravity = override_gravity;
1779 player->physics_override_sneak = sneak;
1780 player->physics_override_sneak_glitch = sneak_glitch;
1781 player->physics_override_new_move = new_move;
1783 } else if (cmd == AO_CMD_SET_ANIMATION) {
1784 // TODO: change frames send as v2s32 value
1785 v2f range = readV2F32(is);
1786 if (!m_is_local_player) {
1787 m_animation_range = v2s32((s32)range.X, (s32)range.Y);
1788 m_animation_speed = readF32(is);
1789 m_animation_blend = readF32(is);
1790 // these are sent inverted so we get true when the server sends nothing
1791 m_animation_loop = !readU8(is);
1794 LocalPlayer *player = m_env->getLocalPlayer();
1795 if(player->last_animation == NO_ANIM)
1797 m_animation_range = v2s32((s32)range.X, (s32)range.Y);
1798 m_animation_speed = readF32(is);
1799 m_animation_blend = readF32(is);
1800 // these are sent inverted so we get true when the server sends nothing
1801 m_animation_loop = !readU8(is);
1803 // update animation only if local animations present
1804 // and received animation is unknown (except idle animation)
1805 bool is_known = false;
1806 for (int i = 1;i<4;i++)
1808 if(m_animation_range.Y == player->local_animations[i].Y)
1812 (player->local_animations[1].Y + player->local_animations[2].Y < 1))
1817 } else if (cmd == AO_CMD_SET_ANIMATION_SPEED) {
1818 m_animation_speed = readF32(is);
1819 updateAnimationSpeed();
1820 } else if (cmd == AO_CMD_SET_BONE_POSITION) {
1821 std::string bone = deSerializeString16(is);
1822 v3f position = readV3F32(is);
1823 v3f rotation = readV3F32(is);
1824 m_bone_position[bone] = core::vector2d<v3f>(position, rotation);
1826 // updateBonePosition(); now called every step
1827 } else if (cmd == AO_CMD_ATTACH_TO) {
1828 u16 parent_id = readS16(is);
1829 std::string bone = deSerializeString16(is);
1830 v3f position = readV3F32(is);
1831 v3f rotation = readV3F32(is);
1832 bool force_visible = readU8(is); // Returns false for EOF
1834 setAttachment(parent_id, bone, position, rotation, force_visible);
1835 } else if (cmd == AO_CMD_PUNCHED) {
1836 u16 result_hp = readU16(is);
1838 // Use this instead of the send damage to not interfere with prediction
1839 s32 damage = (s32)m_hp - (s32)result_hp;
1843 if (m_is_local_player)
1844 m_env->getLocalPlayer()->hp = m_hp;
1850 // TODO: Execute defined fast response
1851 // As there is no definition, make a smoke puff
1852 ClientSimpleObject *simple = createSmokePuff(
1853 m_smgr, m_env, m_position,
1854 v2f(m_prop.visual_size.X, m_prop.visual_size.Y) * BS);
1855 m_env->addSimpleObject(simple);
1856 } else if (m_reset_textures_timer < 0 && !m_prop.damage_texture_modifier.empty()) {
1857 m_reset_textures_timer = 0.05;
1859 m_reset_textures_timer += 0.05 * damage;
1860 updateTextures(m_current_texture_modifier + m_prop.damage_texture_modifier);
1865 // Same as 'Server::DiePlayer'
1866 clearParentAttachment();
1867 // Same as 'ObjectRef::l_remove'
1869 clearChildAttachments();
1871 if (m_client->modsLoaded())
1872 m_client->getScript()->on_object_hp_change(m_id);
1874 } else if (cmd == AO_CMD_UPDATE_ARMOR_GROUPS) {
1875 m_armor_groups.clear();
1876 int armor_groups_size = readU16(is);
1877 for(int i=0; i<armor_groups_size; i++)
1879 std::string name = deSerializeString16(is);
1880 int rating = readS16(is);
1881 m_armor_groups[name] = rating;
1883 } else if (cmd == AO_CMD_SPAWN_INFANT) {
1884 u16 child_id = readU16(is);
1885 u8 type = readU8(is); // maybe this will be useful later
1888 addAttachmentChild(child_id);
1889 } else if (cmd == AO_CMD_OBSOLETE1) {
1890 // Don't do anything and also don't log a warning
1892 warningstream << FUNCTION_NAME
1893 << ": unknown command or outdated client \""
1894 << +cmd << "\"" << std::endl;
1898 /* \pre punchitem != NULL
1900 bool GenericCAO::directReportPunch(v3f dir, const ItemStack *punchitem,
1901 float time_from_last_punch)
1903 assert(punchitem); // pre-condition
1904 const ToolCapabilities *toolcap =
1905 &punchitem->getToolCapabilities(m_client->idef());
1906 PunchDamageResult result = getPunchDamage(
1910 time_from_last_punch);
1912 if(result.did_punch && result.damage != 0)
1914 if(result.damage < m_hp)
1916 m_hp -= result.damage;
1919 // TODO: Execute defined fast response
1920 // As there is no definition, make a smoke puff
1921 ClientSimpleObject *simple = createSmokePuff(
1922 m_smgr, m_env, m_position,
1923 v2f(m_prop.visual_size.X, m_prop.visual_size.Y) * BS);
1924 m_env->addSimpleObject(simple);
1926 if (m_reset_textures_timer < 0 && !m_prop.damage_texture_modifier.empty()) {
1927 m_reset_textures_timer = 0.05;
1928 if (result.damage >= 2)
1929 m_reset_textures_timer += 0.05 * result.damage;
1930 updateTextures(m_current_texture_modifier + m_prop.damage_texture_modifier);
1937 std::string GenericCAO::debugInfoText()
1939 std::ostringstream os(std::ios::binary);
1940 os<<"GenericCAO hp="<<m_hp<<"\n";
1942 for(ItemGroupList::const_iterator i = m_armor_groups.begin();
1943 i != m_armor_groups.end(); ++i)
1945 os<<i->first<<"="<<i->second<<", ";
1951 void GenericCAO::updateMeshCulling()
1953 if (!m_is_local_player)
1956 const bool hidden = m_client->getCamera()->getCameraMode() == CAMERA_MODE_FIRST && ! g_settings->getBool("freecam");
1958 if (m_meshnode && m_prop.visual == "upright_sprite") {
1959 u32 buffers = m_meshnode->getMesh()->getMeshBufferCount();
1960 for (u32 i = 0; i < buffers; i++) {
1961 video::SMaterial &mat = m_meshnode->getMesh()->getMeshBuffer(i)->getMaterial();
1962 // upright sprite has no backface culling
1963 mat.setFlag(video::EMF_FRONT_FACE_CULLING, hidden);
1968 irr::scene::ISceneNode *node = getSceneNode();
1973 // Hide the mesh by culling both front and
1974 // back faces. Serious hackyness but it works for our
1975 // purposes. This also preserves the skeletal armature.
1976 node->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
1978 node->setMaterialFlag(video::EMF_FRONT_FACE_CULLING,
1981 // Restore mesh visibility.
1982 node->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
1983 m_prop.backface_culling);
1984 node->setMaterialFlag(video::EMF_FRONT_FACE_CULLING,
1990 GenericCAO proto_GenericCAO(NULL, NULL);