3 Copyright (C) 2010-2011 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"
22 #include "environment.h"
23 #include "collision.h"
25 #include <ICameraSceneNode.h>
26 #include <ITextSceneNode.h>
27 #include <IBillboardSceneNode.h>
28 #include "serialization.h" // For decompressZlib
30 #include "clientobject.h"
31 #include "content_object.h"
35 #include "content_cso.h"
38 #include "localplayer.h"
39 #include "util/numeric.h" // For IntervalLimiter
40 #include "util/serialize.h"
41 #include "util/mathconstants.h"
43 #include <IMeshManipulator.h>
44 #include <IAnimatedMeshSceneNode.h>
45 #include <IBoneSceneNode.h>
48 struct ToolCapabilities;
50 #define PP(x) "("<<(x).X<<","<<(x).Y<<","<<(x).Z<<")"
52 core::map<u16, ClientActiveObject::Factory> ClientActiveObject::m_types;
58 struct SmoothTranslator
65 f32 anim_time_counter;
85 anim_time_counter = 0;
94 void update(v3f vect_new, bool is_end_position=false, float update_interval=-1)
96 aim_is_end = is_end_position;
99 if(update_interval > 0){
100 anim_time = update_interval;
102 if(anim_time < 0.001 || anim_time > 1.0)
103 anim_time = anim_time_counter;
105 anim_time = anim_time * 0.9 + anim_time_counter * 0.1;
107 anim_time_counter = 0;
111 void translate(f32 dtime)
113 anim_time_counter = anim_time_counter + dtime;
114 anim_counter = anim_counter + dtime;
115 v3f vect_move = vect_aim - vect_old;
117 if(anim_time > 0.001)
118 moveratio = anim_time_counter / anim_time;
119 // Move a bit less than should, to avoid oscillation
120 moveratio = moveratio * 0.8;
121 float move_end = 1.5;
124 if(moveratio > move_end)
125 moveratio = move_end;
126 vect_show = vect_old + vect_move * moveratio;
131 return ((anim_time_counter / anim_time) < 1.4);
139 static void setBillboardTextureMatrix(scene::IBillboardSceneNode *bill,
140 float txs, float tys, int col, int row)
142 video::SMaterial& material = bill->getMaterial(0);
143 core::matrix4& matrix = material.getTextureMatrix(0);
144 matrix.setTextureTranslate(txs*col, tys*row);
145 matrix.setTextureScale(txs, tys);
152 class TestCAO : public ClientActiveObject
155 TestCAO(IGameDef *gamedef, ClientEnvironment *env);
160 return ACTIVEOBJECT_TYPE_TEST;
163 static ClientActiveObject* create(IGameDef *gamedef, ClientEnvironment *env);
165 void addToScene(scene::ISceneManager *smgr, ITextureSource *tsrc,
166 IrrlichtDevice *irr);
167 void removeFromScene();
168 void updateLight(u8 light_at_pos);
169 v3s16 getLightPosition();
170 void updateNodePos();
172 void step(float dtime, ClientEnvironment *env);
174 void processMessage(const std::string &data);
177 scene::IMeshSceneNode *m_node;
182 TestCAO proto_TestCAO(NULL, NULL);
184 TestCAO::TestCAO(IGameDef *gamedef, ClientEnvironment *env):
185 ClientActiveObject(0, gamedef, env),
187 m_position(v3f(0,10*BS,0))
189 ClientActiveObject::registerType(getType(), create);
196 ClientActiveObject* TestCAO::create(IGameDef *gamedef, ClientEnvironment *env)
198 return new TestCAO(gamedef, env);
201 void TestCAO::addToScene(scene::ISceneManager *smgr, ITextureSource *tsrc,
207 //video::IVideoDriver* driver = smgr->getVideoDriver();
209 scene::SMesh *mesh = new scene::SMesh();
210 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
211 video::SColor c(255,255,255,255);
212 video::S3DVertex vertices[4] =
214 video::S3DVertex(-BS/2,-BS/4,0, 0,0,0, c, 0,1),
215 video::S3DVertex(BS/2,-BS/4,0, 0,0,0, c, 1,1),
216 video::S3DVertex(BS/2,BS/4,0, 0,0,0, c, 1,0),
217 video::S3DVertex(-BS/2,BS/4,0, 0,0,0, c, 0,0),
219 u16 indices[] = {0,1,2,2,3,0};
220 buf->append(vertices, 4, indices, 6);
222 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
223 buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false);
224 buf->getMaterial().setTexture(0, tsrc->getTextureRaw("rat.png"));
225 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
226 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
227 buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
229 mesh->addMeshBuffer(buf);
231 m_node = smgr->addMeshSceneNode(mesh, NULL);
236 void TestCAO::removeFromScene()
245 void TestCAO::updateLight(u8 light_at_pos)
249 v3s16 TestCAO::getLightPosition()
251 return floatToInt(m_position, BS);
254 void TestCAO::updateNodePos()
259 m_node->setPosition(m_position);
260 //m_node->setRotation(v3f(0, 45, 0));
263 void TestCAO::step(float dtime, ClientEnvironment *env)
267 v3f rot = m_node->getRotation();
268 //infostream<<"dtime="<<dtime<<", rot.Y="<<rot.Y<<std::endl;
269 rot.Y += dtime * 180;
270 m_node->setRotation(rot);
274 void TestCAO::processMessage(const std::string &data)
276 infostream<<"TestCAO: Got data: "<<data<<std::endl;
277 std::istringstream is(data, std::ios::binary);
295 class ItemCAO : public ClientActiveObject
298 ItemCAO(IGameDef *gamedef, ClientEnvironment *env);
303 return ACTIVEOBJECT_TYPE_ITEM;
306 static ClientActiveObject* create(IGameDef *gamedef, ClientEnvironment *env);
308 void addToScene(scene::ISceneManager *smgr, ITextureSource *tsrc,
309 IrrlichtDevice *irr);
310 void removeFromScene();
311 void updateLight(u8 light_at_pos);
312 v3s16 getLightPosition();
313 void updateNodePos();
314 void updateInfoText();
315 void updateTexture();
317 void step(float dtime, ClientEnvironment *env);
319 void processMessage(const std::string &data);
321 void initialize(const std::string &data);
323 core::aabbox3d<f32>* getSelectionBox()
324 {return &m_selection_box;}
328 std::string infoText()
332 core::aabbox3d<f32> m_selection_box;
333 scene::IMeshSceneNode *m_node;
335 std::string m_itemstring;
336 std::string m_infotext;
339 #include "inventory.h"
342 ItemCAO proto_ItemCAO(NULL, NULL);
344 ItemCAO::ItemCAO(IGameDef *gamedef, ClientEnvironment *env):
345 ClientActiveObject(0, gamedef, env),
346 m_selection_box(-BS/3.,0.0,-BS/3., BS/3.,BS*2./3.,BS/3.),
348 m_position(v3f(0,10*BS,0))
352 ClientActiveObject::registerType(getType(), create);
360 ClientActiveObject* ItemCAO::create(IGameDef *gamedef, ClientEnvironment *env)
362 return new ItemCAO(gamedef, env);
365 void ItemCAO::addToScene(scene::ISceneManager *smgr, ITextureSource *tsrc,
371 //video::IVideoDriver* driver = smgr->getVideoDriver();
373 scene::SMesh *mesh = new scene::SMesh();
374 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
375 video::SColor c(255,255,255,255);
376 video::S3DVertex vertices[4] =
378 /*video::S3DVertex(-BS/2,-BS/4,0, 0,0,0, c, 0,1),
379 video::S3DVertex(BS/2,-BS/4,0, 0,0,0, c, 1,1),
380 video::S3DVertex(BS/2,BS/4,0, 0,0,0, c, 1,0),
381 video::S3DVertex(-BS/2,BS/4,0, 0,0,0, c, 0,0),*/
382 video::S3DVertex(BS/3.,0,0, 0,0,0, c, 0,1),
383 video::S3DVertex(-BS/3.,0,0, 0,0,0, c, 1,1),
384 video::S3DVertex(-BS/3.,0+BS*2./3.,0, 0,0,0, c, 1,0),
385 video::S3DVertex(BS/3.,0+BS*2./3.,0, 0,0,0, c, 0,0),
387 u16 indices[] = {0,1,2,2,3,0};
388 buf->append(vertices, 4, indices, 6);
390 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
391 buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false);
392 // Initialize with a generated placeholder texture
393 buf->getMaterial().setTexture(0, tsrc->getTextureRaw(""));
394 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
395 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
396 buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
398 mesh->addMeshBuffer(buf);
400 m_node = smgr->addMeshSceneNode(mesh, NULL);
411 void ItemCAO::removeFromScene()
420 void ItemCAO::updateLight(u8 light_at_pos)
425 u8 li = decode_light(light_at_pos);
426 video::SColor color(255,li,li,li);
427 setMeshColor(m_node->getMesh(), color);
430 v3s16 ItemCAO::getLightPosition()
432 return floatToInt(m_position + v3f(0,0.5*BS,0), BS);
435 void ItemCAO::updateNodePos()
440 m_node->setPosition(m_position);
443 void ItemCAO::updateInfoText()
446 IItemDefManager *idef = m_gamedef->idef();
448 item.deSerialize(m_itemstring, idef);
449 if(item.isKnown(idef))
450 m_infotext = item.getDefinition(idef).description;
452 m_infotext = "Unknown item: '" + m_itemstring + "'";
454 m_infotext += " (" + itos(item.count) + ")";
456 catch(SerializationError &e)
458 m_infotext = "Unknown item: '" + m_itemstring + "'";
462 void ItemCAO::updateTexture()
467 // Create an inventory item to see what is its image
468 std::istringstream is(m_itemstring, std::ios_base::binary);
469 video::ITexture *texture = NULL;
471 IItemDefManager *idef = m_gamedef->idef();
473 item.deSerialize(is, idef);
474 texture = item.getDefinition(idef).inventory_texture;
476 catch(SerializationError &e)
478 infostream<<"WARNING: "<<__FUNCTION_NAME
479 <<": error deSerializing itemstring \""
480 <<m_itemstring<<std::endl;
483 // Set meshbuffer texture
484 m_node->getMaterial(0).setTexture(0, texture);
488 void ItemCAO::step(float dtime, ClientEnvironment *env)
492 /*v3f rot = m_node->getRotation();
493 rot.Y += dtime * 120;
494 m_node->setRotation(rot);*/
495 LocalPlayer *player = env->getLocalPlayer();
497 v3f rot = m_node->getRotation();
498 rot.Y = 180.0 - (player->getYaw());
499 m_node->setRotation(rot);
503 void ItemCAO::processMessage(const std::string &data)
505 //infostream<<"ItemCAO: Got message"<<std::endl;
506 std::istringstream is(data, std::ios::binary);
512 m_position = readV3F1000(is);
518 m_itemstring = deSerializeString(is);
524 void ItemCAO::initialize(const std::string &data)
526 infostream<<"ItemCAO: Got init data"<<std::endl;
529 std::istringstream is(data, std::ios::binary);
531 u8 version = readU8(is);
536 m_position = readV3F1000(is);
538 m_itemstring = deSerializeString(is);
549 #include "genericobject.h"
551 class GenericCAO : public ClientActiveObject
554 // Only set at initialization
557 bool m_is_local_player;
559 // Property-ish things
560 ObjectProperties m_prop;
562 scene::ISceneManager *m_smgr;
563 IrrlichtDevice *m_irr;
564 core::aabbox3d<f32> m_selection_box;
565 scene::IMeshSceneNode *m_meshnode;
566 scene::IAnimatedMeshSceneNode *m_animated_meshnode;
567 scene::IBillboardSceneNode *m_spritenode;
568 scene::ITextSceneNode* m_textnode;
574 SmoothTranslator pos_translator;
575 // Spritesheet/animation stuff
578 bool m_initial_tx_basepos_set;
579 bool m_tx_select_horiz_by_yawpitch;
583 std::map<std::string, core::vector2d<v3f> > m_bone_posrot;
584 ClientActiveObject* m_attachment_parent;
585 std::string m_attachment_bone;
586 v3f m_attacmhent_position;
587 v3f m_attachment_rotation;
589 int m_anim_num_frames;
590 float m_anim_framelength;
592 ItemGroupList m_armor_groups;
593 float m_reset_textures_timer;
594 bool m_visuals_expired;
595 float m_step_distance_counter;
600 GenericCAO(IGameDef *gamedef, ClientEnvironment *env):
601 ClientActiveObject(0, gamedef, env),
604 m_is_local_player(false),
609 m_selection_box(-BS/3.,-BS/3.,-BS/3., BS/3.,BS/3.,BS/3.),
611 m_animated_meshnode(NULL),
614 m_position(v3f(0,10*BS,0)),
615 m_velocity(v3f(0,0,0)),
616 m_acceleration(v3f(0,0,0)),
621 m_initial_tx_basepos_set(false),
622 m_tx_select_horiz_by_yawpitch(false),
626 // Nothing to do for m_bone_posrot
627 m_attachment_parent(NULL),
628 m_attachment_bone(""),
629 m_attacmhent_position(v3f(0,0,0)),
630 m_attachment_rotation(v3f(0,0,0)),
632 m_anim_num_frames(1),
633 m_anim_framelength(0.2),
635 m_reset_textures_timer(-1),
636 m_visuals_expired(false),
637 m_step_distance_counter(0),
642 ClientActiveObject::registerType(getType(), create);
645 void initialize(const std::string &data)
647 infostream<<"GenericCAO: Got init data"<<std::endl;
648 std::istringstream is(data, std::ios::binary);
650 u8 version = readU8(is);
653 errorstream<<"GenericCAO: Unsupported init data version"
657 m_name = deSerializeString(is);
658 m_is_player = readU8(is);
660 m_position = readV3F1000(is);
661 m_yaw = readF1000(is);
664 int num_messages = readU8(is);
665 for(int i=0; i<num_messages; i++){
666 std::string message = deSerializeLongString(is);
667 processMessage(message);
670 pos_translator.init(m_position);
674 Player *player = m_env->getPlayer(m_name.c_str());
675 if(player && player->isLocal()){
676 m_is_local_player = true;
685 static ClientActiveObject* create(IGameDef *gamedef, ClientEnvironment *env)
687 return new GenericCAO(gamedef, env);
692 return ACTIVEOBJECT_TYPE_GENERIC;
694 core::aabbox3d<f32>* getSelectionBox()
696 if(!m_prop.is_visible || !m_is_visible || m_is_local_player)
698 return &m_selection_box;
702 return pos_translator.vect_show;
705 scene::IMeshSceneNode *getMeshSceneNode()
710 scene::IAnimatedMeshSceneNode *getAnimatedMeshSceneNode()
712 return m_animated_meshnode;
715 scene::IBillboardSceneNode *getSpriteSceneNode()
727 return m_is_local_player;
730 void removeFromScene()
733 m_meshnode->remove();
736 if(m_animated_meshnode){
737 m_animated_meshnode->remove();
738 m_animated_meshnode = NULL;
741 m_spritenode->remove();
746 void addToScene(scene::ISceneManager *smgr, ITextureSource *tsrc,
752 if(m_meshnode != NULL || m_animated_meshnode != NULL || m_spritenode != NULL)
755 m_visuals_expired = false;
757 if(!m_prop.is_visible || m_is_local_player)
760 //video::IVideoDriver* driver = smgr->getVideoDriver();
762 if(m_prop.visual == "sprite"){
763 infostream<<"GenericCAO::addToScene(): single_sprite"<<std::endl;
764 m_spritenode = smgr->addBillboardSceneNode(
765 NULL, v2f(1, 1), v3f(0,0,0), -1);
766 m_spritenode->setMaterialTexture(0,
767 tsrc->getTextureRaw("unknown_block.png"));
768 m_spritenode->setMaterialFlag(video::EMF_LIGHTING, false);
769 m_spritenode->setMaterialFlag(video::EMF_BILINEAR_FILTER, false);
770 m_spritenode->setMaterialType(video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF);
771 m_spritenode->setMaterialFlag(video::EMF_FOG_ENABLE, true);
772 u8 li = m_last_light;
773 m_spritenode->setColor(video::SColor(255,li,li,li));
774 m_spritenode->setSize(m_prop.visual_size*BS);
776 const float txs = 1.0 / 1;
777 const float tys = 1.0 / 1;
778 setBillboardTextureMatrix(m_spritenode,
782 else if(m_prop.visual == "upright_sprite")
784 scene::SMesh *mesh = new scene::SMesh();
785 double dx = BS*m_prop.visual_size.X/2;
786 double dy = BS*m_prop.visual_size.Y/2;
788 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
789 u8 li = m_last_light;
790 video::SColor c(255,li,li,li);
791 video::S3DVertex vertices[4] =
793 video::S3DVertex(-dx,-dy,0, 0,0,0, c, 0,1),
794 video::S3DVertex(dx,-dy,0, 0,0,0, c, 1,1),
795 video::S3DVertex(dx,dy,0, 0,0,0, c, 1,0),
796 video::S3DVertex(-dx,dy,0, 0,0,0, c, 0,0),
798 u16 indices[] = {0,1,2,2,3,0};
799 buf->append(vertices, 4, indices, 6);
801 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
802 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
803 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
804 buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
806 mesh->addMeshBuffer(buf);
810 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
811 u8 li = m_last_light;
812 video::SColor c(255,li,li,li);
813 video::S3DVertex vertices[4] =
815 video::S3DVertex(dx,-dy,0, 0,0,0, c, 1,1),
816 video::S3DVertex(-dx,-dy,0, 0,0,0, c, 0,1),
817 video::S3DVertex(-dx,dy,0, 0,0,0, c, 0,0),
818 video::S3DVertex(dx,dy,0, 0,0,0, c, 1,0),
820 u16 indices[] = {0,1,2,2,3,0};
821 buf->append(vertices, 4, indices, 6);
823 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
824 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
825 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
826 buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
828 mesh->addMeshBuffer(buf);
831 m_meshnode = smgr->addMeshSceneNode(mesh, NULL);
833 // Set it to use the materials of the meshbuffers directly.
834 // This is needed for changing the texture in the future
835 m_meshnode->setReadOnlyMaterials(true);
837 else if(m_prop.visual == "cube"){
838 infostream<<"GenericCAO::addToScene(): cube"<<std::endl;
839 scene::IMesh *mesh = createCubeMesh(v3f(BS,BS,BS));
840 m_meshnode = smgr->addMeshSceneNode(mesh, NULL);
843 m_meshnode->setScale(v3f(m_prop.visual_size.X,
844 m_prop.visual_size.Y,
845 m_prop.visual_size.X));
846 u8 li = m_last_light;
847 setMeshColor(m_meshnode->getMesh(), video::SColor(255,li,li,li));
849 else if(m_prop.visual == "mesh"){
850 infostream<<"GenericCAO::addToScene(): mesh"<<std::endl;
851 scene::IAnimatedMesh *mesh = smgr->getMesh(m_prop.mesh.c_str());
854 m_animated_meshnode = smgr->addAnimatedMeshSceneNode(mesh, NULL);
855 m_animated_meshnode->setMD2Animation(scene::EMAT_STAND);
856 m_animated_meshnode->animateJoints(); // Needed for some animations
857 m_animated_meshnode->setScale(v3f(m_prop.visual_size.X,
858 m_prop.visual_size.Y,
859 m_prop.visual_size.X));
860 u8 li = m_last_light;
861 setMeshColor(m_animated_meshnode->getMesh(), video::SColor(255,li,li,li));
864 errorstream<<"GenericCAO::addToScene(): Could not load mesh "<<m_prop.mesh<<std::endl;
866 else if(m_prop.visual == "wielditem"){
867 infostream<<"GenericCAO::addToScene(): node"<<std::endl;
868 infostream<<"textures: "<<m_prop.textures.size()<<std::endl;
869 if(m_prop.textures.size() >= 1){
870 infostream<<"textures[0]: "<<m_prop.textures[0]<<std::endl;
871 IItemDefManager *idef = m_gamedef->idef();
872 ItemStack item(m_prop.textures[0], 1, 0, "", idef);
873 scene::IMesh *item_mesh = item.getDefinition(idef).wield_mesh;
875 // Copy mesh to be able to set unique vertex colors
876 scene::IMeshManipulator *manip =
877 irr->getVideoDriver()->getMeshManipulator();
878 scene::IMesh *mesh = manip->createMeshUniquePrimitives(item_mesh);
880 m_meshnode = smgr->addMeshSceneNode(mesh, NULL);
883 m_meshnode->setScale(v3f(m_prop.visual_size.X/2,
884 m_prop.visual_size.Y/2,
885 m_prop.visual_size.X/2));
886 u8 li = m_last_light;
887 setMeshColor(m_meshnode->getMesh(), video::SColor(255,li,li,li));
890 infostream<<"GenericCAO::addToScene(): \""<<m_prop.visual
891 <<"\" not supported"<<std::endl;
895 scene::ISceneNode *node = NULL;
898 else if(m_animated_meshnode)
899 node = m_animated_meshnode;
902 if(node && m_is_player && !m_is_local_player){
903 // Add a text node for showing the name
904 gui::IGUIEnvironment* gui = irr->getGUIEnvironment();
905 std::wstring wname = narrow_to_wide(m_name);
906 m_textnode = smgr->addTextSceneNode(gui->getBuiltInFont(),
907 wname.c_str(), video::SColor(255,255,255,255), node);
908 m_textnode->setPosition(v3f(0, BS*1.1, 0));
916 m_visuals_expired = true;
919 void updateLight(u8 light_at_pos)
921 // Objects attached to the local player should always be hidden
922 if(m_attachment_parent != NULL && m_attachment_parent->isLocalPlayer())
923 m_is_visible = false;
925 m_is_visible = (m_hp != 0);
926 u8 li = decode_light(light_at_pos);
928 if(li != m_last_light){
930 video::SColor color(255,li,li,li);
932 setMeshColor(m_meshnode->getMesh(), color);
933 m_meshnode->setVisible(m_is_visible);
935 if(m_animated_meshnode){
936 setMeshColor(m_animated_meshnode->getMesh(), color);
937 m_animated_meshnode->setVisible(m_is_visible);
940 m_spritenode->setColor(color);
941 m_spritenode->setVisible(m_is_visible);
946 v3s16 getLightPosition()
948 return floatToInt(m_position, BS);
953 if(m_attachment_parent != NULL)
957 m_meshnode->setPosition(pos_translator.vect_show);
958 v3f rot = m_meshnode->getRotation();
960 m_meshnode->setRotation(rot);
962 if(m_animated_meshnode){
963 m_animated_meshnode->setPosition(pos_translator.vect_show);
964 v3f rot = m_animated_meshnode->getRotation();
966 m_animated_meshnode->setRotation(rot);
969 m_spritenode->setPosition(pos_translator.vect_show);
973 void step(float dtime, ClientEnvironment *env)
975 v3f lastpos = pos_translator.vect_show;
977 if(m_visuals_expired && m_smgr && m_irr){
978 m_visuals_expired = false;
980 addToScene(m_smgr, m_gamedef->tsrc(), m_irr);
986 if(m_attachment_parent == NULL) // Attachments should be glued to their parent by Irrlicht
989 core::aabbox3d<f32> box = m_prop.collisionbox;
992 collisionMoveResult moveresult;
993 f32 pos_max_d = BS*0.125; // Distance per iteration
995 v3f p_pos = m_position;
996 v3f p_velocity = m_velocity;
997 v3f p_acceleration = m_acceleration;
998 IGameDef *gamedef = env->getGameDef();
999 moveresult = collisionMoveSimple(&env->getMap(), gamedef,
1000 pos_max_d, box, stepheight, dtime,
1001 p_pos, p_velocity, p_acceleration);
1004 m_velocity = p_velocity;
1005 m_acceleration = p_acceleration;
1007 bool is_end_position = moveresult.collides;
1008 pos_translator.update(m_position, is_end_position, dtime);
1009 pos_translator.translate(dtime);
1012 m_position += dtime * m_velocity + 0.5 * dtime * dtime * m_acceleration;
1013 m_velocity += dtime * m_acceleration;
1014 pos_translator.update(m_position, pos_translator.aim_is_end, pos_translator.anim_time);
1015 pos_translator.translate(dtime);
1019 float moved = lastpos.getDistanceFrom(pos_translator.vect_show);
1020 m_step_distance_counter += moved;
1021 if(m_step_distance_counter > 1.5*BS){
1022 m_step_distance_counter = 0;
1023 if(!m_is_local_player && m_prop.makes_footstep_sound){
1024 INodeDefManager *ndef = m_gamedef->ndef();
1025 v3s16 p = floatToInt(getPosition() + v3f(0,
1026 (m_prop.collisionbox.MinEdge.Y-0.5)*BS, 0), BS);
1027 MapNode n = m_env->getMap().getNodeNoEx(p);
1028 SimpleSoundSpec spec = ndef->get(n).sound_footstep;
1029 m_gamedef->sound()->playSoundAt(spec, false, getPosition());
1034 m_anim_timer += dtime;
1035 if(m_anim_timer >= m_anim_framelength){
1036 m_anim_timer -= m_anim_framelength;
1038 if(m_anim_frame >= m_anim_num_frames)
1044 if(m_reset_textures_timer >= 0){
1045 m_reset_textures_timer -= dtime;
1046 if(m_reset_textures_timer <= 0){
1047 m_reset_textures_timer = -1;
1051 if(fabs(m_prop.automatic_rotate) > 0.001){
1052 m_yaw += dtime * m_prop.automatic_rotate * 180 / M_PI;
1056 if(m_animated_meshnode)
1057 errorstream<<"Attachment position: "<<m_animated_meshnode->getPosition().X<<","<<m_animated_meshnode->getPosition().Y<<","<<m_animated_meshnode->getPosition().Z<<std::endl;
1060 void updateTexturePos()
1063 scene::ICameraSceneNode* camera =
1064 m_spritenode->getSceneManager()->getActiveCamera();
1067 v3f cam_to_entity = m_spritenode->getAbsolutePosition()
1068 - camera->getAbsolutePosition();
1069 cam_to_entity.normalize();
1071 int row = m_tx_basepos.Y;
1072 int col = m_tx_basepos.X;
1074 if(m_tx_select_horiz_by_yawpitch)
1076 if(cam_to_entity.Y > 0.75)
1078 else if(cam_to_entity.Y < -0.75)
1081 float mob_dir = atan2(cam_to_entity.Z, cam_to_entity.X) / M_PI * 180.;
1082 float dir = mob_dir - m_yaw;
1083 dir = wrapDegrees_180(dir);
1084 //infostream<<"id="<<m_id<<" dir="<<dir<<std::endl;
1085 if(fabs(wrapDegrees_180(dir - 0)) <= 45.1)
1087 else if(fabs(wrapDegrees_180(dir - 90)) <= 45.1)
1089 else if(fabs(wrapDegrees_180(dir - 180)) <= 45.1)
1091 else if(fabs(wrapDegrees_180(dir + 90)) <= 45.1)
1098 // Animation goes downwards
1099 row += m_anim_frame;
1101 float txs = m_tx_size.X;
1102 float tys = m_tx_size.Y;
1103 setBillboardTextureMatrix(m_spritenode,
1104 txs, tys, col, row);
1108 void updateTextures(const std::string &mod)
1110 ITextureSource *tsrc = m_gamedef->tsrc();
1114 if(m_prop.visual == "sprite")
1116 std::string texturestring = "unknown_block.png";
1117 if(m_prop.textures.size() >= 1)
1118 texturestring = m_prop.textures[0];
1119 texturestring += mod;
1120 m_spritenode->setMaterialTexture(0,
1121 tsrc->getTextureRaw(texturestring));
1123 // Does not work yet with the current lighting settings
1124 m_meshnode->getMaterial(0).AmbientColor = m_prop.colors[0];
1125 m_meshnode->getMaterial(0).DiffuseColor = m_prop.colors[0];
1128 if(m_animated_meshnode)
1130 if(m_prop.visual == "mesh")
1132 for (u32 i = 0; i < m_prop.textures.size(); ++i)
1134 std::string texturestring = m_prop.textures[i];
1135 if(texturestring == "")
1136 continue; // Empty texture string means don't modify that material
1137 texturestring += mod;
1138 video::ITexture* texture = tsrc->getTextureRaw(texturestring);
1141 errorstream<<"GenericCAO::updateTextures(): Could not load texture "<<texturestring<<std::endl;
1145 // Set material flags and texture
1146 m_animated_meshnode->setMaterialTexture(i, texture);
1147 video::SMaterial& material = m_animated_meshnode->getMaterial(i);
1148 material.setFlag(video::EMF_LIGHTING, false);
1149 material.setFlag(video::EMF_BILINEAR_FILTER, false);
1151 for (u32 i = 0; i < m_prop.colors.size(); ++i)
1153 // Does not work yet with the current lighting settings
1154 m_animated_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i];
1155 m_animated_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i];
1161 if(m_prop.visual == "cube")
1163 for (u32 i = 0; i < 6; ++i)
1165 std::string texturestring = "unknown_block.png";
1166 if(m_prop.textures.size() > i)
1167 texturestring = m_prop.textures[i];
1168 texturestring += mod;
1169 AtlasPointer ap = tsrc->getTexture(texturestring);
1171 // Get the tile texture and atlas transformation
1172 video::ITexture* atlas = ap.atlas;
1176 // Set material flags and texture
1177 video::SMaterial& material = m_meshnode->getMaterial(i);
1178 material.setFlag(video::EMF_LIGHTING, false);
1179 material.setFlag(video::EMF_BILINEAR_FILTER, false);
1180 material.setTexture(0, atlas);
1181 material.getTextureMatrix(0).setTextureTranslate(pos.X, pos.Y);
1182 material.getTextureMatrix(0).setTextureScale(size.X, size.Y);
1184 // Does not work yet with the current lighting settings
1185 m_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i];
1186 m_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i];
1189 else if(m_prop.visual == "upright_sprite")
1191 scene::IMesh *mesh = m_meshnode->getMesh();
1193 std::string tname = "unknown_object.png";
1194 if(m_prop.textures.size() >= 1)
1195 tname = m_prop.textures[0];
1197 scene::IMeshBuffer *buf = mesh->getMeshBuffer(0);
1198 buf->getMaterial().setTexture(0,
1199 tsrc->getTextureRaw(tname));
1201 // Does not work yet with the current lighting settings
1202 m_meshnode->getMaterial(0).AmbientColor = m_prop.colors[0];
1203 m_meshnode->getMaterial(0).DiffuseColor = m_prop.colors[0];
1206 std::string tname = "unknown_object.png";
1207 if(m_prop.textures.size() >= 2)
1208 tname = m_prop.textures[1];
1209 else if(m_prop.textures.size() >= 1)
1210 tname = m_prop.textures[0];
1212 scene::IMeshBuffer *buf = mesh->getMeshBuffer(1);
1213 buf->getMaterial().setTexture(0,
1214 tsrc->getTextureRaw(tname));
1216 // Does not work yet with the current lighting settings
1217 m_meshnode->getMaterial(1).AmbientColor = m_prop.colors[1];
1218 m_meshnode->getMaterial(1).DiffuseColor = m_prop.colors[1];
1224 void updateAnimations()
1226 if(!m_animated_meshnode)
1229 m_animated_meshnode->setFrameLoop((int)m_frames.X, (int)m_frames.Y);
1230 m_animated_meshnode->setAnimationSpeed(m_frame_speed);
1231 m_animated_meshnode->setTransitionTime(m_frame_blend);
1234 void updateBonePosRot()
1236 if(m_bone_posrot.size() > 0)
1238 m_animated_meshnode->setJointMode(irr::scene::EJUOR_CONTROL); // To write positions to the mesh on render
1239 for(std::map<std::string, core::vector2d<v3f> >::const_iterator ii = m_bone_posrot.begin(); ii != m_bone_posrot.end(); ++ii){
1240 std::string bone_name = (*ii).first;
1241 v3f bone_pos = (*ii).second.X;
1242 v3f bone_rot = (*ii).second.Y;
1243 irr::scene::IBoneSceneNode* bone = m_animated_meshnode->getJointNode(bone_name.c_str());
1244 bone->setPosition(bone_pos);
1245 bone->setRotation(bone_rot);
1250 void updateAttachments()
1252 // REMAINING ATTACHMENT ISSUES:
1253 // We get to this function when the object is an attachment that needs to
1254 // be attached to its parent. If a bone is set we attach it to that skeletal
1255 // bone, otherwise just to the object's origin. Attachments should not copy parent
1256 // position as that's laggy... instead the Irrlicht function(s) to attach should
1257 // be used. If the parent object is NULL that means this object should be detached.
1258 // This function is only called whenever a GENERIC_CMD_SET_ATTACHMENT message is received.
1260 // We already attach our entity on the server too (copy position). Reason we attach
1261 // to the client as well is first of all lag. The server sends the position
1262 // of the child separately than that of the parent, so even on localhost
1263 // you'd see the child lagging behind. Models are also client-side, so this is
1264 // needed to read bone data and attach to joints.
1267 // - m_attachment_parent is ClientActiveObject* for the parent entity.
1268 // - m_attachment_bone is std::string of the bone, "" means none.
1269 // - m_attachment_position is v3f and represents the position offset of the attachment.
1270 // - m_attachment_rotation is v3f and represents the rotation offset of the attachment.
1272 // Implementation information:
1273 // From what I know, we need to get the AnimatedMeshSceneNode of m_attachment_parent then
1274 // use parent_node->addChild(m_animated_meshnode) for position attachment. For skeletal
1275 // attachment I don't know yet. Same must be used to detach when a NULL parent is received.
1278 // http://irrlicht.sourceforge.net/forum/viewtopic.php?t=7514
1279 // http://www.irrlicht3d.org/wiki/index.php?n=Main.HowToUseTheNewAnimationSystem
1280 // http://gamedev.stackexchange.com/questions/27363/finding-the-endpoint-of-a-named-bone-in-irrlicht
1281 // Irrlicht documentation: http://irrlicht.sourceforge.net/docu/
1283 if (m_attachment_parent != NULL && !m_attachment_parent->isLocalPlayer())
1285 // REMAINING ATTACHMENT ISSUES:
1286 // The code below should cause the child to get attached, but for some reason it's not working
1287 // A debug print confirms both position and absolute position are set accordingly, but the object still shows at origin 0,0,0
1289 scene::IMeshSceneNode *parent_mesh = NULL;
1290 if(m_attachment_parent->getMeshSceneNode())
1291 parent_mesh = m_attachment_parent->getMeshSceneNode();
1292 scene::IAnimatedMeshSceneNode *parent_animated_mesh = NULL;
1293 if(m_attachment_parent->getAnimatedMeshSceneNode())
1294 parent_animated_mesh = m_attachment_parent->getAnimatedMeshSceneNode();
1295 scene::IBillboardSceneNode *parent_sprite = NULL;
1296 if(m_attachment_parent->getSpriteSceneNode())
1297 parent_sprite = m_attachment_parent->getSpriteSceneNode();
1299 scene::IBoneSceneNode *parent_bone = NULL;
1300 if(parent_animated_mesh && m_attachment_bone != "")
1301 parent_bone = parent_animated_mesh->getJointNode(m_attachment_bone.c_str());
1302 if(!parent_bone) // Should be false if the bone doesn't exist on the mesh
1305 // TODO: Perhaps use polymorphism here to save code duplication
1308 m_meshnode->setPosition(parent_bone->getPosition());
1309 m_meshnode->setRotation(parent_bone->getRotation());
1310 m_meshnode->updateAbsolutePosition();
1311 //m_meshnode->setParent(parent_bone);
1316 m_meshnode->setPosition(parent_mesh->getPosition());
1317 m_meshnode->setRotation(parent_mesh->getRotation());
1318 m_meshnode->updateAbsolutePosition();
1319 //m_meshnode->setParent(parent_mesh);
1321 else if(parent_animated_mesh){
1322 m_meshnode->setPosition(parent_animated_mesh->getPosition());
1323 m_meshnode->setRotation(parent_animated_mesh->getRotation());
1324 m_meshnode->updateAbsolutePosition();
1325 //m_meshnode->setParent(parent_animated_mesh);
1327 else if(parent_sprite){
1328 m_meshnode->setPosition(parent_sprite->getPosition());
1329 m_meshnode->setRotation(parent_sprite->getRotation());
1330 m_meshnode->updateAbsolutePosition();
1331 //m_meshnode->setParent(parent_sprite);
1335 if(m_animated_meshnode){
1337 m_animated_meshnode->setPosition(parent_bone->getPosition());
1338 m_animated_meshnode->setRotation(parent_bone->getRotation());
1339 m_animated_meshnode->updateAbsolutePosition();
1340 //m_animated_meshnode->setParent(parent_bone);
1345 m_animated_meshnode->setPosition(parent_mesh->getPosition());
1346 m_animated_meshnode->setRotation(parent_mesh->getRotation());
1347 m_animated_meshnode->updateAbsolutePosition();
1348 //m_animated_meshnode->setParent(parent_mesh);
1350 else if(parent_animated_mesh){
1351 m_animated_meshnode->setPosition(parent_animated_mesh->getPosition());
1352 m_animated_meshnode->setRotation(parent_animated_mesh->getRotation());
1353 m_animated_meshnode->updateAbsolutePosition();
1354 //m_animated_meshnode->setParent(parent_animated_mesh);
1356 else if(parent_sprite){
1357 m_animated_meshnode->setPosition(parent_sprite->getPosition());
1358 m_animated_meshnode->setRotation(parent_sprite->getRotation());
1359 m_animated_meshnode->updateAbsolutePosition();
1360 //m_animated_meshnode->setParent(parent_sprite);
1366 m_spritenode->setPosition(parent_bone->getPosition());
1367 m_spritenode->setRotation(parent_bone->getRotation());
1368 m_spritenode->updateAbsolutePosition();
1369 //m_spritenode->setParent(parent_bone);
1374 m_spritenode->setPosition(parent_mesh->getPosition());
1375 m_spritenode->setRotation(parent_mesh->getRotation());
1376 m_spritenode->updateAbsolutePosition();
1377 //m_spritenode->setParent(parent_mesh);
1379 else if(parent_animated_mesh){
1380 m_spritenode->setPosition(parent_animated_mesh->getPosition());
1381 m_spritenode->setRotation(parent_animated_mesh->getRotation());
1382 m_spritenode->updateAbsolutePosition();
1383 //m_spritenode->setParent(parent_animated_mesh);
1385 else if(parent_sprite){
1386 m_spritenode->setPosition(parent_sprite->getPosition());
1387 m_spritenode->setRotation(parent_sprite->getRotation());
1388 m_spritenode->updateAbsolutePosition();
1389 //m_spritenode->setParent(parent_sprite);
1396 void processMessage(const std::string &data)
1398 //infostream<<"GenericCAO: Got message"<<std::endl;
1399 std::istringstream is(data, std::ios::binary);
1401 u8 cmd = readU8(is);
1402 if(cmd == GENERIC_CMD_SET_PROPERTIES)
1404 m_prop = gob_read_set_properties(is);
1406 m_selection_box = m_prop.collisionbox;
1407 m_selection_box.MinEdge *= BS;
1408 m_selection_box.MaxEdge *= BS;
1410 m_tx_size.X = 1.0 / m_prop.spritediv.X;
1411 m_tx_size.Y = 1.0 / m_prop.spritediv.Y;
1413 if(!m_initial_tx_basepos_set){
1414 m_initial_tx_basepos_set = true;
1415 m_tx_basepos = m_prop.initial_sprite_basepos;
1420 else if(cmd == GENERIC_CMD_UPDATE_POSITION)
1422 // Not sent by the server if the object is an attachment
1424 m_position = readV3F1000(is);
1425 m_velocity = readV3F1000(is);
1426 m_acceleration = readV3F1000(is);
1427 if(fabs(m_prop.automatic_rotate) < 0.001)
1428 m_yaw = readF1000(is);
1429 bool do_interpolate = readU8(is);
1430 bool is_end_position = readU8(is);
1431 float update_interval = readF1000(is);
1433 // Place us a bit higher if we're physical, to not sink into
1434 // the ground due to sucky collision detection...
1436 m_position += v3f(0,0.002,0);
1439 if(!m_prop.physical)
1440 pos_translator.update(m_position, is_end_position, update_interval);
1442 pos_translator.init(m_position);
1446 else if(cmd == GENERIC_CMD_SET_TEXTURE_MOD)
1448 std::string mod = deSerializeString(is);
1449 updateTextures(mod);
1451 else if(cmd == GENERIC_CMD_SET_SPRITE)
1453 v2s16 p = readV2S16(is);
1454 int num_frames = readU16(is);
1455 float framelength = readF1000(is);
1456 bool select_horiz_by_yawpitch = readU8(is);
1459 m_anim_num_frames = num_frames;
1460 m_anim_framelength = framelength;
1461 m_tx_select_horiz_by_yawpitch = select_horiz_by_yawpitch;
1465 else if(cmd == GENERIC_CMD_SET_ANIMATIONS)
1467 m_frames = readV2F1000(is);
1468 m_frame_speed = readF1000(is);
1469 m_frame_blend = readF1000(is);
1474 else if(cmd == GENERIC_CMD_SET_BONE_POSROT)
1476 std::string bone = deSerializeString(is);
1477 v3f position = readV3F1000(is);
1478 v3f rotation = readV3F1000(is);
1479 m_bone_posrot[bone] = core::vector2d<v3f>(position, rotation);
1484 else if(cmd == GENERIC_CMD_SET_ATTACHMENT)
1486 int parent_id = readS16(is);
1487 ClientActiveObject *obj = m_env->getActiveObject(parent_id);
1488 if(!parent_id || !obj)
1490 m_attachment_parent = obj;
1491 m_attachment_bone = deSerializeString(is);
1492 m_attacmhent_position = readV3F1000(is);
1493 m_attachment_rotation = readV3F1000(is);
1495 updateAttachments();
1497 else if(cmd == GENERIC_CMD_PUNCHED)
1499 /*s16 damage =*/ readS16(is);
1500 s16 result_hp = readS16(is);
1504 else if(cmd == GENERIC_CMD_UPDATE_ARMOR_GROUPS)
1506 m_armor_groups.clear();
1507 int armor_groups_size = readU16(is);
1508 for(int i=0; i<armor_groups_size; i++){
1509 std::string name = deSerializeString(is);
1510 int rating = readS16(is);
1511 m_armor_groups[name] = rating;
1516 bool directReportPunch(v3f dir, const ItemStack *punchitem=NULL,
1517 float time_from_last_punch=1000000)
1520 const ToolCapabilities *toolcap =
1521 &punchitem->getToolCapabilities(m_gamedef->idef());
1522 PunchDamageResult result = getPunchDamage(
1526 time_from_last_punch);
1528 if(result.did_punch && result.damage != 0)
1530 if(result.damage < m_hp){
1531 m_hp -= result.damage;
1534 // TODO: Execute defined fast response
1535 // As there is no definition, make a smoke puff
1536 ClientSimpleObject *simple = createSmokePuff(
1537 m_smgr, m_env, m_position,
1538 m_prop.visual_size * BS);
1539 m_env->addSimpleObject(simple);
1541 // TODO: Execute defined fast response
1542 // Flashing shall suffice as there is no definition
1543 m_reset_textures_timer = 0.05;
1544 if(result.damage >= 2)
1545 m_reset_textures_timer += 0.05 * result.damage;
1546 updateTextures("^[brighten");
1552 std::string debugInfoText()
1554 std::ostringstream os(std::ios::binary);
1555 os<<"GenericCAO hp="<<m_hp<<"\n";
1557 for(ItemGroupList::const_iterator i = m_armor_groups.begin();
1558 i != m_armor_groups.end(); i++){
1559 os<<i->first<<"="<<i->second<<", ";
1567 GenericCAO proto_GenericCAO(NULL, NULL);