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"
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);
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)
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 = RenderingEngine::get_scene_manager()->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);
350 // Check if it's the current player
351 LocalPlayer *player = m_env->getLocalPlayer();
352 if (player && strcmp(player->getName(), m_name.c_str()) == 0) {
353 m_is_local_player = true;
354 m_is_visible = false;
355 player->setCAO(this);
359 m_enable_shaders = g_settings->getBool("enable_shaders");
362 void GenericCAO::processInitData(const std::string &data)
364 std::istringstream is(data, std::ios::binary);
365 const u8 version = readU8(is);
368 errorstream << "GenericCAO: Unsupported init data version"
373 // PROTOCOL_VERSION >= 37
374 m_name = deSerializeString16(is);
375 m_is_player = readU8(is);
377 m_position = readV3F32(is);
378 m_rotation = readV3F32(is);
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->isForcedVisible() ? true : toset);
465 void GenericCAO::setAttachment(int parent_id, const std::string &bone, v3f position, v3f rotation)
467 int old_parent = m_attachment_parent_id;
468 m_attachment_parent_id = parent_id;
469 m_attachment_bone = bone;
470 m_attachment_position = position;
471 m_attachment_rotation = rotation;
473 ClientActiveObject *parent = m_env->getActiveObject(parent_id);
475 if (parent_id != old_parent) {
476 if (auto *o = m_env->getActiveObject(old_parent))
477 o->removeAttachmentChild(m_id);
479 parent->addAttachmentChild(m_id);
484 void GenericCAO::getAttachment(int *parent_id, std::string *bone, v3f *position,
487 *parent_id = m_attachment_parent_id;
488 *bone = m_attachment_bone;
489 *position = m_attachment_position;
490 *rotation = m_attachment_rotation;
493 void GenericCAO::clearChildAttachments()
495 // Cannot use for-loop here: setAttachment() modifies 'm_attachment_child_ids'!
496 while (!m_attachment_child_ids.empty()) {
497 int child_id = *m_attachment_child_ids.begin();
499 if (ClientActiveObject *child = m_env->getActiveObject(child_id))
500 child->setAttachment(0, "", v3f(), v3f(), false);
502 removeAttachmentChild(child_id);
506 void GenericCAO::clearParentAttachment()
508 if (m_attachment_parent_id)
509 setAttachment(0, "", m_attachment_position, m_attachment_rotation);
511 setAttachment(0, "", v3f(), v3f());
514 void GenericCAO::addAttachmentChild(int child_id)
516 m_attachment_child_ids.insert(child_id);
519 void GenericCAO::removeAttachmentChild(int child_id)
521 m_attachment_child_ids.erase(child_id);
524 ClientActiveObject* GenericCAO::getParent() const
526 return m_attachment_parent_id ? m_env->getActiveObject(m_attachment_parent_id) :
530 void GenericCAO::removeFromScene(bool permanent)
532 // Should be true when removing the object permanently
533 // and false when refreshing (eg: updating visuals)
534 if (m_env && permanent) {
535 // The client does not know whether this object does re-appear to
536 // a later time, thus do not clear child attachments.
538 clearParentAttachment();
542 m_meshnode->remove();
544 m_meshnode = nullptr;
545 } else if (m_animated_meshnode) {
546 m_animated_meshnode->remove();
547 m_animated_meshnode->drop();
548 m_animated_meshnode = nullptr;
549 } else if (m_wield_meshnode) {
550 m_wield_meshnode->remove();
551 m_wield_meshnode->drop();
552 m_wield_meshnode = nullptr;
553 } else if (m_spritenode) {
554 m_spritenode->remove();
555 m_spritenode->drop();
556 m_spritenode = nullptr;
560 m_matrixnode->remove();
561 m_matrixnode->drop();
562 m_matrixnode = nullptr;
566 m_client->getCamera()->removeNametag(m_nametag);
571 void GenericCAO::addToScene(ITextureSource *tsrc)
573 m_smgr = RenderingEngine::get_scene_manager();
575 if (getSceneNode() != NULL) {
579 m_visuals_expired = false;
581 if (!m_prop.is_visible)
584 infostream << "GenericCAO::addToScene(): " << m_prop.visual << std::endl;
586 if (m_enable_shaders) {
587 IShaderSource *shader_source = m_client->getShaderSource();
588 MaterialType material_type;
590 if (m_prop.shaded && m_prop.glow == 0)
591 material_type = (m_prop.use_texture_alpha) ?
592 TILE_MATERIAL_ALPHA : TILE_MATERIAL_BASIC;
594 material_type = (m_prop.use_texture_alpha) ?
595 TILE_MATERIAL_PLAIN_ALPHA : TILE_MATERIAL_PLAIN;
597 u32 shader_id = shader_source->getShader("object_shader", material_type, NDT_NORMAL);
598 m_material_type = shader_source->getShaderInfo(shader_id).material;
600 m_material_type = (m_prop.use_texture_alpha) ?
601 video::EMT_TRANSPARENT_ALPHA_CHANNEL : video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
604 auto grabMatrixNode = [this] {
605 m_matrixnode = RenderingEngine::get_scene_manager()->
606 addDummyTransformationSceneNode();
607 m_matrixnode->grab();
610 auto setSceneNodeMaterial = [this] (scene::ISceneNode *node) {
611 node->setMaterialFlag(video::EMF_LIGHTING, false);
612 node->setMaterialFlag(video::EMF_BILINEAR_FILTER, false);
613 node->setMaterialFlag(video::EMF_FOG_ENABLE, true);
614 node->setMaterialType(m_material_type);
616 if (m_enable_shaders) {
617 node->setMaterialFlag(video::EMF_GOURAUD_SHADING, false);
618 node->setMaterialFlag(video::EMF_NORMALIZE_NORMALS, true);
622 if (m_prop.visual == "sprite") {
624 m_spritenode = RenderingEngine::get_scene_manager()->addBillboardSceneNode(
625 m_matrixnode, v2f(1, 1), v3f(0,0,0), -1);
626 m_spritenode->grab();
627 m_spritenode->setMaterialTexture(0,
628 tsrc->getTextureForMesh("unknown_node.png"));
630 setSceneNodeMaterial(m_spritenode);
632 m_spritenode->setSize(v2f(m_prop.visual_size.X,
633 m_prop.visual_size.Y) * BS);
635 const float txs = 1.0 / 1;
636 const float tys = 1.0 / 1;
637 setBillboardTextureMatrix(m_spritenode,
640 } else if (m_prop.visual == "upright_sprite") {
642 scene::SMesh *mesh = new scene::SMesh();
643 double dx = BS * m_prop.visual_size.X / 2;
644 double dy = BS * m_prop.visual_size.Y / 2;
645 video::SColor c(0xFFFFFFFF);
648 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
649 video::S3DVertex vertices[4] = {
650 video::S3DVertex(-dx, -dy, 0, 0,0,1, c, 1,1),
651 video::S3DVertex( dx, -dy, 0, 0,0,1, c, 0,1),
652 video::S3DVertex( dx, dy, 0, 0,0,1, c, 0,0),
653 video::S3DVertex(-dx, dy, 0, 0,0,1, c, 1,0),
656 // Move minimal Y position to 0 (feet position)
657 for (video::S3DVertex &vertex : vertices)
660 u16 indices[] = {0,1,2,2,3,0};
661 buf->append(vertices, 4, indices, 6);
663 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
664 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
665 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
666 buf->getMaterial().MaterialType = m_material_type;
668 if (m_enable_shaders) {
669 buf->getMaterial().EmissiveColor = c;
670 buf->getMaterial().setFlag(video::EMF_GOURAUD_SHADING, false);
671 buf->getMaterial().setFlag(video::EMF_NORMALIZE_NORMALS, true);
675 mesh->addMeshBuffer(buf);
679 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
680 video::S3DVertex vertices[4] = {
681 video::S3DVertex( dx,-dy, 0, 0,0,-1, c, 1,1),
682 video::S3DVertex(-dx,-dy, 0, 0,0,-1, c, 0,1),
683 video::S3DVertex(-dx, dy, 0, 0,0,-1, c, 0,0),
684 video::S3DVertex( dx, dy, 0, 0,0,-1, c, 1,0),
687 // Move minimal Y position to 0 (feet position)
688 for (video::S3DVertex &vertex : vertices)
691 u16 indices[] = {0,1,2,2,3,0};
692 buf->append(vertices, 4, indices, 6);
694 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
695 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
696 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
697 buf->getMaterial().MaterialType = m_material_type;
699 if (m_enable_shaders) {
700 buf->getMaterial().EmissiveColor = c;
701 buf->getMaterial().setFlag(video::EMF_GOURAUD_SHADING, false);
702 buf->getMaterial().setFlag(video::EMF_NORMALIZE_NORMALS, true);
706 mesh->addMeshBuffer(buf);
709 m_meshnode = RenderingEngine::get_scene_manager()->
710 addMeshSceneNode(mesh, m_matrixnode);
713 // Set it to use the materials of the meshbuffers directly.
714 // This is needed for changing the texture in the future
715 m_meshnode->setReadOnlyMaterials(true);
716 } else if (m_prop.visual == "cube") {
718 scene::IMesh *mesh = createCubeMesh(v3f(BS,BS,BS));
719 m_meshnode = RenderingEngine::get_scene_manager()->
720 addMeshSceneNode(mesh, m_matrixnode);
724 m_meshnode->setScale(m_prop.visual_size);
725 m_meshnode->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
726 m_prop.backface_culling);
728 setSceneNodeMaterial(m_meshnode);
729 } else if (m_prop.visual == "mesh") {
731 scene::IAnimatedMesh *mesh = m_client->getMesh(m_prop.mesh, true);
733 m_animated_meshnode = RenderingEngine::get_scene_manager()->
734 addAnimatedMeshSceneNode(mesh, m_matrixnode);
735 m_animated_meshnode->grab();
736 mesh->drop(); // The scene node took hold of it
738 if (!checkMeshNormals(mesh)) {
739 infostream << "GenericCAO: recalculating normals for mesh "
740 << m_prop.mesh << std::endl;
741 m_smgr->getMeshManipulator()->
742 recalculateNormals(mesh, true, false);
745 m_animated_meshnode->animateJoints(); // Needed for some animations
746 m_animated_meshnode->setScale(m_prop.visual_size);
748 // set vertex colors to ensure alpha is set
749 setMeshColor(m_animated_meshnode->getMesh(), video::SColor(0xFFFFFFFF));
751 setAnimatedMeshColor(m_animated_meshnode, video::SColor(0xFFFFFFFF));
753 setSceneNodeMaterial(m_animated_meshnode);
755 m_animated_meshnode->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
756 m_prop.backface_culling);
758 errorstream<<"GenericCAO::addToScene(): Could not load mesh "<<m_prop.mesh<<std::endl;
759 } else if (m_prop.visual == "wielditem" || m_prop.visual == "item") {
762 if (m_prop.wield_item.empty()) {
763 // Old format, only textures are specified.
764 infostream << "textures: " << m_prop.textures.size() << std::endl;
765 if (!m_prop.textures.empty()) {
766 infostream << "textures[0]: " << m_prop.textures[0]
768 IItemDefManager *idef = m_client->idef();
769 item = ItemStack(m_prop.textures[0], 1, 0, idef);
772 infostream << "serialized form: " << m_prop.wield_item << std::endl;
773 item.deSerialize(m_prop.wield_item, m_client->idef());
775 m_wield_meshnode = new WieldMeshSceneNode(
776 RenderingEngine::get_scene_manager(), -1);
777 m_wield_meshnode->setItem(item, m_client,
778 (m_prop.visual == "wielditem"));
780 m_wield_meshnode->setScale(m_prop.visual_size / 2.0f);
781 m_wield_meshnode->setColor(video::SColor(0xFFFFFFFF));
783 infostream<<"GenericCAO::addToScene(): \""<<m_prop.visual
784 <<"\" not supported"<<std::endl;
787 /* don't update while punch texture modifier is active */
788 if (m_reset_textures_timer < 0)
789 updateTextures(m_current_texture_modifier);
791 scene::ISceneNode *node = getSceneNode();
793 if (node && m_matrixnode)
794 node->setParent(m_matrixnode);
799 updateBonePosition();
801 setNodeLight(m_last_light);
805 void GenericCAO::updateLight(u32 day_night_ratio)
814 u16 npos = getLightPosition(pos);
815 for (u16 i = 0; i < npos; i++) {
817 MapNode n = m_env->getMap().getNode(pos[i], &this_ok);
819 u8 this_light = n.getLightBlend(day_night_ratio, m_client->ndef());
820 light_at_pos = MYMAX(light_at_pos, this_light);
825 light_at_pos = blend_light(day_night_ratio, LIGHT_SUN, 0);
827 u8 light = decode_light(light_at_pos + m_glow);
828 if (light != m_last_light) {
829 m_last_light = light;
834 void GenericCAO::setNodeLight(u8 light)
836 video::SColor color(255, light, light, light);
838 if (m_prop.visual == "wielditem" || m_prop.visual == "item") {
839 if (m_wield_meshnode)
840 m_wield_meshnode->setNodeLightColor(color);
844 if (m_enable_shaders) {
845 if (m_prop.visual == "upright_sprite") {
849 scene::IMesh *mesh = m_meshnode->getMesh();
850 for (u32 i = 0; i < mesh->getMeshBufferCount(); ++i) {
851 scene::IMeshBuffer *buf = mesh->getMeshBuffer(i);
852 buf->getMaterial().EmissiveColor = color;
855 scene::ISceneNode *node = getSceneNode();
859 for (u32 i = 0; i < node->getMaterialCount(); ++i) {
860 video::SMaterial &material = node->getMaterial(i);
861 material.EmissiveColor = color;
866 setMeshColor(m_meshnode->getMesh(), color);
867 } else if (m_animated_meshnode) {
868 setAnimatedMeshColor(m_animated_meshnode, color);
869 } else if (m_spritenode) {
870 m_spritenode->setColor(color);
875 u16 GenericCAO::getLightPosition(v3s16 *pos)
877 const auto &box = m_prop.collisionbox;
878 pos[0] = floatToInt(m_position + box.MinEdge * BS, BS);
879 pos[1] = floatToInt(m_position + box.MaxEdge * BS, BS);
881 // Skip center pos if it falls into the same node as Min or MaxEdge
882 if ((box.MaxEdge - box.MinEdge).getLengthSQ() < 3.0f)
884 pos[2] = floatToInt(m_position + box.getCenter() * BS, BS);
888 void GenericCAO::updateNametag()
890 if (m_is_local_player) // No nametag for local player
893 if (m_prop.nametag.empty()) {
896 m_client->getCamera()->removeNametag(m_nametag);
902 scene::ISceneNode *node = getSceneNode();
907 pos.Y = m_prop.selectionbox.MaxEdge.Y + 0.3f;
910 m_nametag = m_client->getCamera()->addNametag(node,
911 m_prop.nametag, m_prop.nametag_color, pos);
914 m_nametag->nametag_text = m_prop.nametag;
915 m_nametag->nametag_color = m_prop.nametag_color;
916 m_nametag->nametag_pos = pos;
920 void GenericCAO::updateNodePos()
922 if (getParent() != NULL)
925 scene::ISceneNode *node = getSceneNode();
928 v3s16 camera_offset = m_env->getCameraOffset();
929 v3f pos = pos_translator.val_current -
930 intToFloat(camera_offset, BS);
931 getPosRotMatrix().setTranslation(pos);
932 if (node != m_spritenode) { // rotate if not a sprite
933 v3f rot = m_is_local_player ? -m_rotation : -rot_translator.val_current;
934 setPitchYawRoll(getPosRotMatrix(), rot);
939 void GenericCAO::step(float dtime, ClientEnvironment *env)
941 // Handle model animations and update positions instantly to prevent lags
942 if (m_is_local_player) {
943 LocalPlayer *player = m_env->getLocalPlayer();
944 m_position = player->getPosition();
945 pos_translator.val_current = m_position;
946 m_rotation.Y = wrapDegrees_0_360(player->getYaw());
947 rot_translator.val_current = m_rotation;
950 int old_anim = player->last_animation;
951 float old_anim_speed = player->last_animation_speed;
952 m_velocity = v3f(0,0,0);
953 m_acceleration = v3f(0,0,0);
954 const PlayerControl &controls = player->getPlayerControl();
956 bool walking = false;
957 if (controls.up || controls.down || controls.left || controls.right ||
958 controls.forw_move_joystick_axis != 0.f ||
959 controls.sidew_move_joystick_axis != 0.f)
962 f32 new_speed = player->local_animation_speed;
963 v2s32 new_anim = v2s32(0,0);
964 bool allow_update = false;
966 // increase speed if using fast or flying fast
967 if((g_settings->getBool("fast_move") &&
968 m_client->checkLocalPrivilege("fast")) &&
970 (!player->touching_ground &&
971 g_settings->getBool("free_move") &&
972 m_client->checkLocalPrivilege("fly"))))
974 // slowdown speed if sneeking
975 if (controls.sneak && walking)
978 if (walking && (controls.dig || controls.place)) {
979 new_anim = player->local_animations[3];
980 player->last_animation = WD_ANIM;
981 } else if (walking) {
982 new_anim = player->local_animations[1];
983 player->last_animation = WALK_ANIM;
984 } else if (controls.dig || controls.place) {
985 new_anim = player->local_animations[2];
986 player->last_animation = DIG_ANIM;
989 // Apply animations if input detected and not attached
990 // or set idle animation
991 if ((new_anim.X + new_anim.Y) > 0 && !getParent()) {
993 m_animation_range = new_anim;
994 m_animation_speed = new_speed;
995 player->last_animation_speed = m_animation_speed;
997 player->last_animation = NO_ANIM;
999 if (old_anim != NO_ANIM) {
1000 m_animation_range = player->local_animations[0];
1005 // Update local player animations
1006 if ((player->last_animation != old_anim ||
1007 m_animation_speed != old_anim_speed) &&
1008 player->last_animation != NO_ANIM && allow_update)
1014 if (m_visuals_expired && m_smgr) {
1015 m_visuals_expired = false;
1017 // Attachments, part 1: All attached objects must be unparented first,
1018 // or Irrlicht causes a segmentation fault
1019 for (u16 cao_id : m_attachment_child_ids) {
1020 ClientActiveObject *obj = m_env->getActiveObject(cao_id);
1022 scene::ISceneNode *child_node = obj->getSceneNode();
1023 // The node's parent is always an IDummyTraformationSceneNode,
1024 // so we need to reparent that one instead.
1026 child_node->getParent()->setParent(m_smgr->getRootSceneNode());
1030 removeFromScene(false);
1031 addToScene(m_client->tsrc());
1033 // Attachments, part 2: Now that the parent has been refreshed, put its attachments back
1034 for (u16 cao_id : m_attachment_child_ids) {
1035 ClientActiveObject *obj = m_env->getActiveObject(cao_id);
1037 obj->updateAttachments();
1041 // Make sure m_is_visible is always applied
1042 scene::ISceneNode *node = getSceneNode();
1044 node->setVisible(m_is_visible);
1046 if(getParent() != NULL) // Attachments should be glued to their parent by Irrlicht
1048 // Set these for later
1049 m_position = getPosition();
1050 m_velocity = v3f(0,0,0);
1051 m_acceleration = v3f(0,0,0);
1052 pos_translator.val_current = m_position;
1053 pos_translator.val_target = m_position;
1055 rot_translator.translate(dtime);
1056 v3f lastpos = pos_translator.val_current;
1060 aabb3f box = m_prop.collisionbox;
1063 collisionMoveResult moveresult;
1064 f32 pos_max_d = BS*0.125; // Distance per iteration
1065 v3f p_pos = m_position;
1066 v3f p_velocity = m_velocity;
1067 moveresult = collisionMoveSimple(env,env->getGameDef(),
1068 pos_max_d, box, m_prop.stepheight, dtime,
1069 &p_pos, &p_velocity, m_acceleration,
1070 this, m_prop.collideWithObjects);
1073 m_velocity = p_velocity;
1075 bool is_end_position = moveresult.collides;
1076 pos_translator.update(m_position, is_end_position, dtime);
1078 m_position += dtime * m_velocity + 0.5 * dtime * dtime * m_acceleration;
1079 m_velocity += dtime * m_acceleration;
1080 pos_translator.update(m_position, pos_translator.aim_is_end,
1081 pos_translator.anim_time);
1083 pos_translator.translate(dtime);
1086 float moved = lastpos.getDistanceFrom(pos_translator.val_current);
1087 m_step_distance_counter += moved;
1088 if (m_step_distance_counter > 1.5f * BS) {
1089 m_step_distance_counter = 0.0f;
1090 if (!m_is_local_player && m_prop.makes_footstep_sound) {
1091 const NodeDefManager *ndef = m_client->ndef();
1092 v3s16 p = floatToInt(getPosition() +
1093 v3f(0.0f, (m_prop.collisionbox.MinEdge.Y - 0.5f) * BS, 0.0f), BS);
1094 MapNode n = m_env->getMap().getNode(p);
1095 SimpleSoundSpec spec = ndef->get(n).sound_footstep;
1096 // Reduce footstep gain, as non-local-player footsteps are
1099 m_client->sound()->playSoundAt(spec, false, getPosition());
1104 m_anim_timer += dtime;
1105 if(m_anim_timer >= m_anim_framelength)
1107 m_anim_timer -= m_anim_framelength;
1109 if(m_anim_frame >= m_anim_num_frames)
1115 if(m_reset_textures_timer >= 0)
1117 m_reset_textures_timer -= dtime;
1118 if(m_reset_textures_timer <= 0) {
1119 m_reset_textures_timer = -1;
1120 updateTextures(m_previous_texture_modifier);
1124 if (!getParent() && std::fabs(m_prop.automatic_rotate) > 0.001) {
1125 // This is the child node's rotation. It is only used for automatic_rotate.
1126 v3f local_rot = node->getRotation();
1127 local_rot.Y = modulo360f(local_rot.Y - dtime * core::RADTODEG *
1128 m_prop.automatic_rotate);
1129 node->setRotation(local_rot);
1132 if (!getParent() && m_prop.automatic_face_movement_dir &&
1133 (fabs(m_velocity.Z) > 0.001 || fabs(m_velocity.X) > 0.001)) {
1134 float target_yaw = atan2(m_velocity.Z, m_velocity.X) * 180 / M_PI
1135 + m_prop.automatic_face_movement_dir_offset;
1136 float max_rotation_per_sec =
1137 m_prop.automatic_face_movement_max_rotation_per_sec;
1139 if (max_rotation_per_sec > 0) {
1140 wrappedApproachShortest(m_rotation.Y, target_yaw,
1141 dtime * max_rotation_per_sec, 360.f);
1143 // Negative values of max_rotation_per_sec mean disabled.
1144 m_rotation.Y = target_yaw;
1147 rot_translator.val_current = m_rotation;
1151 if (m_animated_meshnode) {
1152 // Everything must be updated; the whole transform
1153 // chain as well as the animated mesh node.
1154 // Otherwise, bone attachments would be relative to
1155 // a position that's one frame old.
1157 updatePositionRecursive(m_matrixnode);
1158 m_animated_meshnode->updateAbsolutePosition();
1159 m_animated_meshnode->animateJoints();
1160 updateBonePosition();
1164 void GenericCAO::updateTexturePos()
1168 scene::ICameraSceneNode* camera =
1169 m_spritenode->getSceneManager()->getActiveCamera();
1172 v3f cam_to_entity = m_spritenode->getAbsolutePosition()
1173 - camera->getAbsolutePosition();
1174 cam_to_entity.normalize();
1176 int row = m_tx_basepos.Y;
1177 int col = m_tx_basepos.X;
1179 // Yawpitch goes rightwards
1180 if (m_tx_select_horiz_by_yawpitch) {
1181 if (cam_to_entity.Y > 0.75)
1183 else if (cam_to_entity.Y < -0.75)
1187 atan2(cam_to_entity.Z, cam_to_entity.X) / M_PI * 180.;
1188 float dir = mob_dir - m_rotation.Y;
1189 dir = wrapDegrees_180(dir);
1190 if (std::fabs(wrapDegrees_180(dir - 0)) <= 45.1f)
1192 else if(std::fabs(wrapDegrees_180(dir - 90)) <= 45.1f)
1194 else if(std::fabs(wrapDegrees_180(dir - 180)) <= 45.1f)
1196 else if(std::fabs(wrapDegrees_180(dir + 90)) <= 45.1f)
1203 // Animation goes downwards
1204 row += m_anim_frame;
1206 float txs = m_tx_size.X;
1207 float tys = m_tx_size.Y;
1208 setBillboardTextureMatrix(m_spritenode, txs, tys, col, row);
1211 else if (m_meshnode) {
1212 if (m_prop.visual == "upright_sprite") {
1213 int row = m_tx_basepos.Y;
1214 int col = m_tx_basepos.X;
1216 // Animation goes downwards
1217 row += m_anim_frame;
1219 const auto &tx = m_tx_size;
1220 v2f t[4] = { // cf. vertices in GenericCAO::addToScene()
1221 tx * v2f(col+1, row+1),
1222 tx * v2f(col, row+1),
1224 tx * v2f(col+1, row),
1226 auto mesh = m_meshnode->getMesh();
1227 setMeshBufferTextureCoords(mesh->getMeshBuffer(0), t, 4);
1228 setMeshBufferTextureCoords(mesh->getMeshBuffer(1), t, 4);
1233 // Do not pass by reference, see header.
1234 void GenericCAO::updateTextures(std::string mod)
1236 ITextureSource *tsrc = m_client->tsrc();
1238 bool use_trilinear_filter = g_settings->getBool("trilinear_filter");
1239 bool use_bilinear_filter = g_settings->getBool("bilinear_filter");
1240 bool use_anisotropic_filter = g_settings->getBool("anisotropic_filter");
1242 m_previous_texture_modifier = m_current_texture_modifier;
1243 m_current_texture_modifier = mod;
1244 m_glow = m_prop.glow;
1247 if (m_prop.visual == "sprite") {
1248 std::string texturestring = "unknown_node.png";
1249 if (!m_prop.textures.empty())
1250 texturestring = m_prop.textures[0];
1251 texturestring += mod;
1252 m_spritenode->getMaterial(0).MaterialType = m_material_type;
1253 m_spritenode->getMaterial(0).MaterialTypeParam = 0.5f;
1254 m_spritenode->setMaterialTexture(0,
1255 tsrc->getTextureForMesh(texturestring));
1257 // This allows setting per-material colors. However, until a real lighting
1258 // system is added, the code below will have no effect. Once MineTest
1259 // has directional lighting, it should work automatically.
1260 if (!m_prop.colors.empty()) {
1261 m_spritenode->getMaterial(0).AmbientColor = m_prop.colors[0];
1262 m_spritenode->getMaterial(0).DiffuseColor = m_prop.colors[0];
1263 m_spritenode->getMaterial(0).SpecularColor = m_prop.colors[0];
1266 m_spritenode->getMaterial(0).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1267 m_spritenode->getMaterial(0).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1268 m_spritenode->getMaterial(0).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1272 else if (m_animated_meshnode) {
1273 if (m_prop.visual == "mesh") {
1274 for (u32 i = 0; i < m_prop.textures.size() &&
1275 i < m_animated_meshnode->getMaterialCount(); ++i) {
1276 std::string texturestring = m_prop.textures[i];
1277 if (texturestring.empty())
1278 continue; // Empty texture string means don't modify that material
1279 texturestring += mod;
1280 video::ITexture* texture = tsrc->getTextureForMesh(texturestring);
1282 errorstream<<"GenericCAO::updateTextures(): Could not load texture "<<texturestring<<std::endl;
1286 // Set material flags and texture
1287 video::SMaterial& material = m_animated_meshnode->getMaterial(i);
1288 material.MaterialType = m_material_type;
1289 material.MaterialTypeParam = 0.5f;
1290 material.TextureLayer[0].Texture = texture;
1291 material.setFlag(video::EMF_LIGHTING, true);
1292 material.setFlag(video::EMF_BILINEAR_FILTER, false);
1293 material.setFlag(video::EMF_BACK_FACE_CULLING, m_prop.backface_culling);
1295 // don't filter low-res textures, makes them look blurry
1296 // player models have a res of 64
1297 const core::dimension2d<u32> &size = texture->getOriginalSize();
1298 const u32 res = std::min(size.Height, size.Width);
1299 use_trilinear_filter &= res > 64;
1300 use_bilinear_filter &= res > 64;
1302 m_animated_meshnode->getMaterial(i)
1303 .setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1304 m_animated_meshnode->getMaterial(i)
1305 .setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1306 m_animated_meshnode->getMaterial(i)
1307 .setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1309 for (u32 i = 0; i < m_prop.colors.size() &&
1310 i < m_animated_meshnode->getMaterialCount(); ++i)
1312 // This allows setting per-material colors. However, until a real lighting
1313 // system is added, the code below will have no effect. Once MineTest
1314 // has directional lighting, it should work automatically.
1315 m_animated_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i];
1316 m_animated_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i];
1317 m_animated_meshnode->getMaterial(i).SpecularColor = m_prop.colors[i];
1322 else if (m_meshnode) {
1323 if(m_prop.visual == "cube")
1325 for (u32 i = 0; i < 6; ++i)
1327 std::string texturestring = "unknown_node.png";
1328 if(m_prop.textures.size() > i)
1329 texturestring = m_prop.textures[i];
1330 texturestring += mod;
1333 // Set material flags and texture
1334 video::SMaterial& material = m_meshnode->getMaterial(i);
1335 material.MaterialType = m_material_type;
1336 material.MaterialTypeParam = 0.5f;
1337 material.setFlag(video::EMF_LIGHTING, false);
1338 material.setFlag(video::EMF_BILINEAR_FILTER, false);
1339 material.setTexture(0,
1340 tsrc->getTextureForMesh(texturestring));
1341 material.getTextureMatrix(0).makeIdentity();
1343 // This allows setting per-material colors. However, until a real lighting
1344 // system is added, the code below will have no effect. Once MineTest
1345 // has directional lighting, it should work automatically.
1346 if(m_prop.colors.size() > i)
1348 m_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i];
1349 m_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i];
1350 m_meshnode->getMaterial(i).SpecularColor = m_prop.colors[i];
1353 m_meshnode->getMaterial(i).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1354 m_meshnode->getMaterial(i).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1355 m_meshnode->getMaterial(i).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1357 } else if (m_prop.visual == "upright_sprite") {
1358 scene::IMesh *mesh = m_meshnode->getMesh();
1360 std::string tname = "unknown_object.png";
1361 if (!m_prop.textures.empty())
1362 tname = m_prop.textures[0];
1364 scene::IMeshBuffer *buf = mesh->getMeshBuffer(0);
1365 buf->getMaterial().setTexture(0,
1366 tsrc->getTextureForMesh(tname));
1368 // This allows setting per-material colors. However, until a real lighting
1369 // system is added, the code below will have no effect. Once MineTest
1370 // has directional lighting, it should work automatically.
1371 if(!m_prop.colors.empty()) {
1372 buf->getMaterial().AmbientColor = m_prop.colors[0];
1373 buf->getMaterial().DiffuseColor = m_prop.colors[0];
1374 buf->getMaterial().SpecularColor = m_prop.colors[0];
1377 buf->getMaterial().setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1378 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1379 buf->getMaterial().setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1382 std::string tname = "unknown_object.png";
1383 if (m_prop.textures.size() >= 2)
1384 tname = m_prop.textures[1];
1385 else if (!m_prop.textures.empty())
1386 tname = m_prop.textures[0];
1388 scene::IMeshBuffer *buf = mesh->getMeshBuffer(1);
1389 buf->getMaterial().setTexture(0,
1390 tsrc->getTextureForMesh(tname));
1392 // This allows setting per-material colors. However, until a real lighting
1393 // system is added, the code below will have no effect. Once MineTest
1394 // has directional lighting, it should work automatically.
1395 if (m_prop.colors.size() >= 2) {
1396 buf->getMaterial().AmbientColor = m_prop.colors[1];
1397 buf->getMaterial().DiffuseColor = m_prop.colors[1];
1398 buf->getMaterial().SpecularColor = m_prop.colors[1];
1399 } else if (!m_prop.colors.empty()) {
1400 buf->getMaterial().AmbientColor = m_prop.colors[0];
1401 buf->getMaterial().DiffuseColor = m_prop.colors[0];
1402 buf->getMaterial().SpecularColor = m_prop.colors[0];
1405 buf->getMaterial().setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1406 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1407 buf->getMaterial().setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1409 // Set mesh color (only if lighting is disabled)
1410 if (!m_prop.colors.empty() && m_glow < 0)
1411 setMeshColor(mesh, m_prop.colors[0]);
1414 // Prevent showing the player after changing texture
1415 if (m_is_local_player)
1416 updateMeshCulling();
1419 void GenericCAO::updateAnimation()
1421 if (!m_animated_meshnode)
1424 if (m_animated_meshnode->getStartFrame() != m_animation_range.X ||
1425 m_animated_meshnode->getEndFrame() != m_animation_range.Y)
1426 m_animated_meshnode->setFrameLoop(m_animation_range.X, m_animation_range.Y);
1427 if (m_animated_meshnode->getAnimationSpeed() != m_animation_speed)
1428 m_animated_meshnode->setAnimationSpeed(m_animation_speed);
1429 m_animated_meshnode->setTransitionTime(m_animation_blend);
1430 // Requires Irrlicht 1.8 or greater
1431 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR > 1
1432 if (m_animated_meshnode->getLoopMode() != m_animation_loop)
1433 m_animated_meshnode->setLoopMode(m_animation_loop);
1437 void GenericCAO::updateAnimationSpeed()
1439 if (!m_animated_meshnode)
1442 m_animated_meshnode->setAnimationSpeed(m_animation_speed);
1445 void GenericCAO::updateBonePosition()
1447 if (m_bone_position.empty() || !m_animated_meshnode)
1450 m_animated_meshnode->setJointMode(irr::scene::EJUOR_CONTROL); // To write positions to the mesh on render
1451 for (auto &it : m_bone_position) {
1452 std::string bone_name = it.first;
1453 irr::scene::IBoneSceneNode* bone = m_animated_meshnode->getJointNode(bone_name.c_str());
1455 bone->setPosition(it.second.X);
1456 bone->setRotation(it.second.Y);
1460 // search through bones to find mistakenly rotated bones due to bug in Irrlicht
1461 for (u32 i = 0; i < m_animated_meshnode->getJointCount(); ++i) {
1462 irr::scene::IBoneSceneNode *bone = m_animated_meshnode->getJointNode(i);
1466 // Workaround for Irrlicht bug
1467 // We check each bone to see if it has been rotated ~180deg from its expected position due to a bug in Irricht
1468 // when using EJUOR_CONTROL joint control. If the bug is detected we update the bone to the proper position
1469 // and update the bones transformation.
1470 v3f bone_rot = bone->getRelativeTransformation().getRotationDegrees();
1471 float offset_X = fabsf(bone_rot.X - bone->getRotation().X);
1472 float offset_Y = fabsf(bone_rot.Y - bone->getRotation().Y);
1473 float offset_Z = fabsf(bone_rot.Z - bone->getRotation().Z);
1474 if ((offset_X > 179.9f && offset_X < 180.1f)
1475 || (offset_Y > 179.9f && offset_Y < 180.1f)
1476 || (offset_Z > 179.9f && offset_Z < 180.1f)) {
1477 bone->setRotation(bone_rot);
1478 bone->updateAbsolutePosition();
1481 // The following is needed for set_bone_pos to propagate to
1482 // attached objects correctly.
1483 // Irrlicht ought to do this, but doesn't when using EJUOR_CONTROL.
1484 for (u32 i = 0; i < m_animated_meshnode->getJointCount(); ++i) {
1485 auto bone = m_animated_meshnode->getJointNode(i);
1486 // Look for the root bone.
1487 if (bone && bone->getParent() == m_animated_meshnode) {
1488 // Update entire skeleton.
1489 bone->updateAbsolutePositionOfAllChildren();
1495 void GenericCAO::updateAttachments()
1497 ClientActiveObject *parent = getParent();
1499 m_attached_to_local = parent && parent->isLocalPlayer();
1502 Following cases exist:
1503 m_attachment_parent_id == 0 && !parent
1504 This object is not attached
1505 m_attachment_parent_id != 0 && parent
1506 This object is attached
1507 m_attachment_parent_id != 0 && !parent
1508 This object will be attached as soon the parent is known
1509 m_attachment_parent_id == 0 && parent
1513 if (!parent) { // Detach or don't attach
1515 v3s16 camera_offset = m_env->getCameraOffset();
1516 v3f old_pos = getPosition();
1518 m_matrixnode->setParent(m_smgr->getRootSceneNode());
1519 getPosRotMatrix().setTranslation(old_pos - intToFloat(camera_offset, BS));
1520 m_matrixnode->updateAbsolutePosition();
1525 parent->updateAttachments();
1526 scene::ISceneNode *parent_node = parent->getSceneNode();
1527 scene::IAnimatedMeshSceneNode *parent_animated_mesh_node =
1528 parent->getAnimatedMeshSceneNode();
1529 if (parent_animated_mesh_node && !m_attachment_bone.empty()) {
1530 parent_node = parent_animated_mesh_node->getJointNode(m_attachment_bone.c_str());
1533 if (m_matrixnode && parent_node) {
1534 m_matrixnode->setParent(parent_node);
1535 parent_node->updateAbsolutePosition();
1536 getPosRotMatrix().setTranslation(m_attachment_position);
1537 //setPitchYawRoll(getPosRotMatrix(), m_attachment_rotation);
1538 // use Irrlicht eulers instead
1539 getPosRotMatrix().setRotationDegrees(m_attachment_rotation);
1540 m_matrixnode->updateAbsolutePosition();
1545 bool GenericCAO::visualExpiryRequired(const ObjectProperties &new_) const
1547 const ObjectProperties &old = m_prop;
1548 /* Visuals do not need to be expired for:
1549 * - nametag props: handled by updateNametag()
1550 * - textures: handled by updateTextures()
1551 * - sprite props: handled by updateTexturePos()
1552 * - glow: handled by updateLight()
1553 * - any other properties that do not change appearance
1556 bool uses_legacy_texture = new_.wield_item.empty() &&
1557 (new_.visual == "wielditem" || new_.visual == "item");
1558 // Ordered to compare primitive types before std::vectors
1559 return old.backface_culling != new_.backface_culling ||
1560 old.is_visible != new_.is_visible ||
1561 old.mesh != new_.mesh ||
1562 old.shaded != new_.shaded ||
1563 old.use_texture_alpha != new_.use_texture_alpha ||
1564 old.visual != new_.visual ||
1565 old.visual_size != new_.visual_size ||
1566 old.wield_item != new_.wield_item ||
1567 old.colors != new_.colors ||
1568 (uses_legacy_texture && old.textures != new_.textures);
1571 void GenericCAO::processMessage(const std::string &data)
1573 //infostream<<"GenericCAO: Got message"<<std::endl;
1574 std::istringstream is(data, std::ios::binary);
1576 u8 cmd = readU8(is);
1577 if (cmd == AO_CMD_SET_PROPERTIES) {
1578 ObjectProperties newprops;
1579 newprops.deSerialize(is);
1581 // Check what exactly changed
1582 bool expire_visuals = visualExpiryRequired(newprops);
1583 bool textures_changed = m_prop.textures != newprops.textures;
1586 m_prop = std::move(newprops);
1588 m_selection_box = m_prop.selectionbox;
1589 m_selection_box.MinEdge *= BS;
1590 m_selection_box.MaxEdge *= BS;
1592 m_tx_size.X = 1.0f / m_prop.spritediv.X;
1593 m_tx_size.Y = 1.0f / m_prop.spritediv.Y;
1595 if(!m_initial_tx_basepos_set){
1596 m_initial_tx_basepos_set = true;
1597 m_tx_basepos = m_prop.initial_sprite_basepos;
1599 if (m_is_local_player) {
1600 LocalPlayer *player = m_env->getLocalPlayer();
1601 player->makes_footstep_sound = m_prop.makes_footstep_sound;
1602 aabb3f collision_box = m_prop.collisionbox;
1603 collision_box.MinEdge *= BS;
1604 collision_box.MaxEdge *= BS;
1605 player->setCollisionbox(collision_box);
1606 player->setEyeHeight(m_prop.eye_height);
1607 player->setZoomFOV(m_prop.zoom_fov);
1610 if ((m_is_player && !m_is_local_player) && m_prop.nametag.empty())
1611 m_prop.nametag = m_name;
1613 if (expire_visuals) {
1616 infostream << "GenericCAO: properties updated but expiring visuals"
1617 << " not necessary" << std::endl;
1618 if (textures_changed) {
1619 // don't update while punch texture modifier is active
1620 if (m_reset_textures_timer < 0)
1621 updateTextures(m_current_texture_modifier);
1625 } else if (cmd == AO_CMD_UPDATE_POSITION) {
1626 // Not sent by the server if this object is an attachment.
1627 // We might however get here if the server notices the object being detached before the client.
1628 m_position = readV3F32(is);
1629 m_velocity = readV3F32(is);
1630 m_acceleration = readV3F32(is);
1631 m_rotation = readV3F32(is);
1633 m_rotation = wrapDegrees_0_360_v3f(m_rotation);
1634 bool do_interpolate = readU8(is);
1635 bool is_end_position = readU8(is);
1636 float update_interval = readF32(is);
1638 // Place us a bit higher if we're physical, to not sink into
1639 // the ground due to sucky collision detection...
1641 m_position += v3f(0,0.002,0);
1643 if(getParent() != NULL) // Just in case
1648 if(!m_prop.physical)
1649 pos_translator.update(m_position, is_end_position, update_interval);
1651 pos_translator.init(m_position);
1653 rot_translator.update(m_rotation, false, update_interval);
1655 } else if (cmd == AO_CMD_SET_TEXTURE_MOD) {
1656 std::string mod = deSerializeString16(is);
1658 // immediately reset a engine issued texture modifier if a mod sends a different one
1659 if (m_reset_textures_timer > 0) {
1660 m_reset_textures_timer = -1;
1661 updateTextures(m_previous_texture_modifier);
1663 updateTextures(mod);
1664 } else if (cmd == AO_CMD_SET_SPRITE) {
1665 v2s16 p = readV2S16(is);
1666 int num_frames = readU16(is);
1667 float framelength = readF32(is);
1668 bool select_horiz_by_yawpitch = readU8(is);
1671 m_anim_num_frames = num_frames;
1672 m_anim_framelength = framelength;
1673 m_tx_select_horiz_by_yawpitch = select_horiz_by_yawpitch;
1676 } else if (cmd == AO_CMD_SET_PHYSICS_OVERRIDE) {
1677 float override_speed = readF32(is);
1678 float override_jump = readF32(is);
1679 float override_gravity = readF32(is);
1680 // these are sent inverted so we get true when the server sends nothing
1681 bool sneak = !readU8(is);
1682 bool sneak_glitch = !readU8(is);
1683 bool new_move = !readU8(is);
1686 if(m_is_local_player)
1688 LocalPlayer *player = m_env->getLocalPlayer();
1689 player->physics_override_speed = override_speed;
1690 player->physics_override_jump = override_jump;
1691 player->physics_override_gravity = override_gravity;
1692 player->physics_override_sneak = sneak;
1693 player->physics_override_sneak_glitch = sneak_glitch;
1694 player->physics_override_new_move = new_move;
1696 } else if (cmd == AO_CMD_SET_ANIMATION) {
1697 // TODO: change frames send as v2s32 value
1698 v2f range = readV2F32(is);
1699 if (!m_is_local_player) {
1700 m_animation_range = v2s32((s32)range.X, (s32)range.Y);
1701 m_animation_speed = readF32(is);
1702 m_animation_blend = readF32(is);
1703 // these are sent inverted so we get true when the server sends nothing
1704 m_animation_loop = !readU8(is);
1707 LocalPlayer *player = m_env->getLocalPlayer();
1708 if(player->last_animation == NO_ANIM)
1710 m_animation_range = v2s32((s32)range.X, (s32)range.Y);
1711 m_animation_speed = readF32(is);
1712 m_animation_blend = readF32(is);
1713 // these are sent inverted so we get true when the server sends nothing
1714 m_animation_loop = !readU8(is);
1716 // update animation only if local animations present
1717 // and received animation is unknown (except idle animation)
1718 bool is_known = false;
1719 for (int i = 1;i<4;i++)
1721 if(m_animation_range.Y == player->local_animations[i].Y)
1725 (player->local_animations[1].Y + player->local_animations[2].Y < 1))
1730 } else if (cmd == AO_CMD_SET_ANIMATION_SPEED) {
1731 m_animation_speed = readF32(is);
1732 updateAnimationSpeed();
1733 } else if (cmd == AO_CMD_SET_BONE_POSITION) {
1734 std::string bone = deSerializeString16(is);
1735 v3f position = readV3F32(is);
1736 v3f rotation = readV3F32(is);
1737 m_bone_position[bone] = core::vector2d<v3f>(position, rotation);
1739 // updateBonePosition(); now called every step
1740 } else if (cmd == AO_CMD_ATTACH_TO) {
1741 u16 parent_id = readS16(is);
1742 std::string bone = deSerializeString16(is);
1743 v3f position = readV3F32(is);
1744 v3f rotation = readV3F32(is);
1745 m_force_visible = readU8(is); // Returns false for EOF
1747 setAttachment(parent_id, bone, position, rotation);
1749 // Forcibly show attachments if required by set_attach
1750 if (m_force_visible)
1751 m_is_visible = true;
1752 // localplayer itself can't be attached to localplayer
1753 else if (!m_is_local_player) {
1754 // Objects attached to the local player should be hidden in first
1755 // person provided the forced boolean isn't set.
1756 m_is_visible = !m_attached_to_local ||
1757 m_client->getCamera()->getCameraMode() != CAMERA_MODE_FIRST;
1758 m_force_visible = false;
1760 // Local players need to have this set,
1761 // otherwise first person attachments fail.
1762 m_is_visible = true;
1764 } else if (cmd == AO_CMD_PUNCHED) {
1765 u16 result_hp = readU16(is);
1767 // Use this instead of the send damage to not interfere with prediction
1768 s32 damage = (s32)m_hp - (s32)result_hp;
1772 if (m_is_local_player)
1773 m_env->getLocalPlayer()->hp = m_hp;
1779 // TODO: Execute defined fast response
1780 // As there is no definition, make a smoke puff
1781 ClientSimpleObject *simple = createSmokePuff(
1782 m_smgr, m_env, m_position,
1783 v2f(m_prop.visual_size.X, m_prop.visual_size.Y) * BS);
1784 m_env->addSimpleObject(simple);
1785 } else if (m_reset_textures_timer < 0 && !m_prop.damage_texture_modifier.empty()) {
1786 m_reset_textures_timer = 0.05;
1788 m_reset_textures_timer += 0.05 * damage;
1789 updateTextures(m_current_texture_modifier + m_prop.damage_texture_modifier);
1794 // Same as 'Server::DiePlayer'
1795 clearParentAttachment();
1796 // Same as 'ObjectRef::l_remove'
1798 clearChildAttachments();
1800 } else if (cmd == AO_CMD_UPDATE_ARMOR_GROUPS) {
1801 m_armor_groups.clear();
1802 int armor_groups_size = readU16(is);
1803 for(int i=0; i<armor_groups_size; i++)
1805 std::string name = deSerializeString16(is);
1806 int rating = readS16(is);
1807 m_armor_groups[name] = rating;
1809 } else if (cmd == AO_CMD_SPAWN_INFANT) {
1810 u16 child_id = readU16(is);
1811 u8 type = readU8(is); // maybe this will be useful later
1814 addAttachmentChild(child_id);
1815 } else if (cmd == AO_CMD_OBSOLETE1) {
1816 // Don't do anything and also don't log a warning
1818 warningstream << FUNCTION_NAME
1819 << ": unknown command or outdated client \""
1820 << +cmd << "\"" << std::endl;
1824 /* \pre punchitem != NULL
1826 bool GenericCAO::directReportPunch(v3f dir, const ItemStack *punchitem,
1827 float time_from_last_punch)
1829 assert(punchitem); // pre-condition
1830 const ToolCapabilities *toolcap =
1831 &punchitem->getToolCapabilities(m_client->idef());
1832 PunchDamageResult result = getPunchDamage(
1836 time_from_last_punch);
1838 if(result.did_punch && result.damage != 0)
1840 if(result.damage < m_hp)
1842 m_hp -= result.damage;
1845 // TODO: Execute defined fast response
1846 // As there is no definition, make a smoke puff
1847 ClientSimpleObject *simple = createSmokePuff(
1848 m_smgr, m_env, m_position,
1849 v2f(m_prop.visual_size.X, m_prop.visual_size.Y) * BS);
1850 m_env->addSimpleObject(simple);
1852 if (m_reset_textures_timer < 0 && !m_prop.damage_texture_modifier.empty()) {
1853 m_reset_textures_timer = 0.05;
1854 if (result.damage >= 2)
1855 m_reset_textures_timer += 0.05 * result.damage;
1856 updateTextures(m_current_texture_modifier + m_prop.damage_texture_modifier);
1863 std::string GenericCAO::debugInfoText()
1865 std::ostringstream os(std::ios::binary);
1866 os<<"GenericCAO hp="<<m_hp<<"\n";
1868 for(ItemGroupList::const_iterator i = m_armor_groups.begin();
1869 i != m_armor_groups.end(); ++i)
1871 os<<i->first<<"="<<i->second<<", ";
1877 void GenericCAO::updateMeshCulling()
1879 if (!m_is_local_player)
1882 // Grab the active player scene node so we know there's
1883 // at least a mesh to occlude from the camera.
1884 irr::scene::ISceneNode *node = getSceneNode();
1888 if (m_client->getCamera()->getCameraMode() == CAMERA_MODE_FIRST) {
1889 // Hide the mesh by culling both front and
1890 // back faces. Serious hackyness but it works for our
1891 // purposes. This also preserves the skeletal armature.
1892 node->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
1894 node->setMaterialFlag(video::EMF_FRONT_FACE_CULLING,
1897 // Restore mesh visibility.
1898 node->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
1899 m_prop.backface_culling);
1900 node->setMaterialFlag(video::EMF_FRONT_FACE_CULLING,
1906 GenericCAO proto_GenericCAO(NULL, NULL);