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);
169 class TestCAO : public ClientActiveObject
172 TestCAO(Client *client, ClientEnvironment *env);
173 virtual ~TestCAO() = default;
175 ActiveObjectType getType() const
177 return ACTIVEOBJECT_TYPE_TEST;
180 static ClientActiveObject* create(Client *client, ClientEnvironment *env);
182 void addToScene(ITextureSource *tsrc);
183 void removeFromScene(bool permanent);
184 void updateLight(u8 light_at_pos);
185 v3s16 getLightPosition();
186 void updateNodePos();
188 void step(float dtime, ClientEnvironment *env);
190 void processMessage(const std::string &data);
192 bool getCollisionBox(aabb3f *toset) const { return false; }
194 scene::IMeshSceneNode *m_node;
199 TestCAO proto_TestCAO(NULL, NULL);
201 TestCAO::TestCAO(Client *client, ClientEnvironment *env):
202 ClientActiveObject(0, client, env),
204 m_position(v3f(0,10*BS,0))
206 ClientActiveObject::registerType(getType(), create);
209 ClientActiveObject* TestCAO::create(Client *client, ClientEnvironment *env)
211 return new TestCAO(client, env);
214 void TestCAO::addToScene(ITextureSource *tsrc)
219 //video::IVideoDriver* driver = smgr->getVideoDriver();
221 scene::SMesh *mesh = new scene::SMesh();
222 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
223 video::SColor c(255,255,255,255);
224 video::S3DVertex vertices[4] =
226 video::S3DVertex(-BS/2,-BS/4,0, 0,0,0, c, 0,1),
227 video::S3DVertex(BS/2,-BS/4,0, 0,0,0, c, 1,1),
228 video::S3DVertex(BS/2,BS/4,0, 0,0,0, c, 1,0),
229 video::S3DVertex(-BS/2,BS/4,0, 0,0,0, c, 0,0),
231 u16 indices[] = {0,1,2,2,3,0};
232 buf->append(vertices, 4, indices, 6);
234 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
235 buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false);
236 buf->getMaterial().setTexture(0, tsrc->getTextureForMesh("rat.png"));
237 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
238 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
239 buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
241 mesh->addMeshBuffer(buf);
243 m_node = RenderingEngine::get_scene_manager()->addMeshSceneNode(mesh, NULL);
248 void TestCAO::removeFromScene(bool permanent)
257 void TestCAO::updateLight(u8 light_at_pos)
261 v3s16 TestCAO::getLightPosition()
263 return floatToInt(m_position, BS);
266 void TestCAO::updateNodePos()
271 m_node->setPosition(m_position);
272 //m_node->setRotation(v3f(0, 45, 0));
275 void TestCAO::step(float dtime, ClientEnvironment *env)
279 v3f rot = m_node->getRotation();
280 //infostream<<"dtime="<<dtime<<", rot.Y="<<rot.Y<<std::endl;
281 rot.Y += dtime * 180;
282 m_node->setRotation(rot);
286 void TestCAO::processMessage(const std::string &data)
288 infostream<<"TestCAO: Got data: "<<data<<std::endl;
289 std::istringstream is(data, std::ios::binary);
307 #include "clientobject.h"
309 GenericCAO::GenericCAO(Client *client, ClientEnvironment *env):
310 ClientActiveObject(0, client, env)
312 if (client == NULL) {
313 ClientActiveObject::registerType(getType(), create);
319 bool GenericCAO::getCollisionBox(aabb3f *toset) const
323 //update collision box
324 toset->MinEdge = m_prop.collisionbox.MinEdge * BS;
325 toset->MaxEdge = m_prop.collisionbox.MaxEdge * BS;
327 toset->MinEdge += m_position;
328 toset->MaxEdge += m_position;
336 bool GenericCAO::collideWithObjects() const
338 return m_prop.collideWithObjects;
341 void GenericCAO::initialize(const std::string &data)
343 infostream<<"GenericCAO: Got init data"<<std::endl;
344 processInitData(data);
347 // Check if it's the current player
348 LocalPlayer *player = m_env->getLocalPlayer();
349 if (player && strcmp(player->getName(), m_name.c_str()) == 0) {
350 m_is_local_player = true;
351 m_is_visible = false;
352 player->setCAO(this);
356 m_enable_shaders = g_settings->getBool("enable_shaders");
359 void GenericCAO::processInitData(const std::string &data)
361 std::istringstream is(data, std::ios::binary);
362 const u8 version = readU8(is);
365 errorstream << "GenericCAO: Unsupported init data version"
370 // PROTOCOL_VERSION >= 37
371 m_name = deSerializeString(is);
372 m_is_player = readU8(is);
374 m_position = readV3F32(is);
375 m_rotation = readV3F32(is);
378 const u8 num_messages = readU8(is);
380 for (int i = 0; i < num_messages; i++) {
381 std::string message = deSerializeLongString(is);
382 processMessage(message);
385 m_rotation = wrapDegrees_0_360_v3f(m_rotation);
386 pos_translator.init(m_position);
387 rot_translator.init(m_rotation);
391 GenericCAO::~GenericCAO()
393 removeFromScene(true);
396 bool GenericCAO::getSelectionBox(aabb3f *toset) const
398 if (!m_prop.is_visible || !m_is_visible || m_is_local_player
399 || !m_prop.pointable) {
402 *toset = m_selection_box;
406 const v3f GenericCAO::getPosition() const
409 return pos_translator.val_current;
411 // Calculate real position in world based on MatrixNode
413 v3s16 camera_offset = m_env->getCameraOffset();
414 return m_matrixnode->getAbsolutePosition() +
415 intToFloat(camera_offset, BS);
421 const bool GenericCAO::isImmortal()
423 return itemgroup_get(getGroups(), "immortal");
426 scene::ISceneNode *GenericCAO::getSceneNode() const
432 if (m_animated_meshnode) {
433 return m_animated_meshnode;
436 if (m_wield_meshnode) {
437 return m_wield_meshnode;
446 scene::IAnimatedMeshSceneNode *GenericCAO::getAnimatedMeshSceneNode() const
448 return m_animated_meshnode;
451 void GenericCAO::setChildrenVisible(bool toset)
453 for (u16 cao_id : m_attachment_child_ids) {
454 GenericCAO *obj = m_env->getGenericCAO(cao_id);
456 obj->setVisible(toset);
461 void GenericCAO::setAttachment(int parent_id, const std::string &bone, v3f position, v3f rotation)
463 int old_parent = m_attachment_parent_id;
464 m_attachment_parent_id = parent_id;
465 m_attachment_bone = bone;
466 m_attachment_position = position;
467 m_attachment_rotation = rotation;
469 ClientActiveObject *parent = m_env->getActiveObject(parent_id);
471 if (parent_id != old_parent) {
472 if (auto *o = m_env->getActiveObject(old_parent))
473 o->removeAttachmentChild(m_id);
475 parent->addAttachmentChild(m_id);
481 void GenericCAO::getAttachment(int *parent_id, std::string *bone, v3f *position,
484 *parent_id = m_attachment_parent_id;
485 *bone = m_attachment_bone;
486 *position = m_attachment_position;
487 *rotation = m_attachment_rotation;
490 void GenericCAO::clearChildAttachments()
492 // Cannot use for-loop here: setAttachment() modifies 'm_attachment_child_ids'!
493 while (!m_attachment_child_ids.empty()) {
494 int child_id = *m_attachment_child_ids.begin();
496 if (ClientActiveObject *child = m_env->getActiveObject(child_id))
497 child->setAttachment(0, "", v3f(), v3f());
499 removeAttachmentChild(child_id);
503 void GenericCAO::clearParentAttachment()
505 if (m_attachment_parent_id)
506 setAttachment(0, "", m_attachment_position, m_attachment_rotation);
508 setAttachment(0, "", v3f(), v3f());
511 void GenericCAO::addAttachmentChild(int child_id)
513 m_attachment_child_ids.insert(child_id);
516 void GenericCAO::removeAttachmentChild(int child_id)
518 m_attachment_child_ids.erase(child_id);
521 ClientActiveObject* GenericCAO::getParent() const
523 return m_attachment_parent_id ? m_env->getActiveObject(m_attachment_parent_id) :
527 void GenericCAO::removeFromScene(bool permanent)
529 // Should be true when removing the object permanently
530 // and false when refreshing (eg: updating visuals)
531 if (m_env && permanent) {
532 // The client does not know whether this object does re-appear to
533 // a later time, thus do not clear child attachments.
535 clearParentAttachment();
539 m_meshnode->remove();
541 m_meshnode = nullptr;
542 } else if (m_animated_meshnode) {
543 m_animated_meshnode->remove();
544 m_animated_meshnode->drop();
545 m_animated_meshnode = nullptr;
546 } else if (m_wield_meshnode) {
547 m_wield_meshnode->remove();
548 m_wield_meshnode->drop();
549 m_wield_meshnode = nullptr;
550 } else if (m_spritenode) {
551 m_spritenode->remove();
552 m_spritenode->drop();
553 m_spritenode = nullptr;
557 m_matrixnode->remove();
558 m_matrixnode->drop();
559 m_matrixnode = nullptr;
563 m_client->getCamera()->removeNametag(m_nametag);
568 void GenericCAO::addToScene(ITextureSource *tsrc)
570 m_smgr = RenderingEngine::get_scene_manager();
572 if (getSceneNode() != NULL) {
576 m_visuals_expired = false;
578 if (!m_prop.is_visible)
581 infostream << "GenericCAO::addToScene(): " << m_prop.visual << std::endl;
583 if (m_enable_shaders) {
584 IShaderSource *shader_source = m_client->getShaderSource();
585 u32 shader_id = shader_source->getShader(
587 (m_prop.use_texture_alpha) ? TILE_MATERIAL_ALPHA : TILE_MATERIAL_BASIC,
589 m_material_type = shader_source->getShaderInfo(shader_id).material;
591 m_material_type = (m_prop.use_texture_alpha) ?
592 video::EMT_TRANSPARENT_ALPHA_CHANNEL : video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
595 auto grabMatrixNode = [this] {
596 m_matrixnode = RenderingEngine::get_scene_manager()->
597 addDummyTransformationSceneNode();
598 m_matrixnode->grab();
601 auto setSceneNodeMaterial = [this] (scene::ISceneNode *node) {
602 node->setMaterialFlag(video::EMF_LIGHTING, false);
603 node->setMaterialFlag(video::EMF_BILINEAR_FILTER, false);
604 node->setMaterialFlag(video::EMF_FOG_ENABLE, true);
605 node->setMaterialType(m_material_type);
607 if (m_enable_shaders) {
608 node->setMaterialFlag(video::EMF_GOURAUD_SHADING, false);
609 node->setMaterialFlag(video::EMF_NORMALIZE_NORMALS, true);
613 if (m_prop.visual == "sprite") {
615 m_spritenode = RenderingEngine::get_scene_manager()->addBillboardSceneNode(
616 m_matrixnode, v2f(1, 1), v3f(0,0,0), -1);
617 m_spritenode->grab();
618 m_spritenode->setMaterialTexture(0,
619 tsrc->getTextureForMesh("unknown_node.png"));
621 setSceneNodeMaterial(m_spritenode);
623 m_spritenode->setSize(v2f(m_prop.visual_size.X,
624 m_prop.visual_size.Y) * BS);
626 const float txs = 1.0 / 1;
627 const float tys = 1.0 / 1;
628 setBillboardTextureMatrix(m_spritenode,
631 } else if (m_prop.visual == "upright_sprite") {
633 scene::SMesh *mesh = new scene::SMesh();
634 double dx = BS * m_prop.visual_size.X / 2;
635 double dy = BS * m_prop.visual_size.Y / 2;
636 video::SColor c(0xFFFFFFFF);
639 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
640 video::S3DVertex vertices[4] = {
641 video::S3DVertex(-dx, -dy, 0, 0,0,1, c, 1,1),
642 video::S3DVertex( dx, -dy, 0, 0,0,1, c, 0,1),
643 video::S3DVertex( dx, dy, 0, 0,0,1, c, 0,0),
644 video::S3DVertex(-dx, dy, 0, 0,0,1, c, 1,0),
647 // Move minimal Y position to 0 (feet position)
648 for (video::S3DVertex &vertex : vertices)
651 u16 indices[] = {0,1,2,2,3,0};
652 buf->append(vertices, 4, indices, 6);
654 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
655 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
656 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
657 buf->getMaterial().MaterialType = m_material_type;
659 if (m_enable_shaders) {
660 buf->getMaterial().EmissiveColor = c;
661 buf->getMaterial().setFlag(video::EMF_GOURAUD_SHADING, false);
662 buf->getMaterial().setFlag(video::EMF_NORMALIZE_NORMALS, true);
666 mesh->addMeshBuffer(buf);
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);
700 m_meshnode = RenderingEngine::get_scene_manager()->
701 addMeshSceneNode(mesh, m_matrixnode);
704 // Set it to use the materials of the meshbuffers directly.
705 // This is needed for changing the texture in the future
706 m_meshnode->setReadOnlyMaterials(true);
707 } else if (m_prop.visual == "cube") {
709 scene::IMesh *mesh = createCubeMesh(v3f(BS,BS,BS));
710 m_meshnode = RenderingEngine::get_scene_manager()->
711 addMeshSceneNode(mesh, m_matrixnode);
715 m_meshnode->setScale(m_prop.visual_size);
716 m_meshnode->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
717 m_prop.backface_culling);
719 setSceneNodeMaterial(m_meshnode);
720 } else if (m_prop.visual == "mesh") {
722 scene::IAnimatedMesh *mesh = m_client->getMesh(m_prop.mesh, true);
724 m_animated_meshnode = RenderingEngine::get_scene_manager()->
725 addAnimatedMeshSceneNode(mesh, m_matrixnode);
726 m_animated_meshnode->grab();
727 mesh->drop(); // The scene node took hold of it
728 m_animated_meshnode->animateJoints(); // Needed for some animations
729 m_animated_meshnode->setScale(m_prop.visual_size);
731 // set vertex colors to ensure alpha is set
732 setMeshColor(m_animated_meshnode->getMesh(), video::SColor(0xFFFFFFFF));
734 setAnimatedMeshColor(m_animated_meshnode, video::SColor(0xFFFFFFFF));
736 setSceneNodeMaterial(m_animated_meshnode);
738 m_animated_meshnode->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
739 m_prop.backface_culling);
741 errorstream<<"GenericCAO::addToScene(): Could not load mesh "<<m_prop.mesh<<std::endl;
742 } else if (m_prop.visual == "wielditem" || m_prop.visual == "item") {
745 if (m_prop.wield_item.empty()) {
746 // Old format, only textures are specified.
747 infostream << "textures: " << m_prop.textures.size() << std::endl;
748 if (!m_prop.textures.empty()) {
749 infostream << "textures[0]: " << m_prop.textures[0]
751 IItemDefManager *idef = m_client->idef();
752 item = ItemStack(m_prop.textures[0], 1, 0, idef);
755 infostream << "serialized form: " << m_prop.wield_item << std::endl;
756 item.deSerialize(m_prop.wield_item, m_client->idef());
758 m_wield_meshnode = new WieldMeshSceneNode(
759 RenderingEngine::get_scene_manager(), -1);
760 m_wield_meshnode->setItem(item, m_client,
761 (m_prop.visual == "wielditem"));
763 m_wield_meshnode->setScale(m_prop.visual_size / 2.0f);
764 m_wield_meshnode->setColor(video::SColor(0xFFFFFFFF));
766 infostream<<"GenericCAO::addToScene(): \""<<m_prop.visual
767 <<"\" not supported"<<std::endl;
770 /* don't update while punch texture modifier is active */
771 if (m_reset_textures_timer < 0)
772 updateTextures(m_current_texture_modifier);
774 scene::ISceneNode *node = getSceneNode();
776 if (node && m_matrixnode)
777 node->setParent(m_matrixnode);
779 if (node && !m_prop.nametag.empty() && !m_is_local_player) {
782 pos.Y = m_prop.selectionbox.MaxEdge.Y + 0.3f;
783 m_nametag = m_client->getCamera()->addNametag(node,
784 m_prop.nametag, m_prop.nametag_color,
790 updateBonePosition();
792 setNodeLight(m_last_light);
795 void GenericCAO::updateLight(u8 light_at_pos)
797 // Don't update light of attached one
798 if (getParent() != NULL) {
802 updateLightNoCheck(light_at_pos);
804 // Update light of all children
805 for (u16 i : m_attachment_child_ids) {
806 ClientActiveObject *obj = m_env->getActiveObject(i);
808 obj->updateLightNoCheck(light_at_pos);
813 void GenericCAO::updateLightNoCheck(u8 light_at_pos)
818 u8 li = decode_light(light_at_pos + m_glow);
820 if (li != m_last_light) {
826 void GenericCAO::setNodeLight(u8 light)
828 video::SColor color(255, light, light, light);
830 if (m_prop.visual == "wielditem" || m_prop.visual == "item") {
831 if (m_wield_meshnode)
832 m_wield_meshnode->setNodeLightColor(color);
836 if (m_enable_shaders) {
837 if (m_prop.visual == "upright_sprite") {
841 scene::IMesh *mesh = m_meshnode->getMesh();
842 for (u32 i = 0; i < mesh->getMeshBufferCount(); ++i) {
843 scene::IMeshBuffer *buf = mesh->getMeshBuffer(i);
844 buf->getMaterial().EmissiveColor = color;
847 scene::ISceneNode *node = getSceneNode();
851 for (u32 i = 0; i < node->getMaterialCount(); ++i) {
852 video::SMaterial &material = node->getMaterial(i);
853 material.EmissiveColor = color;
858 setMeshColor(m_meshnode->getMesh(), color);
859 } else if (m_animated_meshnode) {
860 setAnimatedMeshColor(m_animated_meshnode, color);
861 } else if (m_spritenode) {
862 m_spritenode->setColor(color);
867 v3s16 GenericCAO::getLightPosition()
870 return floatToInt(m_position + v3f(0, 0.5 * BS, 0), BS);
872 return floatToInt(m_position, BS);
875 void GenericCAO::updateNodePos()
877 if (getParent() != NULL)
880 scene::ISceneNode *node = getSceneNode();
883 v3s16 camera_offset = m_env->getCameraOffset();
884 v3f pos = pos_translator.val_current -
885 intToFloat(camera_offset, BS);
886 getPosRotMatrix().setTranslation(pos);
887 if (node != m_spritenode) { // rotate if not a sprite
888 v3f rot = m_is_local_player ? -m_rotation : -rot_translator.val_current;
889 setPitchYawRoll(getPosRotMatrix(), rot);
894 void GenericCAO::step(float dtime, ClientEnvironment *env)
896 if (m_animated_meshnode) {
897 m_animated_meshnode->animateJoints();
898 updateBonePosition();
901 // Handle model animations and update positions instantly to prevent lags
902 if (m_is_local_player) {
903 LocalPlayer *player = m_env->getLocalPlayer();
904 m_position = player->getPosition();
905 pos_translator.val_current = m_position;
906 m_rotation.Y = wrapDegrees_0_360(player->getYaw());
907 rot_translator.val_current = m_rotation;
910 int old_anim = player->last_animation;
911 float old_anim_speed = player->last_animation_speed;
912 m_velocity = v3f(0,0,0);
913 m_acceleration = v3f(0,0,0);
914 const PlayerControl &controls = player->getPlayerControl();
916 bool walking = false;
917 if (controls.up || controls.down || controls.left || controls.right ||
918 controls.forw_move_joystick_axis != 0.f ||
919 controls.sidew_move_joystick_axis != 0.f)
922 f32 new_speed = player->local_animation_speed;
923 v2s32 new_anim = v2s32(0,0);
924 bool allow_update = false;
926 // increase speed if using fast or flying fast
927 if((g_settings->getBool("fast_move") &&
928 m_client->checkLocalPrivilege("fast")) &&
930 (!player->touching_ground &&
931 g_settings->getBool("free_move") &&
932 m_client->checkLocalPrivilege("fly"))))
934 // slowdown speed if sneeking
935 if (controls.sneak && walking)
938 if (walking && (controls.LMB || controls.RMB)) {
939 new_anim = player->local_animations[3];
940 player->last_animation = WD_ANIM;
942 new_anim = player->local_animations[1];
943 player->last_animation = WALK_ANIM;
944 } else if(controls.LMB || controls.RMB) {
945 new_anim = player->local_animations[2];
946 player->last_animation = DIG_ANIM;
949 // Apply animations if input detected and not attached
950 // or set idle animation
951 if ((new_anim.X + new_anim.Y) > 0 && !getParent()) {
953 m_animation_range = new_anim;
954 m_animation_speed = new_speed;
955 player->last_animation_speed = m_animation_speed;
957 player->last_animation = NO_ANIM;
959 if (old_anim != NO_ANIM) {
960 m_animation_range = player->local_animations[0];
965 // Update local player animations
966 if ((player->last_animation != old_anim ||
967 m_animation_speed != old_anim_speed) &&
968 player->last_animation != NO_ANIM && allow_update)
974 if (m_visuals_expired && m_smgr) {
975 m_visuals_expired = false;
977 // Attachments, part 1: All attached objects must be unparented first,
978 // or Irrlicht causes a segmentation fault
979 for (u16 cao_id : m_attachment_child_ids) {
980 ClientActiveObject *obj = m_env->getActiveObject(cao_id);
982 scene::ISceneNode *child_node = obj->getSceneNode();
983 // The node's parent is always an IDummyTraformationSceneNode,
984 // so we need to reparent that one instead.
986 child_node->getParent()->setParent(m_smgr->getRootSceneNode());
990 removeFromScene(false);
991 addToScene(m_client->tsrc());
993 // Attachments, part 2: Now that the parent has been refreshed, put its attachments back
994 for (u16 cao_id : m_attachment_child_ids) {
995 ClientActiveObject *obj = m_env->getActiveObject(cao_id);
997 obj->updateAttachments();
1001 // Make sure m_is_visible is always applied
1002 scene::ISceneNode *node = getSceneNode();
1004 node->setVisible(m_is_visible);
1006 if(getParent() != NULL) // Attachments should be glued to their parent by Irrlicht
1008 // Set these for later
1009 m_position = getPosition();
1010 m_velocity = v3f(0,0,0);
1011 m_acceleration = v3f(0,0,0);
1012 pos_translator.val_current = m_position;
1013 pos_translator.val_target = m_position;
1015 rot_translator.translate(dtime);
1016 v3f lastpos = pos_translator.val_current;
1020 aabb3f box = m_prop.collisionbox;
1023 collisionMoveResult moveresult;
1024 f32 pos_max_d = BS*0.125; // Distance per iteration
1025 v3f p_pos = m_position;
1026 v3f p_velocity = m_velocity;
1027 moveresult = collisionMoveSimple(env,env->getGameDef(),
1028 pos_max_d, box, m_prop.stepheight, dtime,
1029 &p_pos, &p_velocity, m_acceleration,
1030 this, m_prop.collideWithObjects);
1033 m_velocity = p_velocity;
1035 bool is_end_position = moveresult.collides;
1036 pos_translator.update(m_position, is_end_position, dtime);
1038 m_position += dtime * m_velocity + 0.5 * dtime * dtime * m_acceleration;
1039 m_velocity += dtime * m_acceleration;
1040 pos_translator.update(m_position, pos_translator.aim_is_end,
1041 pos_translator.anim_time);
1043 pos_translator.translate(dtime);
1046 float moved = lastpos.getDistanceFrom(pos_translator.val_current);
1047 m_step_distance_counter += moved;
1048 if (m_step_distance_counter > 1.5f * BS) {
1049 m_step_distance_counter = 0.0f;
1050 if (!m_is_local_player && m_prop.makes_footstep_sound) {
1051 const NodeDefManager *ndef = m_client->ndef();
1052 v3s16 p = floatToInt(getPosition() +
1053 v3f(0.0f, (m_prop.collisionbox.MinEdge.Y - 0.5f) * BS, 0.0f), BS);
1054 MapNode n = m_env->getMap().getNode(p);
1055 SimpleSoundSpec spec = ndef->get(n).sound_footstep;
1056 // Reduce footstep gain, as non-local-player footsteps are
1059 m_client->sound()->playSoundAt(spec, false, getPosition());
1064 m_anim_timer += dtime;
1065 if(m_anim_timer >= m_anim_framelength)
1067 m_anim_timer -= m_anim_framelength;
1069 if(m_anim_frame >= m_anim_num_frames)
1075 if(m_reset_textures_timer >= 0)
1077 m_reset_textures_timer -= dtime;
1078 if(m_reset_textures_timer <= 0) {
1079 m_reset_textures_timer = -1;
1080 updateTextures(m_previous_texture_modifier);
1084 if (!getParent() && std::fabs(m_prop.automatic_rotate) > 0.001) {
1085 // This is the child node's rotation. It is only used for automatic_rotate.
1086 v3f local_rot = node->getRotation();
1087 local_rot.Y = modulo360f(local_rot.Y - dtime * core::RADTODEG *
1088 m_prop.automatic_rotate);
1089 node->setRotation(local_rot);
1092 if (!getParent() && m_prop.automatic_face_movement_dir &&
1093 (fabs(m_velocity.Z) > 0.001 || fabs(m_velocity.X) > 0.001)) {
1094 float target_yaw = atan2(m_velocity.Z, m_velocity.X) * 180 / M_PI
1095 + m_prop.automatic_face_movement_dir_offset;
1096 float max_rotation_per_sec =
1097 m_prop.automatic_face_movement_max_rotation_per_sec;
1099 if (max_rotation_per_sec > 0) {
1100 wrappedApproachShortest(m_rotation.Y, target_yaw,
1101 dtime * max_rotation_per_sec, 360.f);
1103 // Negative values of max_rotation_per_sec mean disabled.
1104 m_rotation.Y = target_yaw;
1107 rot_translator.val_current = m_rotation;
1112 void GenericCAO::updateTexturePos()
1116 scene::ICameraSceneNode* camera =
1117 m_spritenode->getSceneManager()->getActiveCamera();
1120 v3f cam_to_entity = m_spritenode->getAbsolutePosition()
1121 - camera->getAbsolutePosition();
1122 cam_to_entity.normalize();
1124 int row = m_tx_basepos.Y;
1125 int col = m_tx_basepos.X;
1127 if (m_tx_select_horiz_by_yawpitch) {
1128 if (cam_to_entity.Y > 0.75)
1130 else if (cam_to_entity.Y < -0.75)
1134 atan2(cam_to_entity.Z, cam_to_entity.X) / M_PI * 180.;
1135 float dir = mob_dir - m_rotation.Y;
1136 dir = wrapDegrees_180(dir);
1137 if (std::fabs(wrapDegrees_180(dir - 0)) <= 45.1f)
1139 else if(std::fabs(wrapDegrees_180(dir - 90)) <= 45.1f)
1141 else if(std::fabs(wrapDegrees_180(dir - 180)) <= 45.1f)
1143 else if(std::fabs(wrapDegrees_180(dir + 90)) <= 45.1f)
1150 // Animation goes downwards
1151 row += m_anim_frame;
1153 float txs = m_tx_size.X;
1154 float tys = m_tx_size.Y;
1155 setBillboardTextureMatrix(m_spritenode, txs, tys, col, row);
1159 // Do not pass by reference, see header.
1160 void GenericCAO::updateTextures(std::string mod)
1162 ITextureSource *tsrc = m_client->tsrc();
1164 bool use_trilinear_filter = g_settings->getBool("trilinear_filter");
1165 bool use_bilinear_filter = g_settings->getBool("bilinear_filter");
1166 bool use_anisotropic_filter = g_settings->getBool("anisotropic_filter");
1168 m_previous_texture_modifier = m_current_texture_modifier;
1169 m_current_texture_modifier = mod;
1170 m_glow = m_prop.glow;
1173 if (m_prop.visual == "sprite") {
1174 std::string texturestring = "unknown_node.png";
1175 if (!m_prop.textures.empty())
1176 texturestring = m_prop.textures[0];
1177 texturestring += mod;
1178 m_spritenode->getMaterial(0).MaterialType = m_material_type;
1179 m_spritenode->getMaterial(0).MaterialTypeParam = 0.5f;
1180 m_spritenode->setMaterialTexture(0,
1181 tsrc->getTextureForMesh(texturestring));
1183 // This allows setting per-material colors. However, until a real lighting
1184 // system is added, the code below will have no effect. Once MineTest
1185 // has directional lighting, it should work automatically.
1186 if (!m_prop.colors.empty()) {
1187 m_spritenode->getMaterial(0).AmbientColor = m_prop.colors[0];
1188 m_spritenode->getMaterial(0).DiffuseColor = m_prop.colors[0];
1189 m_spritenode->getMaterial(0).SpecularColor = m_prop.colors[0];
1192 m_spritenode->getMaterial(0).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1193 m_spritenode->getMaterial(0).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1194 m_spritenode->getMaterial(0).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1198 if (m_animated_meshnode) {
1199 if (m_prop.visual == "mesh") {
1200 for (u32 i = 0; i < m_prop.textures.size() &&
1201 i < m_animated_meshnode->getMaterialCount(); ++i) {
1202 std::string texturestring = m_prop.textures[i];
1203 if (texturestring.empty())
1204 continue; // Empty texture string means don't modify that material
1205 texturestring += mod;
1206 video::ITexture* texture = tsrc->getTextureForMesh(texturestring);
1208 errorstream<<"GenericCAO::updateTextures(): Could not load texture "<<texturestring<<std::endl;
1212 // Set material flags and texture
1213 video::SMaterial& material = m_animated_meshnode->getMaterial(i);
1214 material.MaterialType = m_material_type;
1215 material.MaterialTypeParam = 0.5f;
1216 material.TextureLayer[0].Texture = texture;
1217 material.setFlag(video::EMF_LIGHTING, true);
1218 material.setFlag(video::EMF_BILINEAR_FILTER, false);
1219 material.setFlag(video::EMF_BACK_FACE_CULLING, m_prop.backface_culling);
1221 // don't filter low-res textures, makes them look blurry
1222 // player models have a res of 64
1223 const core::dimension2d<u32> &size = texture->getOriginalSize();
1224 const u32 res = std::min(size.Height, size.Width);
1225 use_trilinear_filter &= res > 64;
1226 use_bilinear_filter &= res > 64;
1228 m_animated_meshnode->getMaterial(i)
1229 .setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1230 m_animated_meshnode->getMaterial(i)
1231 .setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1232 m_animated_meshnode->getMaterial(i)
1233 .setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1235 for (u32 i = 0; i < m_prop.colors.size() &&
1236 i < m_animated_meshnode->getMaterialCount(); ++i)
1238 // This allows setting per-material colors. However, until a real lighting
1239 // system is added, the code below will have no effect. Once MineTest
1240 // has directional lighting, it should work automatically.
1241 m_animated_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i];
1242 m_animated_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i];
1243 m_animated_meshnode->getMaterial(i).SpecularColor = m_prop.colors[i];
1249 if(m_prop.visual == "cube")
1251 for (u32 i = 0; i < 6; ++i)
1253 std::string texturestring = "unknown_node.png";
1254 if(m_prop.textures.size() > i)
1255 texturestring = m_prop.textures[i];
1256 texturestring += mod;
1259 // Set material flags and texture
1260 video::SMaterial& material = m_meshnode->getMaterial(i);
1261 material.MaterialType = m_material_type;
1262 material.MaterialTypeParam = 0.5f;
1263 material.setFlag(video::EMF_LIGHTING, false);
1264 material.setFlag(video::EMF_BILINEAR_FILTER, false);
1265 material.setTexture(0,
1266 tsrc->getTextureForMesh(texturestring));
1267 material.getTextureMatrix(0).makeIdentity();
1269 // This allows setting per-material colors. However, until a real lighting
1270 // system is added, the code below will have no effect. Once MineTest
1271 // has directional lighting, it should work automatically.
1272 if(m_prop.colors.size() > i)
1274 m_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i];
1275 m_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i];
1276 m_meshnode->getMaterial(i).SpecularColor = m_prop.colors[i];
1279 m_meshnode->getMaterial(i).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1280 m_meshnode->getMaterial(i).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1281 m_meshnode->getMaterial(i).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1283 } else if (m_prop.visual == "upright_sprite") {
1284 scene::IMesh *mesh = m_meshnode->getMesh();
1286 std::string tname = "unknown_object.png";
1287 if (!m_prop.textures.empty())
1288 tname = m_prop.textures[0];
1290 scene::IMeshBuffer *buf = mesh->getMeshBuffer(0);
1291 buf->getMaterial().setTexture(0,
1292 tsrc->getTextureForMesh(tname));
1294 // This allows setting per-material colors. However, until a real lighting
1295 // system is added, the code below will have no effect. Once MineTest
1296 // has directional lighting, it should work automatically.
1297 if(!m_prop.colors.empty()) {
1298 buf->getMaterial().AmbientColor = m_prop.colors[0];
1299 buf->getMaterial().DiffuseColor = m_prop.colors[0];
1300 buf->getMaterial().SpecularColor = m_prop.colors[0];
1303 buf->getMaterial().setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1304 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1305 buf->getMaterial().setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1308 std::string tname = "unknown_object.png";
1309 if (m_prop.textures.size() >= 2)
1310 tname = m_prop.textures[1];
1311 else if (!m_prop.textures.empty())
1312 tname = m_prop.textures[0];
1314 scene::IMeshBuffer *buf = mesh->getMeshBuffer(1);
1315 buf->getMaterial().setTexture(0,
1316 tsrc->getTextureForMesh(tname));
1318 // This allows setting per-material colors. However, until a real lighting
1319 // system is added, the code below will have no effect. Once MineTest
1320 // has directional lighting, it should work automatically.
1321 if (m_prop.colors.size() >= 2) {
1322 buf->getMaterial().AmbientColor = m_prop.colors[1];
1323 buf->getMaterial().DiffuseColor = m_prop.colors[1];
1324 buf->getMaterial().SpecularColor = m_prop.colors[1];
1325 } else if (!m_prop.colors.empty()) {
1326 buf->getMaterial().AmbientColor = m_prop.colors[0];
1327 buf->getMaterial().DiffuseColor = m_prop.colors[0];
1328 buf->getMaterial().SpecularColor = m_prop.colors[0];
1331 buf->getMaterial().setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1332 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1333 buf->getMaterial().setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1335 // Set mesh color (only if lighting is disabled)
1336 if (!m_prop.colors.empty() && m_glow < 0)
1337 setMeshColor(mesh, m_prop.colors[0]);
1342 void GenericCAO::updateAnimation()
1344 if (!m_animated_meshnode)
1347 if (m_animated_meshnode->getStartFrame() != m_animation_range.X ||
1348 m_animated_meshnode->getEndFrame() != m_animation_range.Y)
1349 m_animated_meshnode->setFrameLoop(m_animation_range.X, m_animation_range.Y);
1350 if (m_animated_meshnode->getAnimationSpeed() != m_animation_speed)
1351 m_animated_meshnode->setAnimationSpeed(m_animation_speed);
1352 m_animated_meshnode->setTransitionTime(m_animation_blend);
1353 // Requires Irrlicht 1.8 or greater
1354 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR > 1
1355 if (m_animated_meshnode->getLoopMode() != m_animation_loop)
1356 m_animated_meshnode->setLoopMode(m_animation_loop);
1360 void GenericCAO::updateAnimationSpeed()
1362 if (!m_animated_meshnode)
1365 m_animated_meshnode->setAnimationSpeed(m_animation_speed);
1368 void GenericCAO::updateBonePosition()
1370 if (m_bone_position.empty() || !m_animated_meshnode)
1373 m_animated_meshnode->setJointMode(irr::scene::EJUOR_CONTROL); // To write positions to the mesh on render
1374 for (auto &it : m_bone_position) {
1375 std::string bone_name = it.first;
1376 irr::scene::IBoneSceneNode* bone = m_animated_meshnode->getJointNode(bone_name.c_str());
1378 bone->setPosition(it.second.X);
1379 bone->setRotation(it.second.Y);
1383 // search through bones to find mistakenly rotated bones due to bug in Irrlicht
1384 for (u32 i = 0; i < m_animated_meshnode->getJointCount(); ++i) {
1385 irr::scene::IBoneSceneNode *bone = m_animated_meshnode->getJointNode(i);
1389 //If bone is manually positioned there is no need to perform the bug check
1391 for (auto &it : m_bone_position) {
1392 if (it.first == bone->getName()) {
1400 // Workaround for Irrlicht bug
1401 // We check each bone to see if it has been rotated ~180deg from its expected position due to a bug in Irricht
1402 // when using EJUOR_CONTROL joint control. If the bug is detected we update the bone to the proper position
1403 // and update the bones transformation.
1404 v3f bone_rot = bone->getRelativeTransformation().getRotationDegrees();
1405 float offset = fabsf(bone_rot.X - bone->getRotation().X);
1406 if (offset > 179.9f && offset < 180.1f) {
1407 bone->setRotation(bone_rot);
1408 bone->updateAbsolutePosition();
1413 void GenericCAO::updateAttachments()
1415 ClientActiveObject *parent = getParent();
1417 m_attached_to_local = parent && parent->isLocalPlayer();
1420 Following cases exist:
1421 m_attachment_parent_id == 0 && !parent
1422 This object is not attached
1423 m_attachment_parent_id != 0 && parent
1424 This object is attached
1425 m_attachment_parent_id != 0 && !parent
1426 This object will be attached as soon the parent is known
1427 m_attachment_parent_id == 0 && parent
1431 if (!parent) { // Detach or don't attach
1433 v3f old_pos = getPosition();
1435 m_matrixnode->setParent(m_smgr->getRootSceneNode());
1436 getPosRotMatrix().setTranslation(old_pos);
1437 m_matrixnode->updateAbsolutePosition();
1442 scene::ISceneNode *parent_node = parent->getSceneNode();
1443 scene::IAnimatedMeshSceneNode *parent_animated_mesh_node =
1444 parent->getAnimatedMeshSceneNode();
1445 if (parent_animated_mesh_node && !m_attachment_bone.empty()) {
1446 parent_node = parent_animated_mesh_node->getJointNode(m_attachment_bone.c_str());
1449 if (m_matrixnode && parent_node) {
1450 m_matrixnode->setParent(parent_node);
1451 getPosRotMatrix().setTranslation(m_attachment_position);
1452 //setPitchYawRoll(getPosRotMatrix(), m_attachment_rotation);
1453 // use Irrlicht eulers instead
1454 getPosRotMatrix().setRotationDegrees(m_attachment_rotation);
1455 m_matrixnode->updateAbsolutePosition();
1460 bool GenericCAO::visualExpiryRequired(const ObjectProperties &new_) const
1462 const ObjectProperties &old = m_prop;
1463 // Ordered to compare primitive types before std::vectors
1464 return old.backface_culling != new_.backface_culling ||
1465 old.initial_sprite_basepos != new_.initial_sprite_basepos ||
1466 old.is_visible != new_.is_visible ||
1467 old.mesh != new_.mesh ||
1468 old.nametag != new_.nametag ||
1469 old.nametag_color != new_.nametag_color ||
1470 old.spritediv != new_.spritediv ||
1471 old.use_texture_alpha != new_.use_texture_alpha ||
1472 old.visual != new_.visual ||
1473 old.visual_size != new_.visual_size ||
1474 old.wield_item != new_.wield_item ||
1475 old.colors != new_.colors ||
1476 old.textures != new_.textures;
1479 void GenericCAO::processMessage(const std::string &data)
1481 //infostream<<"GenericCAO: Got message"<<std::endl;
1482 std::istringstream is(data, std::ios::binary);
1484 u8 cmd = readU8(is);
1485 if (cmd == AO_CMD_SET_PROPERTIES) {
1486 ObjectProperties newprops;
1487 newprops.deSerialize(is);
1489 // Check what exactly changed
1490 bool expire_visuals = visualExpiryRequired(newprops);
1493 m_prop = std::move(newprops);
1495 m_selection_box = m_prop.selectionbox;
1496 m_selection_box.MinEdge *= BS;
1497 m_selection_box.MaxEdge *= BS;
1499 m_tx_size.X = 1.0f / m_prop.spritediv.X;
1500 m_tx_size.Y = 1.0f / m_prop.spritediv.Y;
1502 if(!m_initial_tx_basepos_set){
1503 m_initial_tx_basepos_set = true;
1504 m_tx_basepos = m_prop.initial_sprite_basepos;
1506 if (m_is_local_player) {
1507 LocalPlayer *player = m_env->getLocalPlayer();
1508 player->makes_footstep_sound = m_prop.makes_footstep_sound;
1509 aabb3f collision_box = m_prop.collisionbox;
1510 collision_box.MinEdge *= BS;
1511 collision_box.MaxEdge *= BS;
1512 player->setCollisionbox(collision_box);
1513 player->setEyeHeight(m_prop.eye_height);
1514 player->setZoomFOV(m_prop.zoom_fov);
1517 if ((m_is_player && !m_is_local_player) && m_prop.nametag.empty())
1518 m_prop.nametag = m_name;
1520 if (expire_visuals) {
1523 infostream << "GenericCAO: properties updated but expiring visuals"
1524 << " not necessary" << std::endl;
1526 } else if (cmd == AO_CMD_UPDATE_POSITION) {
1527 // Not sent by the server if this object is an attachment.
1528 // We might however get here if the server notices the object being detached before the client.
1529 m_position = readV3F32(is);
1530 m_velocity = readV3F32(is);
1531 m_acceleration = readV3F32(is);
1532 m_rotation = readV3F32(is);
1534 m_rotation = wrapDegrees_0_360_v3f(m_rotation);
1535 bool do_interpolate = readU8(is);
1536 bool is_end_position = readU8(is);
1537 float update_interval = readF32(is);
1539 // Place us a bit higher if we're physical, to not sink into
1540 // the ground due to sucky collision detection...
1542 m_position += v3f(0,0.002,0);
1544 if(getParent() != NULL) // Just in case
1549 if(!m_prop.physical)
1550 pos_translator.update(m_position, is_end_position, update_interval);
1552 pos_translator.init(m_position);
1554 rot_translator.update(m_rotation, false, update_interval);
1556 } else if (cmd == AO_CMD_SET_TEXTURE_MOD) {
1557 std::string mod = deSerializeString(is);
1559 // immediately reset a engine issued texture modifier if a mod sends a different one
1560 if (m_reset_textures_timer > 0) {
1561 m_reset_textures_timer = -1;
1562 updateTextures(m_previous_texture_modifier);
1564 updateTextures(mod);
1565 } else if (cmd == AO_CMD_SET_SPRITE) {
1566 v2s16 p = readV2S16(is);
1567 int num_frames = readU16(is);
1568 float framelength = readF32(is);
1569 bool select_horiz_by_yawpitch = readU8(is);
1572 m_anim_num_frames = num_frames;
1573 m_anim_framelength = framelength;
1574 m_tx_select_horiz_by_yawpitch = select_horiz_by_yawpitch;
1577 } else if (cmd == AO_CMD_SET_PHYSICS_OVERRIDE) {
1578 float override_speed = readF32(is);
1579 float override_jump = readF32(is);
1580 float override_gravity = readF32(is);
1581 // these are sent inverted so we get true when the server sends nothing
1582 bool sneak = !readU8(is);
1583 bool sneak_glitch = !readU8(is);
1584 bool new_move = !readU8(is);
1587 if(m_is_local_player)
1589 LocalPlayer *player = m_env->getLocalPlayer();
1590 player->physics_override_speed = override_speed;
1591 player->physics_override_jump = override_jump;
1592 player->physics_override_gravity = override_gravity;
1593 player->physics_override_sneak = sneak;
1594 player->physics_override_sneak_glitch = sneak_glitch;
1595 player->physics_override_new_move = new_move;
1597 } else if (cmd == AO_CMD_SET_ANIMATION) {
1598 // TODO: change frames send as v2s32 value
1599 v2f range = readV2F32(is);
1600 if (!m_is_local_player) {
1601 m_animation_range = v2s32((s32)range.X, (s32)range.Y);
1602 m_animation_speed = readF32(is);
1603 m_animation_blend = readF32(is);
1604 // these are sent inverted so we get true when the server sends nothing
1605 m_animation_loop = !readU8(is);
1608 LocalPlayer *player = m_env->getLocalPlayer();
1609 if(player->last_animation == NO_ANIM)
1611 m_animation_range = v2s32((s32)range.X, (s32)range.Y);
1612 m_animation_speed = readF32(is);
1613 m_animation_blend = readF32(is);
1614 // these are sent inverted so we get true when the server sends nothing
1615 m_animation_loop = !readU8(is);
1617 // update animation only if local animations present
1618 // and received animation is unknown (except idle animation)
1619 bool is_known = false;
1620 for (int i = 1;i<4;i++)
1622 if(m_animation_range.Y == player->local_animations[i].Y)
1626 (player->local_animations[1].Y + player->local_animations[2].Y < 1))
1631 } else if (cmd == AO_CMD_SET_ANIMATION_SPEED) {
1632 m_animation_speed = readF32(is);
1633 updateAnimationSpeed();
1634 } else if (cmd == AO_CMD_SET_BONE_POSITION) {
1635 std::string bone = deSerializeString(is);
1636 v3f position = readV3F32(is);
1637 v3f rotation = readV3F32(is);
1638 m_bone_position[bone] = core::vector2d<v3f>(position, rotation);
1640 // updateBonePosition(); now called every step
1641 } else if (cmd == AO_CMD_ATTACH_TO) {
1642 u16 parent_id = readS16(is);
1643 std::string bone = deSerializeString(is);
1644 v3f position = readV3F32(is);
1645 v3f rotation = readV3F32(is);
1647 setAttachment(parent_id, bone, position, rotation);
1649 // localplayer itself can't be attached to localplayer
1650 if (!m_is_local_player)
1651 m_is_visible = !m_attached_to_local;
1652 } else if (cmd == AO_CMD_PUNCHED) {
1653 u16 result_hp = readU16(is);
1655 // Use this instead of the send damage to not interfere with prediction
1656 s32 damage = (s32)m_hp - (s32)result_hp;
1660 if (m_is_local_player)
1661 m_env->getLocalPlayer()->hp = m_hp;
1667 // TODO: Execute defined fast response
1668 // As there is no definition, make a smoke puff
1669 ClientSimpleObject *simple = createSmokePuff(
1670 m_smgr, m_env, m_position,
1671 v2f(m_prop.visual_size.X, m_prop.visual_size.Y) * BS);
1672 m_env->addSimpleObject(simple);
1673 } else if (m_reset_textures_timer < 0 && !m_prop.damage_texture_modifier.empty()) {
1674 m_reset_textures_timer = 0.05;
1676 m_reset_textures_timer += 0.05 * damage;
1677 updateTextures(m_current_texture_modifier + m_prop.damage_texture_modifier);
1682 // Same as 'Server::DiePlayer'
1683 clearParentAttachment();
1684 // Same as 'ObjectRef::l_remove'
1686 clearChildAttachments();
1688 } else if (cmd == AO_CMD_UPDATE_ARMOR_GROUPS) {
1689 m_armor_groups.clear();
1690 int armor_groups_size = readU16(is);
1691 for(int i=0; i<armor_groups_size; i++)
1693 std::string name = deSerializeString(is);
1694 int rating = readS16(is);
1695 m_armor_groups[name] = rating;
1697 } else if (cmd == AO_CMD_UPDATE_NAMETAG_ATTRIBUTES) {
1698 // Deprecated, for backwards compatibility only.
1699 readU8(is); // version
1700 m_prop.nametag_color = readARGB8(is);
1701 if (m_nametag != NULL) {
1702 m_nametag->nametag_color = m_prop.nametag_color;
1704 pos.Y = m_prop.collisionbox.MaxEdge.Y + 0.3f;
1705 m_nametag->nametag_pos = pos;
1707 } else if (cmd == AO_CMD_SPAWN_INFANT) {
1708 u16 child_id = readU16(is);
1709 u8 type = readU8(is); // maybe this will be useful later
1712 addAttachmentChild(child_id);
1714 warningstream << FUNCTION_NAME
1715 << ": unknown command or outdated client \""
1716 << +cmd << "\"" << std::endl;
1720 /* \pre punchitem != NULL
1722 bool GenericCAO::directReportPunch(v3f dir, const ItemStack *punchitem,
1723 float time_from_last_punch)
1725 assert(punchitem); // pre-condition
1726 const ToolCapabilities *toolcap =
1727 &punchitem->getToolCapabilities(m_client->idef());
1728 PunchDamageResult result = getPunchDamage(
1732 time_from_last_punch);
1734 if(result.did_punch && result.damage != 0)
1736 if(result.damage < m_hp)
1738 m_hp -= result.damage;
1741 // TODO: Execute defined fast response
1742 // As there is no definition, make a smoke puff
1743 ClientSimpleObject *simple = createSmokePuff(
1744 m_smgr, m_env, m_position,
1745 v2f(m_prop.visual_size.X, m_prop.visual_size.Y) * BS);
1746 m_env->addSimpleObject(simple);
1748 if (m_reset_textures_timer < 0 && !m_prop.damage_texture_modifier.empty()) {
1749 m_reset_textures_timer = 0.05;
1750 if (result.damage >= 2)
1751 m_reset_textures_timer += 0.05 * result.damage;
1752 updateTextures(m_current_texture_modifier + m_prop.damage_texture_modifier);
1759 std::string GenericCAO::debugInfoText()
1761 std::ostringstream os(std::ios::binary);
1762 os<<"GenericCAO hp="<<m_hp<<"\n";
1764 for(ItemGroupList::const_iterator i = m_armor_groups.begin();
1765 i != m_armor_groups.end(); ++i)
1767 os<<i->first<<"="<<i->second<<", ";
1774 GenericCAO proto_GenericCAO(NULL, NULL);