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" // For IntervalLimiter & setPitchYawRoll
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 "client/minimap.h"
52 struct ToolCapabilities;
54 std::unordered_map<u16, ClientActiveObject::Factory> ClientActiveObject::m_types;
57 void SmoothTranslator<T>::init(T current)
60 val_current = current;
63 anim_time_counter = 0;
68 void SmoothTranslator<T>::update(T new_target, bool is_end_position, float update_interval)
70 aim_is_end = is_end_position;
71 val_old = val_current;
72 val_target = new_target;
73 if (update_interval > 0) {
74 anim_time = update_interval;
76 if (anim_time < 0.001 || anim_time > 1.0)
77 anim_time = anim_time_counter;
79 anim_time = anim_time * 0.9 + anim_time_counter * 0.1;
81 anim_time_counter = 0;
85 void SmoothTranslator<T>::translate(f32 dtime)
87 anim_time_counter = anim_time_counter + dtime;
88 T val_diff = val_target - val_old;
90 if (anim_time > 0.001)
91 moveratio = anim_time_counter / anim_time;
92 f32 move_end = aim_is_end ? 1.0 : 1.5;
94 // Move a bit less than should, to avoid oscillation
95 moveratio = std::min(moveratio * 0.8f, move_end);
96 val_current = val_old + val_diff * moveratio;
99 void SmoothTranslatorWrapped::translate(f32 dtime)
101 anim_time_counter = anim_time_counter + dtime;
102 f32 val_diff = std::abs(val_target - val_old);
103 if (val_diff > 180.f)
104 val_diff = 360.f - val_diff;
107 if (anim_time > 0.001)
108 moveratio = anim_time_counter / anim_time;
109 f32 move_end = aim_is_end ? 1.0 : 1.5;
111 // Move a bit less than should, to avoid oscillation
112 moveratio = std::min(moveratio * 0.8f, move_end);
113 wrappedApproachShortest(val_current, val_target,
114 val_diff * moveratio, 360.f);
117 void SmoothTranslatorWrappedv3f::translate(f32 dtime)
119 anim_time_counter = anim_time_counter + dtime;
122 val_diff_v3f.X = std::abs(val_target.X - val_old.X);
123 val_diff_v3f.Y = std::abs(val_target.Y - val_old.Y);
124 val_diff_v3f.Z = std::abs(val_target.Z - val_old.Z);
126 if (val_diff_v3f.X > 180.f)
127 val_diff_v3f.X = 360.f - val_diff_v3f.X;
129 if (val_diff_v3f.Y > 180.f)
130 val_diff_v3f.Y = 360.f - val_diff_v3f.Y;
132 if (val_diff_v3f.Z > 180.f)
133 val_diff_v3f.Z = 360.f - val_diff_v3f.Z;
136 if (anim_time > 0.001)
137 moveratio = anim_time_counter / anim_time;
138 f32 move_end = aim_is_end ? 1.0 : 1.5;
140 // Move a bit less than should, to avoid oscillation
141 moveratio = std::min(moveratio * 0.8f, move_end);
142 wrappedApproachShortest(val_current.X, val_target.X,
143 val_diff_v3f.X * moveratio, 360.f);
145 wrappedApproachShortest(val_current.Y, val_target.Y,
146 val_diff_v3f.Y * moveratio, 360.f);
148 wrappedApproachShortest(val_current.Z, val_target.Z,
149 val_diff_v3f.Z * moveratio, 360.f);
156 static void setBillboardTextureMatrix(scene::IBillboardSceneNode *bill,
157 float txs, float tys, int col, int row)
159 video::SMaterial& material = bill->getMaterial(0);
160 core::matrix4& matrix = material.getTextureMatrix(0);
161 matrix.setTextureTranslate(txs*col, tys*row);
162 matrix.setTextureScale(txs, tys);
165 // Evaluate transform chain recursively; irrlicht does not do this for us
166 static void updatePositionRecursive(scene::ISceneNode *node)
168 scene::ISceneNode *parent = node->getParent();
170 updatePositionRecursive(parent);
171 node->updateAbsolutePosition();
178 class TestCAO : public ClientActiveObject
181 TestCAO(Client *client, ClientEnvironment *env);
182 virtual ~TestCAO() = default;
184 ActiveObjectType getType() const
186 return ACTIVEOBJECT_TYPE_TEST;
189 static ClientActiveObject* create(Client *client, ClientEnvironment *env);
191 void addToScene(ITextureSource *tsrc, scene::ISceneManager *smgr);
192 void removeFromScene(bool permanent);
193 void updateLight(u32 day_night_ratio);
194 void updateNodePos();
196 void step(float dtime, ClientEnvironment *env);
198 void processMessage(const std::string &data);
200 bool getCollisionBox(aabb3f *toset) const { return false; }
202 scene::IMeshSceneNode *m_node;
207 TestCAO proto_TestCAO(NULL, NULL);
209 TestCAO::TestCAO(Client *client, ClientEnvironment *env):
210 ClientActiveObject(0, client, env),
212 m_position(v3f(0,10*BS,0))
214 ClientActiveObject::registerType(getType(), create);
217 ClientActiveObject* TestCAO::create(Client *client, ClientEnvironment *env)
219 return new TestCAO(client, env);
222 void TestCAO::addToScene(ITextureSource *tsrc, scene::ISceneManager *smgr)
227 //video::IVideoDriver* driver = smgr->getVideoDriver();
229 scene::SMesh *mesh = new scene::SMesh();
230 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
231 video::SColor c(255,255,255,255);
232 video::S3DVertex vertices[4] =
234 video::S3DVertex(-BS/2,-BS/4,0, 0,0,0, c, 0,1),
235 video::S3DVertex(BS/2,-BS/4,0, 0,0,0, c, 1,1),
236 video::S3DVertex(BS/2,BS/4,0, 0,0,0, c, 1,0),
237 video::S3DVertex(-BS/2,BS/4,0, 0,0,0, c, 0,0),
239 u16 indices[] = {0,1,2,2,3,0};
240 buf->append(vertices, 4, indices, 6);
242 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
243 buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false);
244 buf->getMaterial().setTexture(0, tsrc->getTextureForMesh("rat.png"));
245 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
246 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
247 buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
249 mesh->addMeshBuffer(buf);
251 m_node = smgr->addMeshSceneNode(mesh, NULL);
256 void TestCAO::removeFromScene(bool permanent)
265 void TestCAO::updateLight(u32 day_night_ratio)
269 void TestCAO::updateNodePos()
274 m_node->setPosition(m_position);
275 //m_node->setRotation(v3f(0, 45, 0));
278 void TestCAO::step(float dtime, ClientEnvironment *env)
282 v3f rot = m_node->getRotation();
283 //infostream<<"dtime="<<dtime<<", rot.Y="<<rot.Y<<std::endl;
284 rot.Y += dtime * 180;
285 m_node->setRotation(rot);
289 void TestCAO::processMessage(const std::string &data)
291 infostream<<"TestCAO: Got data: "<<data<<std::endl;
292 std::istringstream is(data, std::ios::binary);
310 #include "clientobject.h"
312 GenericCAO::GenericCAO(Client *client, ClientEnvironment *env):
313 ClientActiveObject(0, client, env)
315 if (client == NULL) {
316 ClientActiveObject::registerType(getType(), create);
322 bool GenericCAO::getCollisionBox(aabb3f *toset) const
326 //update collision box
327 toset->MinEdge = m_prop.collisionbox.MinEdge * BS;
328 toset->MaxEdge = m_prop.collisionbox.MaxEdge * BS;
330 toset->MinEdge += m_position;
331 toset->MaxEdge += m_position;
339 bool GenericCAO::collideWithObjects() const
341 return m_prop.collideWithObjects;
344 void GenericCAO::initialize(const std::string &data)
346 infostream<<"GenericCAO: Got init data"<<std::endl;
347 processInitData(data);
349 m_enable_shaders = g_settings->getBool("enable_shaders");
352 void GenericCAO::processInitData(const std::string &data)
354 std::istringstream is(data, std::ios::binary);
355 const u8 version = readU8(is);
358 errorstream << "GenericCAO: Unsupported init data version"
363 // PROTOCOL_VERSION >= 37
364 m_name = deSerializeString16(is);
365 m_is_player = readU8(is);
367 m_position = readV3F32(is);
368 m_rotation = readV3F32(is);
372 // Check if it's the current player
373 LocalPlayer *player = m_env->getLocalPlayer();
374 if (player && strcmp(player->getName(), m_name.c_str()) == 0) {
375 m_is_local_player = true;
376 m_is_visible = false;
377 player->setCAO(this);
381 const u8 num_messages = readU8(is);
383 for (int i = 0; i < num_messages; i++) {
384 std::string message = deSerializeString32(is);
385 processMessage(message);
388 m_rotation = wrapDegrees_0_360_v3f(m_rotation);
389 pos_translator.init(m_position);
390 rot_translator.init(m_rotation);
394 GenericCAO::~GenericCAO()
396 removeFromScene(true);
399 bool GenericCAO::getSelectionBox(aabb3f *toset) const
401 if (!m_prop.is_visible || !m_is_visible || m_is_local_player
402 || !m_prop.pointable) {
405 *toset = m_selection_box;
409 const v3f GenericCAO::getPosition() const
412 return pos_translator.val_current;
414 // Calculate real position in world based on MatrixNode
416 v3s16 camera_offset = m_env->getCameraOffset();
417 return m_matrixnode->getAbsolutePosition() +
418 intToFloat(camera_offset, BS);
424 const bool GenericCAO::isImmortal()
426 return itemgroup_get(getGroups(), "immortal");
429 scene::ISceneNode *GenericCAO::getSceneNode() const
435 if (m_animated_meshnode) {
436 return m_animated_meshnode;
439 if (m_wield_meshnode) {
440 return m_wield_meshnode;
449 scene::IAnimatedMeshSceneNode *GenericCAO::getAnimatedMeshSceneNode() const
451 return m_animated_meshnode;
454 void GenericCAO::setChildrenVisible(bool toset)
456 for (u16 cao_id : m_attachment_child_ids) {
457 GenericCAO *obj = m_env->getGenericCAO(cao_id);
459 // Check if the entity is forced to appear in first person.
460 obj->setVisible(obj->m_force_visible ? true : toset);
465 void GenericCAO::setAttachment(int parent_id, const std::string &bone,
466 v3f position, v3f rotation, bool force_visible)
468 int old_parent = m_attachment_parent_id;
469 m_attachment_parent_id = parent_id;
470 m_attachment_bone = bone;
471 m_attachment_position = position;
472 m_attachment_rotation = rotation;
473 m_force_visible = force_visible;
475 ClientActiveObject *parent = m_env->getActiveObject(parent_id);
477 if (parent_id != old_parent) {
478 if (auto *o = m_env->getActiveObject(old_parent))
479 o->removeAttachmentChild(m_id);
481 parent->addAttachmentChild(m_id);
485 // Forcibly show attachments if required by set_attach
486 if (m_force_visible) {
488 } else if (!m_is_local_player) {
489 // Objects attached to the local player should be hidden in first person
490 m_is_visible = !m_attached_to_local ||
491 m_client->getCamera()->getCameraMode() != CAMERA_MODE_FIRST;
492 m_force_visible = false;
494 // Local players need to have this set,
495 // otherwise first person attachments fail.
500 void GenericCAO::getAttachment(int *parent_id, std::string *bone, v3f *position,
501 v3f *rotation, bool *force_visible) const
503 *parent_id = m_attachment_parent_id;
504 *bone = m_attachment_bone;
505 *position = m_attachment_position;
506 *rotation = m_attachment_rotation;
507 *force_visible = m_force_visible;
510 void GenericCAO::clearChildAttachments()
512 // Cannot use for-loop here: setAttachment() modifies 'm_attachment_child_ids'!
513 while (!m_attachment_child_ids.empty()) {
514 int child_id = *m_attachment_child_ids.begin();
516 if (ClientActiveObject *child = m_env->getActiveObject(child_id))
517 child->setAttachment(0, "", v3f(), v3f(), false);
519 removeAttachmentChild(child_id);
523 void GenericCAO::clearParentAttachment()
525 if (m_attachment_parent_id)
526 setAttachment(0, "", m_attachment_position, m_attachment_rotation, false);
528 setAttachment(0, "", v3f(), v3f(), false);
531 void GenericCAO::addAttachmentChild(int child_id)
533 m_attachment_child_ids.insert(child_id);
536 void GenericCAO::removeAttachmentChild(int child_id)
538 m_attachment_child_ids.erase(child_id);
541 ClientActiveObject* GenericCAO::getParent() const
543 return m_attachment_parent_id ? m_env->getActiveObject(m_attachment_parent_id) :
547 void GenericCAO::removeFromScene(bool permanent)
549 // Should be true when removing the object permanently
550 // and false when refreshing (eg: updating visuals)
551 if (m_env && permanent) {
552 // The client does not know whether this object does re-appear to
553 // a later time, thus do not clear child attachments.
555 clearParentAttachment();
558 if (auto shadow = RenderingEngine::get_shadow_renderer())
559 shadow->removeNodeFromShadowList(getSceneNode());
562 m_meshnode->remove();
564 m_meshnode = nullptr;
565 } else if (m_animated_meshnode) {
566 m_animated_meshnode->remove();
567 m_animated_meshnode->drop();
568 m_animated_meshnode = nullptr;
569 } else if (m_wield_meshnode) {
570 m_wield_meshnode->remove();
571 m_wield_meshnode->drop();
572 m_wield_meshnode = nullptr;
573 } else if (m_spritenode) {
574 m_spritenode->remove();
575 m_spritenode->drop();
576 m_spritenode = nullptr;
580 m_matrixnode->remove();
581 m_matrixnode->drop();
582 m_matrixnode = nullptr;
586 m_client->getCamera()->removeNametag(m_nametag);
590 if (m_marker && m_client->getMinimap())
591 m_client->getMinimap()->removeMarker(&m_marker);
594 void GenericCAO::addToScene(ITextureSource *tsrc, scene::ISceneManager *smgr)
598 if (getSceneNode() != NULL) {
602 m_visuals_expired = false;
604 if (!m_prop.is_visible)
607 infostream << "GenericCAO::addToScene(): " << m_prop.visual << std::endl;
609 if (m_enable_shaders) {
610 IShaderSource *shader_source = m_client->getShaderSource();
611 MaterialType material_type;
613 if (m_prop.shaded && m_prop.glow == 0)
614 material_type = (m_prop.use_texture_alpha) ?
615 TILE_MATERIAL_ALPHA : TILE_MATERIAL_BASIC;
617 material_type = (m_prop.use_texture_alpha) ?
618 TILE_MATERIAL_PLAIN_ALPHA : TILE_MATERIAL_PLAIN;
620 u32 shader_id = shader_source->getShader("object_shader", material_type, NDT_NORMAL);
621 m_material_type = shader_source->getShaderInfo(shader_id).material;
623 m_material_type = (m_prop.use_texture_alpha) ?
624 video::EMT_TRANSPARENT_ALPHA_CHANNEL : video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
627 auto grabMatrixNode = [this] {
628 m_matrixnode = m_smgr->addDummyTransformationSceneNode();
629 m_matrixnode->grab();
632 auto setSceneNodeMaterial = [this] (scene::ISceneNode *node) {
633 node->setMaterialFlag(video::EMF_LIGHTING, false);
634 node->setMaterialFlag(video::EMF_BILINEAR_FILTER, false);
635 node->setMaterialFlag(video::EMF_FOG_ENABLE, true);
636 node->setMaterialType(m_material_type);
638 if (m_enable_shaders) {
639 node->setMaterialFlag(video::EMF_GOURAUD_SHADING, false);
640 node->setMaterialFlag(video::EMF_NORMALIZE_NORMALS, true);
644 if (m_prop.visual == "sprite") {
646 m_spritenode = m_smgr->addBillboardSceneNode(
647 m_matrixnode, v2f(1, 1), v3f(0,0,0), -1);
648 m_spritenode->grab();
649 m_spritenode->setMaterialTexture(0,
650 tsrc->getTextureForMesh("unknown_node.png"));
652 setSceneNodeMaterial(m_spritenode);
654 m_spritenode->setSize(v2f(m_prop.visual_size.X,
655 m_prop.visual_size.Y) * BS);
657 const float txs = 1.0 / 1;
658 const float tys = 1.0 / 1;
659 setBillboardTextureMatrix(m_spritenode,
662 } else if (m_prop.visual == "upright_sprite") {
664 scene::SMesh *mesh = new scene::SMesh();
665 double dx = BS * m_prop.visual_size.X / 2;
666 double dy = BS * m_prop.visual_size.Y / 2;
667 video::SColor c(0xFFFFFFFF);
670 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
671 video::S3DVertex vertices[4] = {
672 video::S3DVertex(-dx, -dy, 0, 0,0,1, c, 1,1),
673 video::S3DVertex( dx, -dy, 0, 0,0,1, c, 0,1),
674 video::S3DVertex( dx, dy, 0, 0,0,1, c, 0,0),
675 video::S3DVertex(-dx, dy, 0, 0,0,1, c, 1,0),
678 // Move minimal Y position to 0 (feet position)
679 for (video::S3DVertex &vertex : vertices)
682 u16 indices[] = {0,1,2,2,3,0};
683 buf->append(vertices, 4, indices, 6);
685 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
686 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
687 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
688 buf->getMaterial().MaterialType = m_material_type;
690 if (m_enable_shaders) {
691 buf->getMaterial().EmissiveColor = c;
692 buf->getMaterial().setFlag(video::EMF_GOURAUD_SHADING, false);
693 buf->getMaterial().setFlag(video::EMF_NORMALIZE_NORMALS, true);
697 mesh->addMeshBuffer(buf);
701 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
702 video::S3DVertex vertices[4] = {
703 video::S3DVertex( dx,-dy, 0, 0,0,-1, c, 1,1),
704 video::S3DVertex(-dx,-dy, 0, 0,0,-1, c, 0,1),
705 video::S3DVertex(-dx, dy, 0, 0,0,-1, c, 0,0),
706 video::S3DVertex( dx, dy, 0, 0,0,-1, c, 1,0),
709 // Move minimal Y position to 0 (feet position)
710 for (video::S3DVertex &vertex : vertices)
713 u16 indices[] = {0,1,2,2,3,0};
714 buf->append(vertices, 4, indices, 6);
716 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
717 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
718 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
719 buf->getMaterial().MaterialType = m_material_type;
721 if (m_enable_shaders) {
722 buf->getMaterial().EmissiveColor = c;
723 buf->getMaterial().setFlag(video::EMF_GOURAUD_SHADING, false);
724 buf->getMaterial().setFlag(video::EMF_NORMALIZE_NORMALS, true);
728 mesh->addMeshBuffer(buf);
731 m_meshnode = m_smgr->addMeshSceneNode(mesh, m_matrixnode);
734 // Set it to use the materials of the meshbuffers directly.
735 // This is needed for changing the texture in the future
736 m_meshnode->setReadOnlyMaterials(true);
737 } else if (m_prop.visual == "cube") {
739 scene::IMesh *mesh = createCubeMesh(v3f(BS,BS,BS));
740 m_meshnode = m_smgr->addMeshSceneNode(mesh, m_matrixnode);
744 m_meshnode->setScale(m_prop.visual_size);
745 m_meshnode->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
746 m_prop.backface_culling);
748 setSceneNodeMaterial(m_meshnode);
749 } else if (m_prop.visual == "mesh") {
751 scene::IAnimatedMesh *mesh = m_client->getMesh(m_prop.mesh, true);
753 m_animated_meshnode = m_smgr->addAnimatedMeshSceneNode(mesh, m_matrixnode);
754 m_animated_meshnode->grab();
755 mesh->drop(); // The scene node took hold of it
757 if (!checkMeshNormals(mesh)) {
758 infostream << "GenericCAO: recalculating normals for mesh "
759 << m_prop.mesh << std::endl;
760 m_smgr->getMeshManipulator()->
761 recalculateNormals(mesh, true, false);
764 m_animated_meshnode->animateJoints(); // Needed for some animations
765 m_animated_meshnode->setScale(m_prop.visual_size);
767 // set vertex colors to ensure alpha is set
768 setMeshColor(m_animated_meshnode->getMesh(), video::SColor(0xFFFFFFFF));
770 setAnimatedMeshColor(m_animated_meshnode, video::SColor(0xFFFFFFFF));
772 setSceneNodeMaterial(m_animated_meshnode);
774 m_animated_meshnode->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
775 m_prop.backface_culling);
777 errorstream<<"GenericCAO::addToScene(): Could not load mesh "<<m_prop.mesh<<std::endl;
778 } else if (m_prop.visual == "wielditem" || m_prop.visual == "item") {
781 if (m_prop.wield_item.empty()) {
782 // Old format, only textures are specified.
783 infostream << "textures: " << m_prop.textures.size() << std::endl;
784 if (!m_prop.textures.empty()) {
785 infostream << "textures[0]: " << m_prop.textures[0]
787 IItemDefManager *idef = m_client->idef();
788 item = ItemStack(m_prop.textures[0], 1, 0, idef);
791 infostream << "serialized form: " << m_prop.wield_item << std::endl;
792 item.deSerialize(m_prop.wield_item, m_client->idef());
794 m_wield_meshnode = new WieldMeshSceneNode(m_smgr, -1);
795 m_wield_meshnode->setItem(item, m_client,
796 (m_prop.visual == "wielditem"));
798 m_wield_meshnode->setScale(m_prop.visual_size / 2.0f);
799 m_wield_meshnode->setColor(video::SColor(0xFFFFFFFF));
801 infostream<<"GenericCAO::addToScene(): \""<<m_prop.visual
802 <<"\" not supported"<<std::endl;
805 /* don't update while punch texture modifier is active */
806 if (m_reset_textures_timer < 0)
807 updateTextures(m_current_texture_modifier);
809 if (scene::ISceneNode *node = getSceneNode()) {
811 node->setParent(m_matrixnode);
813 if (auto shadow = RenderingEngine::get_shadow_renderer())
814 shadow->addNodeToShadowList(node);
821 updateBonePosition();
823 setNodeLight(m_last_light);
827 void GenericCAO::updateLight(u32 day_night_ratio)
836 u16 npos = getLightPosition(pos);
837 for (u16 i = 0; i < npos; i++) {
839 MapNode n = m_env->getMap().getNode(pos[i], &this_ok);
841 u8 this_light = n.getLightBlend(day_night_ratio, m_client->ndef());
842 light_at_pos = MYMAX(light_at_pos, this_light);
847 light_at_pos = blend_light(day_night_ratio, LIGHT_SUN, 0);
849 u8 light = decode_light(light_at_pos + m_glow);
850 if (light != m_last_light) {
851 m_last_light = light;
856 void GenericCAO::setNodeLight(u8 light)
858 video::SColor color(255, light, light, light);
860 if (m_prop.visual == "wielditem" || m_prop.visual == "item") {
861 if (m_wield_meshnode)
862 m_wield_meshnode->setNodeLightColor(color);
866 if (m_enable_shaders) {
867 if (m_prop.visual == "upright_sprite") {
871 scene::IMesh *mesh = m_meshnode->getMesh();
872 for (u32 i = 0; i < mesh->getMeshBufferCount(); ++i) {
873 scene::IMeshBuffer *buf = mesh->getMeshBuffer(i);
874 buf->getMaterial().EmissiveColor = color;
877 scene::ISceneNode *node = getSceneNode();
881 for (u32 i = 0; i < node->getMaterialCount(); ++i) {
882 video::SMaterial &material = node->getMaterial(i);
883 material.EmissiveColor = color;
888 setMeshColor(m_meshnode->getMesh(), color);
889 } else if (m_animated_meshnode) {
890 setAnimatedMeshColor(m_animated_meshnode, color);
891 } else if (m_spritenode) {
892 m_spritenode->setColor(color);
897 u16 GenericCAO::getLightPosition(v3s16 *pos)
899 const auto &box = m_prop.collisionbox;
900 pos[0] = floatToInt(m_position + box.MinEdge * BS, BS);
901 pos[1] = floatToInt(m_position + box.MaxEdge * BS, BS);
903 // Skip center pos if it falls into the same node as Min or MaxEdge
904 if ((box.MaxEdge - box.MinEdge).getLengthSQ() < 3.0f)
906 pos[2] = floatToInt(m_position + box.getCenter() * BS, BS);
910 void GenericCAO::updateMarker()
912 if (!m_client->getMinimap())
915 if (!m_prop.show_on_minimap) {
917 m_client->getMinimap()->removeMarker(&m_marker);
924 scene::ISceneNode *node = getSceneNode();
927 m_marker = m_client->getMinimap()->addMarker(node);
930 void GenericCAO::updateNametag()
932 if (m_is_local_player) // No nametag for local player
935 if (m_prop.nametag.empty() || m_prop.nametag_color.getAlpha() == 0) {
938 m_client->getCamera()->removeNametag(m_nametag);
944 scene::ISceneNode *node = getSceneNode();
949 pos.Y = m_prop.selectionbox.MaxEdge.Y + 0.3f;
952 m_nametag = m_client->getCamera()->addNametag(node,
953 m_prop.nametag, m_prop.nametag_color,
954 m_prop.nametag_bgcolor, pos);
957 m_nametag->text = m_prop.nametag;
958 m_nametag->textcolor = m_prop.nametag_color;
959 m_nametag->bgcolor = m_prop.nametag_bgcolor;
960 m_nametag->pos = pos;
964 void GenericCAO::updateNodePos()
966 if (getParent() != NULL)
969 scene::ISceneNode *node = getSceneNode();
972 v3s16 camera_offset = m_env->getCameraOffset();
973 v3f pos = pos_translator.val_current -
974 intToFloat(camera_offset, BS);
975 getPosRotMatrix().setTranslation(pos);
976 if (node != m_spritenode) { // rotate if not a sprite
977 v3f rot = m_is_local_player ? -m_rotation : -rot_translator.val_current;
978 setPitchYawRoll(getPosRotMatrix(), rot);
983 void GenericCAO::step(float dtime, ClientEnvironment *env)
985 // Handle model animations and update positions instantly to prevent lags
986 if (m_is_local_player) {
987 LocalPlayer *player = m_env->getLocalPlayer();
988 m_position = player->getPosition();
989 pos_translator.val_current = m_position;
990 m_rotation.Y = wrapDegrees_0_360(player->getYaw());
991 rot_translator.val_current = m_rotation;
994 int old_anim = player->last_animation;
995 float old_anim_speed = player->last_animation_speed;
996 m_velocity = v3f(0,0,0);
997 m_acceleration = v3f(0,0,0);
998 const PlayerControl &controls = player->getPlayerControl();
1000 bool walking = false;
1001 if (controls.up || controls.down || controls.left || controls.right ||
1002 controls.forw_move_joystick_axis != 0.f ||
1003 controls.sidew_move_joystick_axis != 0.f)
1006 f32 new_speed = player->local_animation_speed;
1007 v2s32 new_anim = v2s32(0,0);
1008 bool allow_update = false;
1010 // increase speed if using fast or flying fast
1011 if((g_settings->getBool("fast_move") &&
1012 m_client->checkLocalPrivilege("fast")) &&
1014 (!player->touching_ground &&
1015 g_settings->getBool("free_move") &&
1016 m_client->checkLocalPrivilege("fly"))))
1018 // slowdown speed if sneeking
1019 if (controls.sneak && walking)
1022 if (walking && (controls.dig || controls.place)) {
1023 new_anim = player->local_animations[3];
1024 player->last_animation = WD_ANIM;
1025 } else if (walking) {
1026 new_anim = player->local_animations[1];
1027 player->last_animation = WALK_ANIM;
1028 } else if (controls.dig || controls.place) {
1029 new_anim = player->local_animations[2];
1030 player->last_animation = DIG_ANIM;
1033 // Apply animations if input detected and not attached
1034 // or set idle animation
1035 if ((new_anim.X + new_anim.Y) > 0 && !getParent()) {
1036 allow_update = true;
1037 m_animation_range = new_anim;
1038 m_animation_speed = new_speed;
1039 player->last_animation_speed = m_animation_speed;
1041 player->last_animation = NO_ANIM;
1043 if (old_anim != NO_ANIM) {
1044 m_animation_range = player->local_animations[0];
1049 // Update local player animations
1050 if ((player->last_animation != old_anim ||
1051 m_animation_speed != old_anim_speed) &&
1052 player->last_animation != NO_ANIM && allow_update)
1058 if (m_visuals_expired && m_smgr) {
1059 m_visuals_expired = false;
1061 // Attachments, part 1: All attached objects must be unparented first,
1062 // or Irrlicht causes a segmentation fault
1063 for (u16 cao_id : m_attachment_child_ids) {
1064 ClientActiveObject *obj = m_env->getActiveObject(cao_id);
1066 scene::ISceneNode *child_node = obj->getSceneNode();
1067 // The node's parent is always an IDummyTraformationSceneNode,
1068 // so we need to reparent that one instead.
1070 child_node->getParent()->setParent(m_smgr->getRootSceneNode());
1074 removeFromScene(false);
1075 addToScene(m_client->tsrc(), m_smgr);
1077 // Attachments, part 2: Now that the parent has been refreshed, put its attachments back
1078 for (u16 cao_id : m_attachment_child_ids) {
1079 ClientActiveObject *obj = m_env->getActiveObject(cao_id);
1081 obj->updateAttachments();
1085 // Make sure m_is_visible is always applied
1086 scene::ISceneNode *node = getSceneNode();
1088 node->setVisible(m_is_visible);
1090 if(getParent() != NULL) // Attachments should be glued to their parent by Irrlicht
1092 // Set these for later
1093 m_position = getPosition();
1094 m_velocity = v3f(0,0,0);
1095 m_acceleration = v3f(0,0,0);
1096 pos_translator.val_current = m_position;
1097 pos_translator.val_target = m_position;
1099 rot_translator.translate(dtime);
1100 v3f lastpos = pos_translator.val_current;
1104 aabb3f box = m_prop.collisionbox;
1107 collisionMoveResult moveresult;
1108 f32 pos_max_d = BS*0.125; // Distance per iteration
1109 v3f p_pos = m_position;
1110 v3f p_velocity = m_velocity;
1111 moveresult = collisionMoveSimple(env,env->getGameDef(),
1112 pos_max_d, box, m_prop.stepheight, dtime,
1113 &p_pos, &p_velocity, m_acceleration,
1114 this, m_prop.collideWithObjects);
1117 m_velocity = p_velocity;
1119 bool is_end_position = moveresult.collides;
1120 pos_translator.update(m_position, is_end_position, dtime);
1122 m_position += dtime * m_velocity + 0.5 * dtime * dtime * m_acceleration;
1123 m_velocity += dtime * m_acceleration;
1124 pos_translator.update(m_position, pos_translator.aim_is_end,
1125 pos_translator.anim_time);
1127 pos_translator.translate(dtime);
1130 float moved = lastpos.getDistanceFrom(pos_translator.val_current);
1131 m_step_distance_counter += moved;
1132 if (m_step_distance_counter > 1.5f * BS) {
1133 m_step_distance_counter = 0.0f;
1134 if (!m_is_local_player && m_prop.makes_footstep_sound) {
1135 const NodeDefManager *ndef = m_client->ndef();
1136 v3s16 p = floatToInt(getPosition() +
1137 v3f(0.0f, (m_prop.collisionbox.MinEdge.Y - 0.5f) * BS, 0.0f), BS);
1138 MapNode n = m_env->getMap().getNode(p);
1139 SimpleSoundSpec spec = ndef->get(n).sound_footstep;
1140 // Reduce footstep gain, as non-local-player footsteps are
1143 m_client->sound()->playSoundAt(spec, false, getPosition());
1148 m_anim_timer += dtime;
1149 if(m_anim_timer >= m_anim_framelength)
1151 m_anim_timer -= m_anim_framelength;
1153 if(m_anim_frame >= m_anim_num_frames)
1159 if(m_reset_textures_timer >= 0)
1161 m_reset_textures_timer -= dtime;
1162 if(m_reset_textures_timer <= 0) {
1163 m_reset_textures_timer = -1;
1164 updateTextures(m_previous_texture_modifier);
1168 if (!getParent() && node && fabs(m_prop.automatic_rotate) > 0.001f) {
1169 // This is the child node's rotation. It is only used for automatic_rotate.
1170 v3f local_rot = node->getRotation();
1171 local_rot.Y = modulo360f(local_rot.Y - dtime * core::RADTODEG *
1172 m_prop.automatic_rotate);
1173 node->setRotation(local_rot);
1176 if (!getParent() && m_prop.automatic_face_movement_dir &&
1177 (fabs(m_velocity.Z) > 0.001f || fabs(m_velocity.X) > 0.001f)) {
1178 float target_yaw = atan2(m_velocity.Z, m_velocity.X) * 180 / M_PI
1179 + m_prop.automatic_face_movement_dir_offset;
1180 float max_rotation_per_sec =
1181 m_prop.automatic_face_movement_max_rotation_per_sec;
1183 if (max_rotation_per_sec > 0) {
1184 wrappedApproachShortest(m_rotation.Y, target_yaw,
1185 dtime * max_rotation_per_sec, 360.f);
1187 // Negative values of max_rotation_per_sec mean disabled.
1188 m_rotation.Y = target_yaw;
1191 rot_translator.val_current = m_rotation;
1195 if (m_animated_meshnode) {
1196 // Everything must be updated; the whole transform
1197 // chain as well as the animated mesh node.
1198 // Otherwise, bone attachments would be relative to
1199 // a position that's one frame old.
1201 updatePositionRecursive(m_matrixnode);
1202 m_animated_meshnode->updateAbsolutePosition();
1203 m_animated_meshnode->animateJoints();
1204 updateBonePosition();
1208 void GenericCAO::updateTexturePos()
1212 scene::ICameraSceneNode* camera =
1213 m_spritenode->getSceneManager()->getActiveCamera();
1216 v3f cam_to_entity = m_spritenode->getAbsolutePosition()
1217 - camera->getAbsolutePosition();
1218 cam_to_entity.normalize();
1220 int row = m_tx_basepos.Y;
1221 int col = m_tx_basepos.X;
1223 // Yawpitch goes rightwards
1224 if (m_tx_select_horiz_by_yawpitch) {
1225 if (cam_to_entity.Y > 0.75)
1227 else if (cam_to_entity.Y < -0.75)
1231 atan2(cam_to_entity.Z, cam_to_entity.X) / M_PI * 180.;
1232 float dir = mob_dir - m_rotation.Y;
1233 dir = wrapDegrees_180(dir);
1234 if (std::fabs(wrapDegrees_180(dir - 0)) <= 45.1f)
1236 else if(std::fabs(wrapDegrees_180(dir - 90)) <= 45.1f)
1238 else if(std::fabs(wrapDegrees_180(dir - 180)) <= 45.1f)
1240 else if(std::fabs(wrapDegrees_180(dir + 90)) <= 45.1f)
1247 // Animation goes downwards
1248 row += m_anim_frame;
1250 float txs = m_tx_size.X;
1251 float tys = m_tx_size.Y;
1252 setBillboardTextureMatrix(m_spritenode, txs, tys, col, row);
1255 else if (m_meshnode) {
1256 if (m_prop.visual == "upright_sprite") {
1257 int row = m_tx_basepos.Y;
1258 int col = m_tx_basepos.X;
1260 // Animation goes downwards
1261 row += m_anim_frame;
1263 const auto &tx = m_tx_size;
1264 v2f t[4] = { // cf. vertices in GenericCAO::addToScene()
1265 tx * v2f(col+1, row+1),
1266 tx * v2f(col, row+1),
1268 tx * v2f(col+1, row),
1270 auto mesh = m_meshnode->getMesh();
1271 setMeshBufferTextureCoords(mesh->getMeshBuffer(0), t, 4);
1272 setMeshBufferTextureCoords(mesh->getMeshBuffer(1), t, 4);
1277 // Do not pass by reference, see header.
1278 void GenericCAO::updateTextures(std::string mod)
1280 ITextureSource *tsrc = m_client->tsrc();
1282 bool use_trilinear_filter = g_settings->getBool("trilinear_filter");
1283 bool use_bilinear_filter = g_settings->getBool("bilinear_filter");
1284 bool use_anisotropic_filter = g_settings->getBool("anisotropic_filter");
1286 m_previous_texture_modifier = m_current_texture_modifier;
1287 m_current_texture_modifier = mod;
1288 m_glow = m_prop.glow;
1291 if (m_prop.visual == "sprite") {
1292 std::string texturestring = "unknown_node.png";
1293 if (!m_prop.textures.empty())
1294 texturestring = m_prop.textures[0];
1295 texturestring += mod;
1296 m_spritenode->getMaterial(0).MaterialType = m_material_type;
1297 m_spritenode->getMaterial(0).MaterialTypeParam = 0.5f;
1298 m_spritenode->setMaterialTexture(0,
1299 tsrc->getTextureForMesh(texturestring));
1301 // This allows setting per-material colors. However, until a real lighting
1302 // system is added, the code below will have no effect. Once MineTest
1303 // has directional lighting, it should work automatically.
1304 if (!m_prop.colors.empty()) {
1305 m_spritenode->getMaterial(0).AmbientColor = m_prop.colors[0];
1306 m_spritenode->getMaterial(0).DiffuseColor = m_prop.colors[0];
1307 m_spritenode->getMaterial(0).SpecularColor = m_prop.colors[0];
1310 m_spritenode->getMaterial(0).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1311 m_spritenode->getMaterial(0).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1312 m_spritenode->getMaterial(0).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1316 else if (m_animated_meshnode) {
1317 if (m_prop.visual == "mesh") {
1318 for (u32 i = 0; i < m_prop.textures.size() &&
1319 i < m_animated_meshnode->getMaterialCount(); ++i) {
1320 std::string texturestring = m_prop.textures[i];
1321 if (texturestring.empty())
1322 continue; // Empty texture string means don't modify that material
1323 texturestring += mod;
1324 video::ITexture* texture = tsrc->getTextureForMesh(texturestring);
1326 errorstream<<"GenericCAO::updateTextures(): Could not load texture "<<texturestring<<std::endl;
1330 // Set material flags and texture
1331 video::SMaterial& material = m_animated_meshnode->getMaterial(i);
1332 material.MaterialType = m_material_type;
1333 material.MaterialTypeParam = 0.5f;
1334 material.TextureLayer[0].Texture = texture;
1335 material.setFlag(video::EMF_LIGHTING, true);
1336 material.setFlag(video::EMF_BILINEAR_FILTER, false);
1337 material.setFlag(video::EMF_BACK_FACE_CULLING, m_prop.backface_culling);
1339 // don't filter low-res textures, makes them look blurry
1340 // player models have a res of 64
1341 const core::dimension2d<u32> &size = texture->getOriginalSize();
1342 const u32 res = std::min(size.Height, size.Width);
1343 use_trilinear_filter &= res > 64;
1344 use_bilinear_filter &= res > 64;
1346 m_animated_meshnode->getMaterial(i)
1347 .setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1348 m_animated_meshnode->getMaterial(i)
1349 .setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1350 m_animated_meshnode->getMaterial(i)
1351 .setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1353 for (u32 i = 0; i < m_prop.colors.size() &&
1354 i < m_animated_meshnode->getMaterialCount(); ++i)
1356 // This allows setting per-material colors. However, until a real lighting
1357 // system is added, the code below will have no effect. Once MineTest
1358 // has directional lighting, it should work automatically.
1359 m_animated_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i];
1360 m_animated_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i];
1361 m_animated_meshnode->getMaterial(i).SpecularColor = m_prop.colors[i];
1366 else if (m_meshnode) {
1367 if(m_prop.visual == "cube")
1369 for (u32 i = 0; i < 6; ++i)
1371 std::string texturestring = "unknown_node.png";
1372 if(m_prop.textures.size() > i)
1373 texturestring = m_prop.textures[i];
1374 texturestring += mod;
1377 // Set material flags and texture
1378 video::SMaterial& material = m_meshnode->getMaterial(i);
1379 material.MaterialType = m_material_type;
1380 material.MaterialTypeParam = 0.5f;
1381 material.setFlag(video::EMF_LIGHTING, false);
1382 material.setFlag(video::EMF_BILINEAR_FILTER, false);
1383 material.setTexture(0,
1384 tsrc->getTextureForMesh(texturestring));
1385 material.getTextureMatrix(0).makeIdentity();
1387 // This allows setting per-material colors. However, until a real lighting
1388 // system is added, the code below will have no effect. Once MineTest
1389 // has directional lighting, it should work automatically.
1390 if(m_prop.colors.size() > i)
1392 m_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i];
1393 m_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i];
1394 m_meshnode->getMaterial(i).SpecularColor = m_prop.colors[i];
1397 m_meshnode->getMaterial(i).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1398 m_meshnode->getMaterial(i).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1399 m_meshnode->getMaterial(i).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1401 } else if (m_prop.visual == "upright_sprite") {
1402 scene::IMesh *mesh = m_meshnode->getMesh();
1404 std::string tname = "unknown_object.png";
1405 if (!m_prop.textures.empty())
1406 tname = m_prop.textures[0];
1408 scene::IMeshBuffer *buf = mesh->getMeshBuffer(0);
1409 buf->getMaterial().setTexture(0,
1410 tsrc->getTextureForMesh(tname));
1412 // This allows setting per-material colors. However, until a real lighting
1413 // system is added, the code below will have no effect. Once MineTest
1414 // has directional lighting, it should work automatically.
1415 if(!m_prop.colors.empty()) {
1416 buf->getMaterial().AmbientColor = m_prop.colors[0];
1417 buf->getMaterial().DiffuseColor = m_prop.colors[0];
1418 buf->getMaterial().SpecularColor = m_prop.colors[0];
1421 buf->getMaterial().setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1422 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1423 buf->getMaterial().setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1426 std::string tname = "unknown_object.png";
1427 if (m_prop.textures.size() >= 2)
1428 tname = m_prop.textures[1];
1429 else if (!m_prop.textures.empty())
1430 tname = m_prop.textures[0];
1432 scene::IMeshBuffer *buf = mesh->getMeshBuffer(1);
1433 buf->getMaterial().setTexture(0,
1434 tsrc->getTextureForMesh(tname));
1436 // This allows setting per-material colors. However, until a real lighting
1437 // system is added, the code below will have no effect. Once MineTest
1438 // has directional lighting, it should work automatically.
1439 if (m_prop.colors.size() >= 2) {
1440 buf->getMaterial().AmbientColor = m_prop.colors[1];
1441 buf->getMaterial().DiffuseColor = m_prop.colors[1];
1442 buf->getMaterial().SpecularColor = m_prop.colors[1];
1443 } else if (!m_prop.colors.empty()) {
1444 buf->getMaterial().AmbientColor = m_prop.colors[0];
1445 buf->getMaterial().DiffuseColor = m_prop.colors[0];
1446 buf->getMaterial().SpecularColor = m_prop.colors[0];
1449 buf->getMaterial().setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1450 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1451 buf->getMaterial().setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1453 // Set mesh color (only if lighting is disabled)
1454 if (!m_prop.colors.empty() && m_glow < 0)
1455 setMeshColor(mesh, m_prop.colors[0]);
1458 // Prevent showing the player after changing texture
1459 if (m_is_local_player)
1460 updateMeshCulling();
1463 void GenericCAO::updateAnimation()
1465 if (!m_animated_meshnode)
1468 if (m_animated_meshnode->getStartFrame() != m_animation_range.X ||
1469 m_animated_meshnode->getEndFrame() != m_animation_range.Y)
1470 m_animated_meshnode->setFrameLoop(m_animation_range.X, m_animation_range.Y);
1471 if (m_animated_meshnode->getAnimationSpeed() != m_animation_speed)
1472 m_animated_meshnode->setAnimationSpeed(m_animation_speed);
1473 m_animated_meshnode->setTransitionTime(m_animation_blend);
1474 if (m_animated_meshnode->getLoopMode() != m_animation_loop)
1475 m_animated_meshnode->setLoopMode(m_animation_loop);
1478 void GenericCAO::updateAnimationSpeed()
1480 if (!m_animated_meshnode)
1483 m_animated_meshnode->setAnimationSpeed(m_animation_speed);
1486 void GenericCAO::updateBonePosition()
1488 if (m_bone_position.empty() || !m_animated_meshnode)
1491 m_animated_meshnode->setJointMode(scene::EJUOR_CONTROL); // To write positions to the mesh on render
1492 for (auto &it : m_bone_position) {
1493 std::string bone_name = it.first;
1494 scene::IBoneSceneNode* bone = m_animated_meshnode->getJointNode(bone_name.c_str());
1496 bone->setPosition(it.second.X);
1497 bone->setRotation(it.second.Y);
1501 // search through bones to find mistakenly rotated bones due to bug in Irrlicht
1502 for (u32 i = 0; i < m_animated_meshnode->getJointCount(); ++i) {
1503 scene::IBoneSceneNode *bone = m_animated_meshnode->getJointNode(i);
1507 //If bone is manually positioned there is no need to perform the bug check
1509 for (auto &it : m_bone_position) {
1510 if (it.first == bone->getName()) {
1518 // Workaround for Irrlicht bug
1519 // We check each bone to see if it has been rotated ~180deg from its expected position due to a bug in Irricht
1520 // when using EJUOR_CONTROL joint control. If the bug is detected we update the bone to the proper position
1521 // and update the bones transformation.
1522 v3f bone_rot = bone->getRelativeTransformation().getRotationDegrees();
1523 float offset = fabsf(bone_rot.X - bone->getRotation().X);
1524 if (offset > 179.9f && offset < 180.1f) {
1525 bone->setRotation(bone_rot);
1526 bone->updateAbsolutePosition();
1529 // The following is needed for set_bone_pos to propagate to
1530 // attached objects correctly.
1531 // Irrlicht ought to do this, but doesn't when using EJUOR_CONTROL.
1532 for (u32 i = 0; i < m_animated_meshnode->getJointCount(); ++i) {
1533 auto bone = m_animated_meshnode->getJointNode(i);
1534 // Look for the root bone.
1535 if (bone && bone->getParent() == m_animated_meshnode) {
1536 // Update entire skeleton.
1537 bone->updateAbsolutePositionOfAllChildren();
1543 void GenericCAO::updateAttachments()
1545 ClientActiveObject *parent = getParent();
1547 m_attached_to_local = parent && parent->isLocalPlayer();
1550 Following cases exist:
1551 m_attachment_parent_id == 0 && !parent
1552 This object is not attached
1553 m_attachment_parent_id != 0 && parent
1554 This object is attached
1555 m_attachment_parent_id != 0 && !parent
1556 This object will be attached as soon the parent is known
1557 m_attachment_parent_id == 0 && parent
1561 if (!parent) { // Detach or don't attach
1563 v3s16 camera_offset = m_env->getCameraOffset();
1564 v3f old_pos = getPosition();
1566 m_matrixnode->setParent(m_smgr->getRootSceneNode());
1567 getPosRotMatrix().setTranslation(old_pos - intToFloat(camera_offset, BS));
1568 m_matrixnode->updateAbsolutePosition();
1573 parent->updateAttachments();
1574 scene::ISceneNode *parent_node = parent->getSceneNode();
1575 scene::IAnimatedMeshSceneNode *parent_animated_mesh_node =
1576 parent->getAnimatedMeshSceneNode();
1577 if (parent_animated_mesh_node && !m_attachment_bone.empty()) {
1578 parent_node = parent_animated_mesh_node->getJointNode(m_attachment_bone.c_str());
1581 if (m_matrixnode && parent_node) {
1582 m_matrixnode->setParent(parent_node);
1583 parent_node->updateAbsolutePosition();
1584 getPosRotMatrix().setTranslation(m_attachment_position);
1585 //setPitchYawRoll(getPosRotMatrix(), m_attachment_rotation);
1586 // use Irrlicht eulers instead
1587 getPosRotMatrix().setRotationDegrees(m_attachment_rotation);
1588 m_matrixnode->updateAbsolutePosition();
1593 bool GenericCAO::visualExpiryRequired(const ObjectProperties &new_) const
1595 const ObjectProperties &old = m_prop;
1596 /* Visuals do not need to be expired for:
1597 * - nametag props: handled by updateNametag()
1598 * - textures: handled by updateTextures()
1599 * - sprite props: handled by updateTexturePos()
1600 * - glow: handled by updateLight()
1601 * - any other properties that do not change appearance
1604 bool uses_legacy_texture = new_.wield_item.empty() &&
1605 (new_.visual == "wielditem" || new_.visual == "item");
1606 // Ordered to compare primitive types before std::vectors
1607 return old.backface_culling != new_.backface_culling ||
1608 old.is_visible != new_.is_visible ||
1609 old.mesh != new_.mesh ||
1610 old.shaded != new_.shaded ||
1611 old.use_texture_alpha != new_.use_texture_alpha ||
1612 old.visual != new_.visual ||
1613 old.visual_size != new_.visual_size ||
1614 old.wield_item != new_.wield_item ||
1615 old.colors != new_.colors ||
1616 (uses_legacy_texture && old.textures != new_.textures);
1619 void GenericCAO::processMessage(const std::string &data)
1621 //infostream<<"GenericCAO: Got message"<<std::endl;
1622 std::istringstream is(data, std::ios::binary);
1624 u8 cmd = readU8(is);
1625 if (cmd == AO_CMD_SET_PROPERTIES) {
1626 ObjectProperties newprops;
1627 newprops.show_on_minimap = m_is_player; // default
1629 newprops.deSerialize(is);
1631 // Check what exactly changed
1632 bool expire_visuals = visualExpiryRequired(newprops);
1633 bool textures_changed = m_prop.textures != newprops.textures;
1636 m_prop = std::move(newprops);
1638 m_selection_box = m_prop.selectionbox;
1639 m_selection_box.MinEdge *= BS;
1640 m_selection_box.MaxEdge *= BS;
1642 m_tx_size.X = 1.0f / m_prop.spritediv.X;
1643 m_tx_size.Y = 1.0f / m_prop.spritediv.Y;
1645 if(!m_initial_tx_basepos_set){
1646 m_initial_tx_basepos_set = true;
1647 m_tx_basepos = m_prop.initial_sprite_basepos;
1649 if (m_is_local_player) {
1650 LocalPlayer *player = m_env->getLocalPlayer();
1651 player->makes_footstep_sound = m_prop.makes_footstep_sound;
1652 aabb3f collision_box = m_prop.collisionbox;
1653 collision_box.MinEdge *= BS;
1654 collision_box.MaxEdge *= BS;
1655 player->setCollisionbox(collision_box);
1656 player->setEyeHeight(m_prop.eye_height);
1657 player->setZoomFOV(m_prop.zoom_fov);
1660 if ((m_is_player && !m_is_local_player) && m_prop.nametag.empty())
1661 m_prop.nametag = m_name;
1662 if (m_is_local_player)
1663 m_prop.show_on_minimap = false;
1665 if (expire_visuals) {
1668 infostream << "GenericCAO: properties updated but expiring visuals"
1669 << " not necessary" << std::endl;
1670 if (textures_changed) {
1671 // don't update while punch texture modifier is active
1672 if (m_reset_textures_timer < 0)
1673 updateTextures(m_current_texture_modifier);
1678 } else if (cmd == AO_CMD_UPDATE_POSITION) {
1679 // Not sent by the server if this object is an attachment.
1680 // We might however get here if the server notices the object being detached before the client.
1681 m_position = readV3F32(is);
1682 m_velocity = readV3F32(is);
1683 m_acceleration = readV3F32(is);
1684 m_rotation = readV3F32(is);
1686 m_rotation = wrapDegrees_0_360_v3f(m_rotation);
1687 bool do_interpolate = readU8(is);
1688 bool is_end_position = readU8(is);
1689 float update_interval = readF32(is);
1691 // Place us a bit higher if we're physical, to not sink into
1692 // the ground due to sucky collision detection...
1694 m_position += v3f(0,0.002,0);
1696 if(getParent() != NULL) // Just in case
1701 if(!m_prop.physical)
1702 pos_translator.update(m_position, is_end_position, update_interval);
1704 pos_translator.init(m_position);
1706 rot_translator.update(m_rotation, false, update_interval);
1708 } else if (cmd == AO_CMD_SET_TEXTURE_MOD) {
1709 std::string mod = deSerializeString16(is);
1711 // immediately reset a engine issued texture modifier if a mod sends a different one
1712 if (m_reset_textures_timer > 0) {
1713 m_reset_textures_timer = -1;
1714 updateTextures(m_previous_texture_modifier);
1716 updateTextures(mod);
1717 } else if (cmd == AO_CMD_SET_SPRITE) {
1718 v2s16 p = readV2S16(is);
1719 int num_frames = readU16(is);
1720 float framelength = readF32(is);
1721 bool select_horiz_by_yawpitch = readU8(is);
1724 m_anim_num_frames = num_frames;
1726 m_anim_framelength = framelength;
1727 m_tx_select_horiz_by_yawpitch = select_horiz_by_yawpitch;
1730 } else if (cmd == AO_CMD_SET_PHYSICS_OVERRIDE) {
1731 float override_speed = readF32(is);
1732 float override_jump = readF32(is);
1733 float override_gravity = readF32(is);
1734 // these are sent inverted so we get true when the server sends nothing
1735 bool sneak = !readU8(is);
1736 bool sneak_glitch = !readU8(is);
1737 bool new_move = !readU8(is);
1740 if(m_is_local_player)
1742 LocalPlayer *player = m_env->getLocalPlayer();
1743 player->physics_override_speed = override_speed;
1744 player->physics_override_jump = override_jump;
1745 player->physics_override_gravity = override_gravity;
1746 player->physics_override_sneak = sneak;
1747 player->physics_override_sneak_glitch = sneak_glitch;
1748 player->physics_override_new_move = new_move;
1750 } else if (cmd == AO_CMD_SET_ANIMATION) {
1751 // TODO: change frames send as v2s32 value
1752 v2f range = readV2F32(is);
1753 if (!m_is_local_player) {
1754 m_animation_range = v2s32((s32)range.X, (s32)range.Y);
1755 m_animation_speed = readF32(is);
1756 m_animation_blend = readF32(is);
1757 // these are sent inverted so we get true when the server sends nothing
1758 m_animation_loop = !readU8(is);
1761 LocalPlayer *player = m_env->getLocalPlayer();
1762 if(player->last_animation == NO_ANIM)
1764 m_animation_range = v2s32((s32)range.X, (s32)range.Y);
1765 m_animation_speed = readF32(is);
1766 m_animation_blend = readF32(is);
1767 // these are sent inverted so we get true when the server sends nothing
1768 m_animation_loop = !readU8(is);
1770 // update animation only if local animations present
1771 // and received animation is unknown (except idle animation)
1772 bool is_known = false;
1773 for (int i = 1;i<4;i++)
1775 if(m_animation_range.Y == player->local_animations[i].Y)
1779 (player->local_animations[1].Y + player->local_animations[2].Y < 1))
1784 } else if (cmd == AO_CMD_SET_ANIMATION_SPEED) {
1785 m_animation_speed = readF32(is);
1786 updateAnimationSpeed();
1787 } else if (cmd == AO_CMD_SET_BONE_POSITION) {
1788 std::string bone = deSerializeString16(is);
1789 v3f position = readV3F32(is);
1790 v3f rotation = readV3F32(is);
1791 m_bone_position[bone] = core::vector2d<v3f>(position, rotation);
1793 // updateBonePosition(); now called every step
1794 } else if (cmd == AO_CMD_ATTACH_TO) {
1795 u16 parent_id = readS16(is);
1796 std::string bone = deSerializeString16(is);
1797 v3f position = readV3F32(is);
1798 v3f rotation = readV3F32(is);
1799 bool force_visible = readU8(is); // Returns false for EOF
1801 setAttachment(parent_id, bone, position, rotation, force_visible);
1802 } else if (cmd == AO_CMD_PUNCHED) {
1803 u16 result_hp = readU16(is);
1805 // Use this instead of the send damage to not interfere with prediction
1806 s32 damage = (s32)m_hp - (s32)result_hp;
1810 if (m_is_local_player)
1811 m_env->getLocalPlayer()->hp = m_hp;
1817 // TODO: Execute defined fast response
1818 // As there is no definition, make a smoke puff
1819 ClientSimpleObject *simple = createSmokePuff(
1820 m_smgr, m_env, m_position,
1821 v2f(m_prop.visual_size.X, m_prop.visual_size.Y) * BS);
1822 m_env->addSimpleObject(simple);
1823 } else if (m_reset_textures_timer < 0 && !m_prop.damage_texture_modifier.empty()) {
1824 m_reset_textures_timer = 0.05;
1826 m_reset_textures_timer += 0.05 * damage;
1827 updateTextures(m_current_texture_modifier + m_prop.damage_texture_modifier);
1832 // Same as 'Server::DiePlayer'
1833 clearParentAttachment();
1834 // Same as 'ObjectRef::l_remove'
1836 clearChildAttachments();
1838 } else if (cmd == AO_CMD_UPDATE_ARMOR_GROUPS) {
1839 m_armor_groups.clear();
1840 int armor_groups_size = readU16(is);
1841 for(int i=0; i<armor_groups_size; i++)
1843 std::string name = deSerializeString16(is);
1844 int rating = readS16(is);
1845 m_armor_groups[name] = rating;
1847 } else if (cmd == AO_CMD_SPAWN_INFANT) {
1848 u16 child_id = readU16(is);
1849 u8 type = readU8(is); // maybe this will be useful later
1852 addAttachmentChild(child_id);
1853 } else if (cmd == AO_CMD_OBSOLETE1) {
1854 // Don't do anything and also don't log a warning
1856 warningstream << FUNCTION_NAME
1857 << ": unknown command or outdated client \""
1858 << +cmd << "\"" << std::endl;
1862 /* \pre punchitem != NULL
1864 bool GenericCAO::directReportPunch(v3f dir, const ItemStack *punchitem,
1865 float time_from_last_punch)
1867 assert(punchitem); // pre-condition
1868 const ToolCapabilities *toolcap =
1869 &punchitem->getToolCapabilities(m_client->idef());
1870 PunchDamageResult result = getPunchDamage(
1874 time_from_last_punch);
1876 if(result.did_punch && result.damage != 0)
1878 if(result.damage < m_hp)
1880 m_hp -= result.damage;
1883 // TODO: Execute defined fast response
1884 // As there is no definition, make a smoke puff
1885 ClientSimpleObject *simple = createSmokePuff(
1886 m_smgr, m_env, m_position,
1887 v2f(m_prop.visual_size.X, m_prop.visual_size.Y) * BS);
1888 m_env->addSimpleObject(simple);
1890 if (m_reset_textures_timer < 0 && !m_prop.damage_texture_modifier.empty()) {
1891 m_reset_textures_timer = 0.05;
1892 if (result.damage >= 2)
1893 m_reset_textures_timer += 0.05 * result.damage;
1894 updateTextures(m_current_texture_modifier + m_prop.damage_texture_modifier);
1901 std::string GenericCAO::debugInfoText()
1903 std::ostringstream os(std::ios::binary);
1904 os<<"GenericCAO hp="<<m_hp<<"\n";
1906 for(ItemGroupList::const_iterator i = m_armor_groups.begin();
1907 i != m_armor_groups.end(); ++i)
1909 os<<i->first<<"="<<i->second<<", ";
1915 void GenericCAO::updateMeshCulling()
1917 if (!m_is_local_player)
1920 const bool hidden = m_client->getCamera()->getCameraMode() == CAMERA_MODE_FIRST;
1922 if (m_meshnode && m_prop.visual == "upright_sprite") {
1923 u32 buffers = m_meshnode->getMesh()->getMeshBufferCount();
1924 for (u32 i = 0; i < buffers; i++) {
1925 video::SMaterial &mat = m_meshnode->getMesh()->getMeshBuffer(i)->getMaterial();
1926 // upright sprite has no backface culling
1927 mat.setFlag(video::EMF_FRONT_FACE_CULLING, hidden);
1932 scene::ISceneNode *node = getSceneNode();
1937 // Hide the mesh by culling both front and
1938 // back faces. Serious hackyness but it works for our
1939 // purposes. This also preserves the skeletal armature.
1940 node->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
1942 node->setMaterialFlag(video::EMF_FRONT_FACE_CULLING,
1945 // Restore mesh visibility.
1946 node->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
1947 m_prop.backface_culling);
1948 node->setMaterialFlag(video::EMF_FRONT_FACE_CULLING,
1954 GenericCAO proto_GenericCAO(NULL, NULL);