]> git.lizzy.rs Git - dragonfireclient.git/blob - src/content_cao.cpp
Smoothed yaw rotation for objects (#6825)
[dragonfireclient.git] / src / content_cao.cpp
1 /*
2 Minetest
3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
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.
9
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.
14
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.
18 */
19
20 #include <ICameraSceneNode.h>
21 #include <ITextSceneNode.h>
22 #include <IBillboardSceneNode.h>
23 #include <IMeshManipulator.h>
24 #include <IAnimatedMeshSceneNode.h>
25 #include "content_cao.h"
26 #include "util/numeric.h" // For IntervalLimiter
27 #include "util/serialize.h"
28 #include "util/basic_macros.h"
29 #include "client/sound.h"
30 #include "client/tile.h"
31 #include "environment.h"
32 #include "collision.h"
33 #include "settings.h"
34 #include "serialization.h" // For decompressZlib
35 #include "clientobject.h"
36 #include "mesh.h"
37 #include "itemdef.h"
38 #include "tool.h"
39 #include "content_cso.h"
40 #include "sound.h"
41 #include "nodedef.h"
42 #include "localplayer.h"
43 #include "map.h"
44 #include "camera.h" // CameraModes
45 #include "client.h"
46 #include "wieldmesh.h"
47 #include <algorithm>
48 #include <cmath>
49 #include "client/renderingengine.h"
50
51 class Settings;
52 struct ToolCapabilities;
53
54 std::unordered_map<u16, ClientActiveObject::Factory> ClientActiveObject::m_types;
55
56 template<typename T>
57 void SmoothTranslator<T>::init(T current)
58 {
59         val_old = current;
60         val_current = current;
61         val_target = current;
62         anim_time = 0;
63         anim_time_counter = 0;
64         aim_is_end = true;
65 }
66
67 template<typename T>
68 void SmoothTranslator<T>::update(T new_target, bool is_end_position, float update_interval)
69 {
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;
75         } else {
76                 if (anim_time < 0.001 || anim_time > 1.0)
77                         anim_time = anim_time_counter;
78                 else
79                         anim_time = anim_time * 0.9 + anim_time_counter * 0.1;
80         }
81         anim_time_counter = 0;
82 }
83
84 template<typename T>
85 void SmoothTranslator<T>::translate(f32 dtime)
86 {
87         anim_time_counter = anim_time_counter + dtime;
88         T val_diff = val_target - val_old;
89         f32 moveratio = 1.0;
90         if (anim_time > 0.001)
91                 moveratio = anim_time_counter / anim_time;
92         f32 move_end = aim_is_end ? 1.0 : 1.5;
93
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;
97 }
98
99 void SmoothTranslatorWrapped::translate(f32 dtime)
100 {
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;
105
106         f32 moveratio = 1.0;
107         if (anim_time > 0.001)
108                 moveratio = anim_time_counter / anim_time;
109         f32 move_end = aim_is_end ? 1.0 : 1.5;
110
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);
115 }
116
117 /*
118         Other stuff
119 */
120
121 static void setBillboardTextureMatrix(scene::IBillboardSceneNode *bill,
122                 float txs, float tys, int col, int row)
123 {
124         video::SMaterial& material = bill->getMaterial(0);
125         core::matrix4& matrix = material.getTextureMatrix(0);
126         matrix.setTextureTranslate(txs*col, tys*row);
127         matrix.setTextureScale(txs, tys);
128 }
129
130 /*
131         TestCAO
132 */
133
134 class TestCAO : public ClientActiveObject
135 {
136 public:
137         TestCAO(Client *client, ClientEnvironment *env);
138         virtual ~TestCAO() = default;
139
140         ActiveObjectType getType() const
141         {
142                 return ACTIVEOBJECT_TYPE_TEST;
143         }
144
145         static ClientActiveObject* create(Client *client, ClientEnvironment *env);
146
147         void addToScene(ITextureSource *tsrc);
148         void removeFromScene(bool permanent);
149         void updateLight(u8 light_at_pos);
150         v3s16 getLightPosition();
151         void updateNodePos();
152
153         void step(float dtime, ClientEnvironment *env);
154
155         void processMessage(const std::string &data);
156
157         bool getCollisionBox(aabb3f *toset) const { return false; }
158 private:
159         scene::IMeshSceneNode *m_node;
160         v3f m_position;
161 };
162
163 // Prototype
164 TestCAO proto_TestCAO(NULL, NULL);
165
166 TestCAO::TestCAO(Client *client, ClientEnvironment *env):
167         ClientActiveObject(0, client, env),
168         m_node(NULL),
169         m_position(v3f(0,10*BS,0))
170 {
171         ClientActiveObject::registerType(getType(), create);
172 }
173
174 ClientActiveObject* TestCAO::create(Client *client, ClientEnvironment *env)
175 {
176         return new TestCAO(client, env);
177 }
178
179 void TestCAO::addToScene(ITextureSource *tsrc)
180 {
181         if(m_node != NULL)
182                 return;
183
184         //video::IVideoDriver* driver = smgr->getVideoDriver();
185
186         scene::SMesh *mesh = new scene::SMesh();
187         scene::IMeshBuffer *buf = new scene::SMeshBuffer();
188         video::SColor c(255,255,255,255);
189         video::S3DVertex vertices[4] =
190         {
191                 video::S3DVertex(-BS/2,-BS/4,0, 0,0,0, c, 0,1),
192                 video::S3DVertex(BS/2,-BS/4,0, 0,0,0, c, 1,1),
193                 video::S3DVertex(BS/2,BS/4,0, 0,0,0, c, 1,0),
194                 video::S3DVertex(-BS/2,BS/4,0, 0,0,0, c, 0,0),
195         };
196         u16 indices[] = {0,1,2,2,3,0};
197         buf->append(vertices, 4, indices, 6);
198         // Set material
199         buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
200         buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false);
201         buf->getMaterial().setTexture(0, tsrc->getTextureForMesh("rat.png"));
202         buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
203         buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
204         buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
205         // Add to mesh
206         mesh->addMeshBuffer(buf);
207         buf->drop();
208         m_node = RenderingEngine::get_scene_manager()->addMeshSceneNode(mesh, NULL);
209         mesh->drop();
210         updateNodePos();
211 }
212
213 void TestCAO::removeFromScene(bool permanent)
214 {
215         if (!m_node)
216                 return;
217
218         m_node->remove();
219         m_node = NULL;
220 }
221
222 void TestCAO::updateLight(u8 light_at_pos)
223 {
224 }
225
226 v3s16 TestCAO::getLightPosition()
227 {
228         return floatToInt(m_position, BS);
229 }
230
231 void TestCAO::updateNodePos()
232 {
233         if (!m_node)
234                 return;
235
236         m_node->setPosition(m_position);
237         //m_node->setRotation(v3f(0, 45, 0));
238 }
239
240 void TestCAO::step(float dtime, ClientEnvironment *env)
241 {
242         if(m_node)
243         {
244                 v3f rot = m_node->getRotation();
245                 //infostream<<"dtime="<<dtime<<", rot.Y="<<rot.Y<<std::endl;
246                 rot.Y += dtime * 180;
247                 m_node->setRotation(rot);
248         }
249 }
250
251 void TestCAO::processMessage(const std::string &data)
252 {
253         infostream<<"TestCAO: Got data: "<<data<<std::endl;
254         std::istringstream is(data, std::ios::binary);
255         u16 cmd;
256         is>>cmd;
257         if(cmd == 0)
258         {
259                 v3f newpos;
260                 is>>newpos.X;
261                 is>>newpos.Y;
262                 is>>newpos.Z;
263                 m_position = newpos;
264                 updateNodePos();
265         }
266 }
267
268 /*
269         GenericCAO
270 */
271
272 #include "genericobject.h"
273
274 GenericCAO::GenericCAO(Client *client, ClientEnvironment *env):
275                 ClientActiveObject(0, client, env)
276 {
277         if (client == NULL) {
278                 ClientActiveObject::registerType(getType(), create);
279         } else {
280                 m_client = client;
281         }
282 }
283
284 bool GenericCAO::getCollisionBox(aabb3f *toset) const
285 {
286         if (m_prop.physical)
287         {
288                 //update collision box
289                 toset->MinEdge = m_prop.collisionbox.MinEdge * BS;
290                 toset->MaxEdge = m_prop.collisionbox.MaxEdge * BS;
291
292                 toset->MinEdge += m_position;
293                 toset->MaxEdge += m_position;
294
295                 return true;
296         }
297
298         return false;
299 }
300
301 bool GenericCAO::collideWithObjects() const
302 {
303         return m_prop.collideWithObjects;
304 }
305
306 void GenericCAO::initialize(const std::string &data)
307 {
308         infostream<<"GenericCAO: Got init data"<<std::endl;
309         processInitData(data);
310
311         if (m_is_player) {
312                 // Check if it's the current player
313                 LocalPlayer *player = m_env->getLocalPlayer();
314                 if (player && strcmp(player->getName(), m_name.c_str()) == 0) {
315                         m_is_local_player = true;
316                         m_is_visible = false;
317                         player->setCAO(this);
318                 }
319         }
320 }
321
322 void GenericCAO::processInitData(const std::string &data)
323 {
324         std::istringstream is(data, std::ios::binary);
325         int num_messages = 0;
326         // version
327         u8 version = readU8(is);
328         // check version
329         if (version == 1) { // In PROTOCOL_VERSION 14
330                 m_name = deSerializeString(is);
331                 m_is_player = readU8(is);
332                 m_id = readU16(is);
333                 m_position = readV3F1000(is);
334                 m_yaw = readF1000(is);
335                 m_hp = readS16(is);
336                 num_messages = readU8(is);
337         } else {
338                 errorstream<<"GenericCAO: Unsupported init data version"
339                                 <<std::endl;
340                 return;
341         }
342
343         for (int i = 0; i < num_messages; i++) {
344                 std::string message = deSerializeLongString(is);
345                 processMessage(message);
346         }
347
348         m_yaw = wrapDegrees_0_360(m_yaw);
349         pos_translator.init(m_position);
350         yaw_translator.init(m_yaw);
351         updateNodePos();
352 }
353
354 GenericCAO::~GenericCAO()
355 {
356         removeFromScene(true);
357 }
358
359 bool GenericCAO::getSelectionBox(aabb3f *toset) const
360 {
361         if (!m_prop.is_visible || !m_is_visible || m_is_local_player
362                         || !m_prop.pointable) {
363                 return false;
364         }
365         *toset = m_selection_box;
366         return true;
367 }
368
369 v3f GenericCAO::getPosition()
370 {
371         if (getParent() != NULL) {
372                 scene::ISceneNode *node = getSceneNode();
373                 if (node)
374                         return node->getAbsolutePosition();
375
376                 return m_position;
377         }
378         return pos_translator.val_current;
379 }
380
381 const bool GenericCAO::isImmortal()
382 {
383         return itemgroup_get(getGroups(), "immortal");
384 }
385
386 scene::ISceneNode* GenericCAO::getSceneNode()
387 {
388         if (m_meshnode) {
389                 return m_meshnode;
390         }
391
392         if (m_animated_meshnode) {
393                 return m_animated_meshnode;
394         }
395
396         if (m_wield_meshnode) {
397                 return m_wield_meshnode;
398         }
399
400         if (m_spritenode) {
401                 return m_spritenode;
402         }
403         return NULL;
404 }
405
406 scene::IAnimatedMeshSceneNode* GenericCAO::getAnimatedMeshSceneNode()
407 {
408         return m_animated_meshnode;
409 }
410
411 void GenericCAO::setChildrenVisible(bool toset)
412 {
413         for (u16 cao_id : m_children) {
414                 GenericCAO *obj = m_env->getGenericCAO(cao_id);
415                 if (obj) {
416                         obj->setVisible(toset);
417                 }
418         }
419 }
420
421 void GenericCAO::setAttachments()
422 {
423         updateAttachments();
424 }
425
426 ClientActiveObject* GenericCAO::getParent() const
427 {
428         ClientActiveObject *obj = NULL;
429
430         u16 attached_id = m_env->attachement_parent_ids[getId()];
431
432         if ((attached_id != 0) &&
433                         (attached_id != getId())) {
434                 obj = m_env->getActiveObject(attached_id);
435         }
436         return obj;
437 }
438
439 void GenericCAO::removeFromScene(bool permanent)
440 {
441         // Should be true when removing the object permanently and false when refreshing (eg: updating visuals)
442         if((m_env != NULL) && (permanent))
443         {
444                 for (u16 ci : m_children) {
445                         if (m_env->attachement_parent_ids[ci] == getId()) {
446                                 m_env->attachement_parent_ids[ci] = 0;
447                         }
448                 }
449                 m_children.clear();
450
451                 m_env->attachement_parent_ids[getId()] = 0;
452
453                 LocalPlayer* player = m_env->getLocalPlayer();
454                 if (this == player->parent) {
455                         player->parent = NULL;
456                         player->isAttached = false;
457                 }
458         }
459
460         if (m_meshnode) {
461                 m_meshnode->remove();
462                 m_meshnode->drop();
463                 m_meshnode = NULL;
464         } else if (m_animated_meshnode) {
465                 m_animated_meshnode->remove();
466                 m_animated_meshnode->drop();
467                 m_animated_meshnode = NULL;
468         } else if (m_wield_meshnode) {
469                 m_wield_meshnode->remove();
470                 m_wield_meshnode->drop();
471                 m_wield_meshnode = NULL;
472         } else if (m_spritenode) {
473                 m_spritenode->remove();
474                 m_spritenode->drop();
475                 m_spritenode = NULL;
476         }
477
478         if (m_nametag) {
479                 m_client->getCamera()->removeNametag(m_nametag);
480                 m_nametag = NULL;
481         }
482 }
483
484 void GenericCAO::addToScene(ITextureSource *tsrc)
485 {
486         m_smgr = RenderingEngine::get_scene_manager();
487
488         if (getSceneNode() != NULL) {
489                 return;
490         }
491
492         m_visuals_expired = false;
493
494         if (!m_prop.is_visible) {
495                 return;
496         }
497
498         video::E_MATERIAL_TYPE material_type = (m_prop.use_texture_alpha) ?
499                 video::EMT_TRANSPARENT_ALPHA_CHANNEL : video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
500
501         if (m_prop.visual == "sprite") {
502                 infostream<<"GenericCAO::addToScene(): single_sprite"<<std::endl;
503                 m_spritenode = RenderingEngine::get_scene_manager()->addBillboardSceneNode(
504                                 NULL, v2f(1, 1), v3f(0,0,0), -1);
505                 m_spritenode->grab();
506                 m_spritenode->setMaterialTexture(0,
507                                 tsrc->getTextureForMesh("unknown_node.png"));
508                 m_spritenode->setMaterialFlag(video::EMF_LIGHTING, false);
509                 m_spritenode->setMaterialFlag(video::EMF_BILINEAR_FILTER, false);
510                 m_spritenode->setMaterialType(material_type);
511                 m_spritenode->setMaterialFlag(video::EMF_FOG_ENABLE, true);
512                 u8 li = m_last_light;
513                 m_spritenode->setColor(video::SColor(255,li,li,li));
514                 m_spritenode->setSize(m_prop.visual_size*BS);
515                 {
516                         const float txs = 1.0 / 1;
517                         const float tys = 1.0 / 1;
518                         setBillboardTextureMatrix(m_spritenode,
519                                         txs, tys, 0, 0);
520                 }
521         } else if (m_prop.visual == "upright_sprite") {
522                 scene::SMesh *mesh = new scene::SMesh();
523                 double dx = BS * m_prop.visual_size.X / 2;
524                 double dy = BS * m_prop.visual_size.Y / 2;
525                 u8 li = m_last_light;
526                 video::SColor c(255, li, li, li);
527
528                 { // Front
529                         scene::IMeshBuffer *buf = new scene::SMeshBuffer();
530                         video::S3DVertex vertices[4] = {
531                                 video::S3DVertex(-dx, -dy, 0, 0,0,0, c, 1,1),
532                                 video::S3DVertex( dx, -dy, 0, 0,0,0, c, 0,1),
533                                 video::S3DVertex( dx,  dy, 0, 0,0,0, c, 0,0),
534                                 video::S3DVertex(-dx,  dy, 0, 0,0,0, c, 1,0),
535                         };
536                         if (m_is_player) {
537                                 // Move minimal Y position to 0 (feet position)
538                                 for (video::S3DVertex &vertex : vertices)
539                                         vertex.Pos.Y += dy;
540                         }
541                         u16 indices[] = {0,1,2,2,3,0};
542                         buf->append(vertices, 4, indices, 6);
543                         // Set material
544                         buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
545                         buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
546                         buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
547                         buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
548                         // Add to mesh
549                         mesh->addMeshBuffer(buf);
550                         buf->drop();
551                 }
552                 { // Back
553                         scene::IMeshBuffer *buf = new scene::SMeshBuffer();
554                         video::S3DVertex vertices[4] = {
555                                 video::S3DVertex( dx,-dy, 0, 0,0,0, c, 1,1),
556                                 video::S3DVertex(-dx,-dy, 0, 0,0,0, c, 0,1),
557                                 video::S3DVertex(-dx, dy, 0, 0,0,0, c, 0,0),
558                                 video::S3DVertex( dx, dy, 0, 0,0,0, c, 1,0),
559                         };
560                         if (m_is_player) {
561                                 // Move minimal Y position to 0 (feet position)
562                                 for (video::S3DVertex &vertex : vertices)
563                                         vertex.Pos.Y += dy;
564                         }
565                         u16 indices[] = {0,1,2,2,3,0};
566                         buf->append(vertices, 4, indices, 6);
567                         // Set material
568                         buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
569                         buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
570                         buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
571                         buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
572                         // Add to mesh
573                         mesh->addMeshBuffer(buf);
574                         buf->drop();
575                 }
576                 m_meshnode = RenderingEngine::get_scene_manager()->addMeshSceneNode(mesh, NULL);
577                 m_meshnode->grab();
578                 mesh->drop();
579                 // Set it to use the materials of the meshbuffers directly.
580                 // This is needed for changing the texture in the future
581                 m_meshnode->setReadOnlyMaterials(true);
582         }
583         else if(m_prop.visual == "cube") {
584                 infostream<<"GenericCAO::addToScene(): cube"<<std::endl;
585                 scene::IMesh *mesh = createCubeMesh(v3f(BS,BS,BS));
586                 m_meshnode = RenderingEngine::get_scene_manager()->addMeshSceneNode(mesh, NULL);
587                 m_meshnode->grab();
588                 mesh->drop();
589
590                 m_meshnode->setScale(v3f(m_prop.visual_size.X,
591                                 m_prop.visual_size.Y,
592                                 m_prop.visual_size.X));
593                 u8 li = m_last_light;
594                 setMeshColor(m_meshnode->getMesh(), video::SColor(255,li,li,li));
595
596                 m_meshnode->setMaterialFlag(video::EMF_LIGHTING, false);
597                 m_meshnode->setMaterialFlag(video::EMF_BILINEAR_FILTER, false);
598                 m_meshnode->setMaterialType(material_type);
599                 m_meshnode->setMaterialFlag(video::EMF_FOG_ENABLE, true);
600         }
601         else if(m_prop.visual == "mesh") {
602                 infostream<<"GenericCAO::addToScene(): mesh"<<std::endl;
603                 scene::IAnimatedMesh *mesh = m_client->getMesh(m_prop.mesh, true);
604                 if(mesh)
605                 {
606                         m_animated_meshnode = RenderingEngine::get_scene_manager()->
607                                 addAnimatedMeshSceneNode(mesh, NULL);
608                         m_animated_meshnode->grab();
609                         mesh->drop(); // The scene node took hold of it
610                         m_animated_meshnode->animateJoints(); // Needed for some animations
611                         m_animated_meshnode->setScale(v3f(m_prop.visual_size.X,
612                                         m_prop.visual_size.Y,
613                                         m_prop.visual_size.X));
614                         u8 li = m_last_light;
615
616                         // set vertex colors to ensure alpha is set
617                         setMeshColor(m_animated_meshnode->getMesh(), video::SColor(255,li,li,li));
618
619                         setAnimatedMeshColor(m_animated_meshnode, video::SColor(255,li,li,li));
620
621                         m_animated_meshnode->setMaterialFlag(video::EMF_LIGHTING, true);
622                         m_animated_meshnode->setMaterialFlag(video::EMF_BILINEAR_FILTER, false);
623                         m_animated_meshnode->setMaterialType(material_type);
624                         m_animated_meshnode->setMaterialFlag(video::EMF_FOG_ENABLE, true);
625                         m_animated_meshnode->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
626                                 m_prop.backface_culling);
627                 }
628                 else
629                         errorstream<<"GenericCAO::addToScene(): Could not load mesh "<<m_prop.mesh<<std::endl;
630         } else if (m_prop.visual == "wielditem") {
631                 ItemStack item;
632                 infostream << "GenericCAO::addToScene(): wielditem" << std::endl;
633                 if (m_prop.wield_item.empty()) {
634                         // Old format, only textures are specified.
635                         infostream << "textures: " << m_prop.textures.size() << std::endl;
636                         if (!m_prop.textures.empty()) {
637                                 infostream << "textures[0]: " << m_prop.textures[0]
638                                         << std::endl;
639                                 IItemDefManager *idef = m_client->idef();
640                                 item = ItemStack(m_prop.textures[0], 1, 0, idef);
641                         }
642                 } else {
643                         infostream << "serialized form: " << m_prop.wield_item << std::endl;
644                         item.deSerialize(m_prop.wield_item, m_client->idef());
645                 }
646                 m_wield_meshnode = new WieldMeshSceneNode(
647                         RenderingEngine::get_scene_manager(), -1);
648                 m_wield_meshnode->setItem(item, m_client);
649
650                 m_wield_meshnode->setScale(
651                         v3f(m_prop.visual_size.X / 2, m_prop.visual_size.Y / 2,
652                                 m_prop.visual_size.X / 2));
653                 u8 li = m_last_light;
654                 m_wield_meshnode->setColor(video::SColor(255, li, li, li));
655         } else {
656                 infostream<<"GenericCAO::addToScene(): \""<<m_prop.visual
657                                 <<"\" not supported"<<std::endl;
658         }
659
660         /* don't update while punch texture modifier is active */
661         if (m_reset_textures_timer < 0)
662                 updateTextures(m_current_texture_modifier);
663
664         scene::ISceneNode *node = getSceneNode();
665         if (node && !m_prop.nametag.empty() && !m_is_local_player) {
666                 // Add nametag
667                 v3f pos;
668                 pos.Y = m_prop.selectionbox.MaxEdge.Y + 0.3f;
669                 m_nametag = m_client->getCamera()->addNametag(node,
670                         m_prop.nametag, m_prop.nametag_color,
671                         pos);
672         }
673
674         updateNodePos();
675         updateAnimation();
676         updateBonePosition();
677         updateAttachments();
678 }
679
680 void GenericCAO::updateLight(u8 light_at_pos)
681 {
682         // Don't update light of attached one
683         if (getParent() != NULL) {
684                 return;
685         }
686
687         updateLightNoCheck(light_at_pos);
688
689         // Update light of all children
690         for (u16 i : m_children) {
691                 ClientActiveObject *obj = m_env->getActiveObject(i);
692                 if (obj) {
693                         obj->updateLightNoCheck(light_at_pos);
694                 }
695         }
696 }
697
698 void GenericCAO::updateLightNoCheck(u8 light_at_pos)
699 {
700         if (m_glow < 0)
701                 return;
702
703         u8 li = decode_light(light_at_pos + m_glow);
704         if (li != m_last_light) {
705                 m_last_light = li;
706                 video::SColor color(255,li,li,li);
707                 if (m_meshnode) {
708                         setMeshColor(m_meshnode->getMesh(), color);
709                 } else if (m_animated_meshnode) {
710                         setAnimatedMeshColor(m_animated_meshnode, color);
711                 } else if (m_wield_meshnode) {
712                         m_wield_meshnode->setColor(color);
713                 } else if (m_spritenode) {
714                         m_spritenode->setColor(color);
715                 }
716         }
717 }
718
719 v3s16 GenericCAO::getLightPosition()
720 {
721         if (m_is_player)
722                 return floatToInt(m_position + v3f(0, 0.5 * BS, 0), BS);
723
724         return floatToInt(m_position, BS);
725 }
726
727 void GenericCAO::updateNodePos()
728 {
729         if (getParent() != NULL)
730                 return;
731
732         scene::ISceneNode *node = getSceneNode();
733
734         if (node) {
735                 v3s16 camera_offset = m_env->getCameraOffset();
736                 node->setPosition(pos_translator.val_current - intToFloat(camera_offset, BS));
737                 if (node != m_spritenode) { // rotate if not a sprite
738                         v3f rot = node->getRotation();
739                         rot.Y = m_is_local_player ? -m_yaw : -yaw_translator.val_current;
740                         node->setRotation(rot);
741                 }
742         }
743 }
744
745 void GenericCAO::step(float dtime, ClientEnvironment *env)
746 {
747         // Handel model of local player instantly to prevent lags
748         if (m_is_local_player) {
749                 LocalPlayer *player = m_env->getLocalPlayer();
750                 if (m_is_visible) {
751                         int old_anim = player->last_animation;
752                         float old_anim_speed = player->last_animation_speed;
753                         m_position = player->getPosition();
754                         m_yaw = wrapDegrees_0_360(player->getYaw());
755                         m_velocity = v3f(0,0,0);
756                         m_acceleration = v3f(0,0,0);
757                         pos_translator.val_current = m_position;
758                         yaw_translator.val_current = m_yaw;
759                         const PlayerControl &controls = player->getPlayerControl();
760
761                         bool walking = false;
762                         if (controls.up || controls.down || controls.left || controls.right ||
763                                         controls.forw_move_joystick_axis != 0.f ||
764                                         controls.sidew_move_joystick_axis != 0.f)
765                                 walking = true;
766
767                         f32 new_speed = player->local_animation_speed;
768                         v2s32 new_anim = v2s32(0,0);
769                         bool allow_update = false;
770
771                         // increase speed if using fast or flying fast
772                         if((g_settings->getBool("fast_move") &&
773                                         m_client->checkLocalPrivilege("fast")) &&
774                                         (controls.aux1 ||
775                                         (!player->touching_ground &&
776                                         g_settings->getBool("free_move") &&
777                                         m_client->checkLocalPrivilege("fly"))))
778                                         new_speed *= 1.5;
779                         // slowdown speed if sneeking
780                         if (controls.sneak && walking)
781                                 new_speed /= 2;
782
783                         if (walking && (controls.LMB || controls.RMB)) {
784                                 new_anim = player->local_animations[3];
785                                 player->last_animation = WD_ANIM;
786                         } else if(walking) {
787                                 new_anim = player->local_animations[1];
788                                 player->last_animation = WALK_ANIM;
789                         } else if(controls.LMB || controls.RMB) {
790                                 new_anim = player->local_animations[2];
791                                 player->last_animation = DIG_ANIM;
792                         }
793
794                         // Apply animations if input detected and not attached
795                         // or set idle animation
796                         if ((new_anim.X + new_anim.Y) > 0 && !player->isAttached) {
797                                 allow_update = true;
798                                 m_animation_range = new_anim;
799                                 m_animation_speed = new_speed;
800                                 player->last_animation_speed = m_animation_speed;
801                         } else {
802                                 player->last_animation = NO_ANIM;
803
804                                 if (old_anim != NO_ANIM) {
805                                         m_animation_range = player->local_animations[0];
806                                         updateAnimation();
807                                 }
808                         }
809
810                         // Update local player animations
811                         if ((player->last_animation != old_anim ||
812                                 m_animation_speed != old_anim_speed) &&
813                                 player->last_animation != NO_ANIM && allow_update)
814                                         updateAnimation();
815
816                 }
817         }
818
819         if (m_visuals_expired && m_smgr) {
820                 m_visuals_expired = false;
821
822                 // Attachments, part 1: All attached objects must be unparented first,
823                 // or Irrlicht causes a segmentation fault
824                 for (auto ci = m_children.begin(); ci != m_children.end();) {
825                         if (m_env->attachement_parent_ids[*ci] != getId()) {
826                                 ci = m_children.erase(ci);
827                                 continue;
828                         }
829                         ClientActiveObject *obj = m_env->getActiveObject(*ci);
830                         if (obj) {
831                                 scene::ISceneNode *child_node = obj->getSceneNode();
832                                 if (child_node)
833                                         child_node->setParent(m_smgr->getRootSceneNode());
834                         }
835                         ++ci;
836                 }
837
838                 removeFromScene(false);
839                 addToScene(m_client->tsrc());
840
841                 // Attachments, part 2: Now that the parent has been refreshed, put its attachments back
842                 for (u16 cao_id : m_children) {
843                         // Get the object of the child
844                         ClientActiveObject *obj = m_env->getActiveObject(cao_id);
845                         if (obj)
846                                 obj->setAttachments();
847                 }
848         }
849
850         // Make sure m_is_visible is always applied
851         scene::ISceneNode *node = getSceneNode();
852         if (node)
853                 node->setVisible(m_is_visible);
854
855         if(getParent() != NULL) // Attachments should be glued to their parent by Irrlicht
856         {
857                 // Set these for later
858                 m_position = getPosition();
859                 m_velocity = v3f(0,0,0);
860                 m_acceleration = v3f(0,0,0);
861                 pos_translator.val_current = m_position;
862
863                 if(m_is_local_player) // Update local player attachment position
864                 {
865                         LocalPlayer *player = m_env->getLocalPlayer();
866                         player->overridePosition = getParent()->getPosition();
867                         m_env->getLocalPlayer()->parent = getParent();
868                 }
869         } else {
870                 yaw_translator.translate(dtime);
871                 v3f lastpos = pos_translator.val_current;
872
873                 if(m_prop.physical)
874                 {
875                         aabb3f box = m_prop.collisionbox;
876                         box.MinEdge *= BS;
877                         box.MaxEdge *= BS;
878                         collisionMoveResult moveresult;
879                         f32 pos_max_d = BS*0.125; // Distance per iteration
880                         v3f p_pos = m_position;
881                         v3f p_velocity = m_velocity;
882                         moveresult = collisionMoveSimple(env,env->getGameDef(),
883                                         pos_max_d, box, m_prop.stepheight, dtime,
884                                         &p_pos, &p_velocity, m_acceleration,
885                                         this, m_prop.collideWithObjects);
886                         // Apply results
887                         m_position = p_pos;
888                         m_velocity = p_velocity;
889
890                         bool is_end_position = moveresult.collides;
891                         pos_translator.update(m_position, is_end_position, dtime);
892                         pos_translator.translate(dtime);
893                         updateNodePos();
894                 } else {
895                         m_position += dtime * m_velocity + 0.5 * dtime * dtime * m_acceleration;
896                         m_velocity += dtime * m_acceleration;
897                         pos_translator.update(m_position, pos_translator.aim_is_end,
898                                         pos_translator.anim_time);
899                         pos_translator.translate(dtime);
900                         updateNodePos();
901                 }
902
903                 float moved = lastpos.getDistanceFrom(pos_translator.val_current);
904                 m_step_distance_counter += moved;
905                 if (m_step_distance_counter > 1.5f * BS) {
906                         m_step_distance_counter = 0.0f;
907                         if (!m_is_local_player && m_prop.makes_footstep_sound) {
908                                 const NodeDefManager *ndef = m_client->ndef();
909                                 v3s16 p = floatToInt(getPosition() +
910                                         v3f(0.0f, (m_prop.collisionbox.MinEdge.Y - 0.5f) * BS, 0.0f), BS);
911                                 MapNode n = m_env->getMap().getNodeNoEx(p);
912                                 SimpleSoundSpec spec = ndef->get(n).sound_footstep;
913                                 // Reduce footstep gain, as non-local-player footsteps are
914                                 // somehow louder.
915                                 spec.gain *= 0.6f;
916                                 m_client->sound()->playSoundAt(spec, false, getPosition());
917                         }
918                 }
919         }
920
921         m_anim_timer += dtime;
922         if(m_anim_timer >= m_anim_framelength)
923         {
924                 m_anim_timer -= m_anim_framelength;
925                 m_anim_frame++;
926                 if(m_anim_frame >= m_anim_num_frames)
927                         m_anim_frame = 0;
928         }
929
930         updateTexturePos();
931
932         if(m_reset_textures_timer >= 0)
933         {
934                 m_reset_textures_timer -= dtime;
935                 if(m_reset_textures_timer <= 0) {
936                         m_reset_textures_timer = -1;
937                         updateTextures(m_previous_texture_modifier);
938                 }
939         }
940         if (!getParent() && std::fabs(m_prop.automatic_rotate) > 0.001) {
941                 m_yaw += dtime * m_prop.automatic_rotate * 180 / M_PI;
942                 yaw_translator.val_current = m_yaw;
943                 updateNodePos();
944         }
945
946         if (!getParent() && m_prop.automatic_face_movement_dir &&
947                         (fabs(m_velocity.Z) > 0.001 || fabs(m_velocity.X) > 0.001)) {
948
949                 float target_yaw = atan2(m_velocity.Z, m_velocity.X) * 180 / M_PI
950                                 + m_prop.automatic_face_movement_dir_offset;
951                 float max_rotation_delta =
952                                 dtime * m_prop.automatic_face_movement_max_rotation_per_sec;
953
954                 wrappedApproachShortest(m_yaw, target_yaw, max_rotation_delta, 360.f);
955                 yaw_translator.val_current = m_yaw;
956                 updateNodePos();
957         }
958 }
959
960 void GenericCAO::updateTexturePos()
961 {
962         if(m_spritenode)
963         {
964                 scene::ICameraSceneNode* camera =
965                                 m_spritenode->getSceneManager()->getActiveCamera();
966                 if(!camera)
967                         return;
968                 v3f cam_to_entity = m_spritenode->getAbsolutePosition()
969                                 - camera->getAbsolutePosition();
970                 cam_to_entity.normalize();
971
972                 int row = m_tx_basepos.Y;
973                 int col = m_tx_basepos.X;
974
975                 if (m_tx_select_horiz_by_yawpitch) {
976                         if (cam_to_entity.Y > 0.75)
977                                 col += 5;
978                         else if (cam_to_entity.Y < -0.75)
979                                 col += 4;
980                         else {
981                                 float mob_dir =
982                                                 atan2(cam_to_entity.Z, cam_to_entity.X) / M_PI * 180.;
983                                 float dir = mob_dir - m_yaw;
984                                 dir = wrapDegrees_180(dir);
985                                 if (std::fabs(wrapDegrees_180(dir - 0)) <= 45.1f)
986                                         col += 2;
987                                 else if(std::fabs(wrapDegrees_180(dir - 90)) <= 45.1f)
988                                         col += 3;
989                                 else if(std::fabs(wrapDegrees_180(dir - 180)) <= 45.1f)
990                                         col += 0;
991                                 else if(std::fabs(wrapDegrees_180(dir + 90)) <= 45.1f)
992                                         col += 1;
993                                 else
994                                         col += 4;
995                         }
996                 }
997
998                 // Animation goes downwards
999                 row += m_anim_frame;
1000
1001                 float txs = m_tx_size.X;
1002                 float tys = m_tx_size.Y;
1003                 setBillboardTextureMatrix(m_spritenode, txs, tys, col, row);
1004         }
1005 }
1006
1007 void GenericCAO::updateTextures(std::string mod)
1008 {
1009         ITextureSource *tsrc = m_client->tsrc();
1010
1011         bool use_trilinear_filter = g_settings->getBool("trilinear_filter");
1012         bool use_bilinear_filter = g_settings->getBool("bilinear_filter");
1013         bool use_anisotropic_filter = g_settings->getBool("anisotropic_filter");
1014
1015         m_previous_texture_modifier = m_current_texture_modifier;
1016         m_current_texture_modifier = mod;
1017         m_glow = m_prop.glow;
1018
1019         video::E_MATERIAL_TYPE material_type = (m_prop.use_texture_alpha) ?
1020                 video::EMT_TRANSPARENT_ALPHA_CHANNEL : video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
1021
1022         if (m_spritenode) {
1023                 if (m_prop.visual == "sprite") {
1024                         std::string texturestring = "unknown_node.png";
1025                         if (!m_prop.textures.empty())
1026                                 texturestring = m_prop.textures[0];
1027                         texturestring += mod;
1028                         m_spritenode->getMaterial(0).MaterialType = material_type;
1029                         m_spritenode->setMaterialTexture(0,
1030                                         tsrc->getTextureForMesh(texturestring));
1031
1032                         // This allows setting per-material colors. However, until a real lighting
1033                         // system is added, the code below will have no effect. Once MineTest
1034                         // has directional lighting, it should work automatically.
1035                         if (!m_prop.colors.empty()) {
1036                                 m_spritenode->getMaterial(0).AmbientColor = m_prop.colors[0];
1037                                 m_spritenode->getMaterial(0).DiffuseColor = m_prop.colors[0];
1038                                 m_spritenode->getMaterial(0).SpecularColor = m_prop.colors[0];
1039                         }
1040
1041                         m_spritenode->getMaterial(0).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1042                         m_spritenode->getMaterial(0).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1043                         m_spritenode->getMaterial(0).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1044                 }
1045         }
1046
1047         if (m_animated_meshnode) {
1048                 if (m_prop.visual == "mesh") {
1049                         for (u32 i = 0; i < m_prop.textures.size() &&
1050                                         i < m_animated_meshnode->getMaterialCount(); ++i) {
1051                                 std::string texturestring = m_prop.textures[i];
1052                                 if (texturestring.empty())
1053                                         continue; // Empty texture string means don't modify that material
1054                                 texturestring += mod;
1055                                 video::ITexture* texture = tsrc->getTextureForMesh(texturestring);
1056                                 if (!texture) {
1057                                         errorstream<<"GenericCAO::updateTextures(): Could not load texture "<<texturestring<<std::endl;
1058                                         continue;
1059                                 }
1060
1061                                 // Set material flags and texture
1062                                 video::SMaterial& material = m_animated_meshnode->getMaterial(i);
1063                                 material.MaterialType = material_type;
1064                                 material.TextureLayer[0].Texture = texture;
1065                                 material.setFlag(video::EMF_LIGHTING, true);
1066                                 material.setFlag(video::EMF_BILINEAR_FILTER, false);
1067                                 material.setFlag(video::EMF_BACK_FACE_CULLING, m_prop.backface_culling);
1068
1069                                 // don't filter low-res textures, makes them look blurry
1070                                 // player models have a res of 64
1071                                 const core::dimension2d<u32> &size = texture->getOriginalSize();
1072                                 const u32 res = std::min(size.Height, size.Width);
1073                                 use_trilinear_filter &= res > 64;
1074                                 use_bilinear_filter &= res > 64;
1075
1076                                 m_animated_meshnode->getMaterial(i)
1077                                                 .setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1078                                 m_animated_meshnode->getMaterial(i)
1079                                                 .setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1080                                 m_animated_meshnode->getMaterial(i)
1081                                                 .setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1082                         }
1083                         for (u32 i = 0; i < m_prop.colors.size() &&
1084                         i < m_animated_meshnode->getMaterialCount(); ++i)
1085                         {
1086                                 // This allows setting per-material colors. However, until a real lighting
1087                                 // system is added, the code below will have no effect. Once MineTest
1088                                 // has directional lighting, it should work automatically.
1089                                 m_animated_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i];
1090                                 m_animated_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i];
1091                                 m_animated_meshnode->getMaterial(i).SpecularColor = m_prop.colors[i];
1092                         }
1093                 }
1094         }
1095         if(m_meshnode)
1096         {
1097                 if(m_prop.visual == "cube")
1098                 {
1099                         for (u32 i = 0; i < 6; ++i)
1100                         {
1101                                 std::string texturestring = "unknown_node.png";
1102                                 if(m_prop.textures.size() > i)
1103                                         texturestring = m_prop.textures[i];
1104                                 texturestring += mod;
1105
1106
1107                                 // Set material flags and texture
1108                                 video::SMaterial& material = m_meshnode->getMaterial(i);
1109                                 material.MaterialType = material_type;
1110                                 material.setFlag(video::EMF_LIGHTING, false);
1111                                 material.setFlag(video::EMF_BILINEAR_FILTER, false);
1112                                 material.setTexture(0,
1113                                                 tsrc->getTextureForMesh(texturestring));
1114                                 material.getTextureMatrix(0).makeIdentity();
1115
1116                                 // This allows setting per-material colors. However, until a real lighting
1117                                 // system is added, the code below will have no effect. Once MineTest
1118                                 // has directional lighting, it should work automatically.
1119                                 if(m_prop.colors.size() > i)
1120                                 {
1121                                         m_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i];
1122                                         m_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i];
1123                                         m_meshnode->getMaterial(i).SpecularColor = m_prop.colors[i];
1124                                 }
1125
1126                                 m_meshnode->getMaterial(i).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1127                                 m_meshnode->getMaterial(i).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1128                                 m_meshnode->getMaterial(i).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1129                         }
1130                 } else if (m_prop.visual == "upright_sprite") {
1131                         scene::IMesh *mesh = m_meshnode->getMesh();
1132                         {
1133                                 std::string tname = "unknown_object.png";
1134                                 if (!m_prop.textures.empty())
1135                                         tname = m_prop.textures[0];
1136                                 tname += mod;
1137                                 scene::IMeshBuffer *buf = mesh->getMeshBuffer(0);
1138                                 buf->getMaterial().setTexture(0,
1139                                                 tsrc->getTextureForMesh(tname));
1140
1141                                 // This allows setting per-material colors. However, until a real lighting
1142                                 // system is added, the code below will have no effect. Once MineTest
1143                                 // has directional lighting, it should work automatically.
1144                                 if(!m_prop.colors.empty()) {
1145                                         buf->getMaterial().AmbientColor = m_prop.colors[0];
1146                                         buf->getMaterial().DiffuseColor = m_prop.colors[0];
1147                                         buf->getMaterial().SpecularColor = m_prop.colors[0];
1148                                 }
1149
1150                                 buf->getMaterial().setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1151                                 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1152                                 buf->getMaterial().setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1153                         }
1154                         {
1155                                 std::string tname = "unknown_object.png";
1156                                 if (m_prop.textures.size() >= 2)
1157                                         tname = m_prop.textures[1];
1158                                 else if (!m_prop.textures.empty())
1159                                         tname = m_prop.textures[0];
1160                                 tname += mod;
1161                                 scene::IMeshBuffer *buf = mesh->getMeshBuffer(1);
1162                                 buf->getMaterial().setTexture(0,
1163                                                 tsrc->getTextureForMesh(tname));
1164
1165                                 // This allows setting per-material colors. However, until a real lighting
1166                                 // system is added, the code below will have no effect. Once MineTest
1167                                 // has directional lighting, it should work automatically.
1168                                 if (m_prop.colors.size() >= 2) {
1169                                         buf->getMaterial().AmbientColor = m_prop.colors[1];
1170                                         buf->getMaterial().DiffuseColor = m_prop.colors[1];
1171                                         buf->getMaterial().SpecularColor = m_prop.colors[1];
1172                                         setMeshColor(mesh, m_prop.colors[1]);
1173                                 } else if (!m_prop.colors.empty()) {
1174                                         buf->getMaterial().AmbientColor = m_prop.colors[0];
1175                                         buf->getMaterial().DiffuseColor = m_prop.colors[0];
1176                                         buf->getMaterial().SpecularColor = m_prop.colors[0];
1177                                         setMeshColor(mesh, m_prop.colors[0]);
1178                                 }
1179
1180                                 buf->getMaterial().setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1181                                 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1182                                 buf->getMaterial().setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1183                         }
1184                 }
1185         }
1186 }
1187
1188 void GenericCAO::updateAnimation()
1189 {
1190         if (!m_animated_meshnode)
1191                 return;
1192
1193         if (m_animated_meshnode->getStartFrame() != m_animation_range.X ||
1194                 m_animated_meshnode->getEndFrame() != m_animation_range.Y)
1195                         m_animated_meshnode->setFrameLoop(m_animation_range.X, m_animation_range.Y);
1196         if (m_animated_meshnode->getAnimationSpeed() != m_animation_speed)
1197                 m_animated_meshnode->setAnimationSpeed(m_animation_speed);
1198         m_animated_meshnode->setTransitionTime(m_animation_blend);
1199 // Requires Irrlicht 1.8 or greater
1200 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR > 1
1201         if (m_animated_meshnode->getLoopMode() != m_animation_loop)
1202                 m_animated_meshnode->setLoopMode(m_animation_loop);
1203 #endif
1204 }
1205
1206 void GenericCAO::updateAnimationSpeed()
1207 {
1208         if (!m_animated_meshnode)
1209                 return;
1210
1211         m_animated_meshnode->setAnimationSpeed(m_animation_speed);
1212 }
1213
1214 void GenericCAO::updateBonePosition()
1215 {
1216         if (m_bone_position.empty() || !m_animated_meshnode)
1217                 return;
1218
1219         m_animated_meshnode->setJointMode(irr::scene::EJUOR_CONTROL); // To write positions to the mesh on render
1220         for(std::unordered_map<std::string, core::vector2d<v3f>>::const_iterator
1221                         ii = m_bone_position.begin(); ii != m_bone_position.end(); ++ii) {
1222                 std::string bone_name = (*ii).first;
1223                 v3f bone_pos = (*ii).second.X;
1224                 v3f bone_rot = (*ii).second.Y;
1225                 irr::scene::IBoneSceneNode* bone = m_animated_meshnode->getJointNode(bone_name.c_str());
1226                 if(bone)
1227                 {
1228                         bone->setPosition(bone_pos);
1229                         bone->setRotation(bone_rot);
1230                 }
1231         }
1232 }
1233
1234 void GenericCAO::updateAttachments()
1235 {
1236
1237         if (!getParent()) { // Detach or don't attach
1238                 scene::ISceneNode *node = getSceneNode();
1239                 if (node) {
1240                         v3f old_position = node->getAbsolutePosition();
1241                         v3f old_rotation = node->getRotation();
1242                         node->setParent(m_smgr->getRootSceneNode());
1243                         node->setPosition(old_position);
1244                         node->setRotation(old_rotation);
1245                         node->updateAbsolutePosition();
1246                 }
1247                 if (m_is_local_player) {
1248                         LocalPlayer *player = m_env->getLocalPlayer();
1249                         player->isAttached = false;
1250                 }
1251         }
1252         else // Attach
1253         {
1254                 scene::ISceneNode *my_node = getSceneNode();
1255
1256                 scene::ISceneNode *parent_node = getParent()->getSceneNode();
1257                 scene::IAnimatedMeshSceneNode *parent_animated_mesh_node =
1258                                 getParent()->getAnimatedMeshSceneNode();
1259                 if (parent_animated_mesh_node && !m_attachment_bone.empty()) {
1260                         parent_node = parent_animated_mesh_node->getJointNode(m_attachment_bone.c_str());
1261                 }
1262
1263                 if (my_node && parent_node) {
1264                         my_node->setParent(parent_node);
1265                         my_node->setPosition(m_attachment_position);
1266                         my_node->setRotation(m_attachment_rotation);
1267                         my_node->updateAbsolutePosition();
1268                 }
1269                 if (m_is_local_player) {
1270                         LocalPlayer *player = m_env->getLocalPlayer();
1271                         player->isAttached = true;
1272                 }
1273         }
1274 }
1275
1276 void GenericCAO::processMessage(const std::string &data)
1277 {
1278         //infostream<<"GenericCAO: Got message"<<std::endl;
1279         std::istringstream is(data, std::ios::binary);
1280         // command
1281         u8 cmd = readU8(is);
1282         if (cmd == GENERIC_CMD_SET_PROPERTIES) {
1283                 m_prop = gob_read_set_properties(is);
1284
1285                 m_selection_box = m_prop.selectionbox;
1286                 m_selection_box.MinEdge *= BS;
1287                 m_selection_box.MaxEdge *= BS;
1288
1289                 m_tx_size.X = 1.0 / m_prop.spritediv.X;
1290                 m_tx_size.Y = 1.0 / m_prop.spritediv.Y;
1291
1292                 if(!m_initial_tx_basepos_set){
1293                         m_initial_tx_basepos_set = true;
1294                         m_tx_basepos = m_prop.initial_sprite_basepos;
1295                 }
1296                 if (m_is_local_player) {
1297                         LocalPlayer *player = m_env->getLocalPlayer();
1298                         player->makes_footstep_sound = m_prop.makes_footstep_sound;
1299                         aabb3f collision_box = m_prop.collisionbox;
1300                         collision_box.MinEdge *= BS;
1301                         collision_box.MaxEdge *= BS;
1302                         player->setCollisionbox(collision_box);
1303                         player->setEyeHeight(m_prop.eye_height);
1304                         player->setZoomFOV(m_prop.zoom_fov);
1305                 }
1306
1307                 if ((m_is_player && !m_is_local_player) && m_prop.nametag.empty())
1308                         m_prop.nametag = m_name;
1309
1310                 expireVisuals();
1311         } else if (cmd == GENERIC_CMD_UPDATE_POSITION) {
1312                 // Not sent by the server if this object is an attachment.
1313                 // We might however get here if the server notices the object being detached before the client.
1314                 m_position = readV3F1000(is);
1315                 m_velocity = readV3F1000(is);
1316                 m_acceleration = readV3F1000(is);
1317                 if (std::fabs(m_prop.automatic_rotate) < 0.001f)
1318                         m_yaw = readF1000(is);
1319                 else
1320                         readF1000(is);
1321                 m_yaw = wrapDegrees_0_360(m_yaw);
1322                 bool do_interpolate = readU8(is);
1323                 bool is_end_position = readU8(is);
1324                 float update_interval = readF1000(is);
1325
1326                 // Place us a bit higher if we're physical, to not sink into
1327                 // the ground due to sucky collision detection...
1328                 if(m_prop.physical)
1329                         m_position += v3f(0,0.002,0);
1330
1331                 if(getParent() != NULL) // Just in case
1332                         return;
1333
1334                 if(do_interpolate)
1335                 {
1336                         if(!m_prop.physical)
1337                                 pos_translator.update(m_position, is_end_position, update_interval);
1338                 } else {
1339                         pos_translator.init(m_position);
1340                 }
1341                 yaw_translator.update(m_yaw, false, update_interval);
1342                 updateNodePos();
1343         } else if (cmd == GENERIC_CMD_SET_TEXTURE_MOD) {
1344                 std::string mod = deSerializeString(is);
1345
1346                 // immediatly reset a engine issued texture modifier if a mod sends a different one
1347                 if (m_reset_textures_timer > 0) {
1348                         m_reset_textures_timer = -1;
1349                         updateTextures(m_previous_texture_modifier);
1350                 }
1351                 updateTextures(mod);
1352         } else if (cmd == GENERIC_CMD_SET_SPRITE) {
1353                 v2s16 p = readV2S16(is);
1354                 int num_frames = readU16(is);
1355                 float framelength = readF1000(is);
1356                 bool select_horiz_by_yawpitch = readU8(is);
1357
1358                 m_tx_basepos = p;
1359                 m_anim_num_frames = num_frames;
1360                 m_anim_framelength = framelength;
1361                 m_tx_select_horiz_by_yawpitch = select_horiz_by_yawpitch;
1362
1363                 updateTexturePos();
1364         } else if (cmd == GENERIC_CMD_SET_PHYSICS_OVERRIDE) {
1365                 float override_speed = readF1000(is);
1366                 float override_jump = readF1000(is);
1367                 float override_gravity = readF1000(is);
1368                 // these are sent inverted so we get true when the server sends nothing
1369                 bool sneak = !readU8(is);
1370                 bool sneak_glitch = !readU8(is);
1371                 bool new_move = !readU8(is);
1372
1373
1374                 if(m_is_local_player)
1375                 {
1376                         LocalPlayer *player = m_env->getLocalPlayer();
1377                         player->physics_override_speed = override_speed;
1378                         player->physics_override_jump = override_jump;
1379                         player->physics_override_gravity = override_gravity;
1380                         player->physics_override_sneak = sneak;
1381                         player->physics_override_sneak_glitch = sneak_glitch;
1382                         player->physics_override_new_move = new_move;
1383                 }
1384         } else if (cmd == GENERIC_CMD_SET_ANIMATION) {
1385                 // TODO: change frames send as v2s32 value
1386                 v2f range = readV2F1000(is);
1387                 if (!m_is_local_player) {
1388                         m_animation_range = v2s32((s32)range.X, (s32)range.Y);
1389                         m_animation_speed = readF1000(is);
1390                         m_animation_blend = readF1000(is);
1391                         // these are sent inverted so we get true when the server sends nothing
1392                         m_animation_loop = !readU8(is);
1393                         updateAnimation();
1394                 } else {
1395                         LocalPlayer *player = m_env->getLocalPlayer();
1396                         if(player->last_animation == NO_ANIM)
1397                         {
1398                                 m_animation_range = v2s32((s32)range.X, (s32)range.Y);
1399                                 m_animation_speed = readF1000(is);
1400                                 m_animation_blend = readF1000(is);
1401                                 // these are sent inverted so we get true when the server sends nothing
1402                                 m_animation_loop = !readU8(is);
1403                         }
1404                         // update animation only if local animations present
1405                         // and received animation is unknown (except idle animation)
1406                         bool is_known = false;
1407                         for (int i = 1;i<4;i++)
1408                         {
1409                                 if(m_animation_range.Y == player->local_animations[i].Y)
1410                                         is_known = true;
1411                         }
1412                         if(!is_known ||
1413                                         (player->local_animations[1].Y + player->local_animations[2].Y < 1))
1414                         {
1415                                         updateAnimation();
1416                         }
1417                 }
1418         } else if (cmd == GENERIC_CMD_SET_ANIMATION_SPEED) {
1419                 m_animation_speed = readF1000(is);
1420                 updateAnimationSpeed();
1421         } else if (cmd == GENERIC_CMD_SET_BONE_POSITION) {
1422                 std::string bone = deSerializeString(is);
1423                 v3f position = readV3F1000(is);
1424                 v3f rotation = readV3F1000(is);
1425                 m_bone_position[bone] = core::vector2d<v3f>(position, rotation);
1426
1427                 updateBonePosition();
1428         } else if (cmd == GENERIC_CMD_ATTACH_TO) {
1429                 u16 parent_id = readS16(is);
1430                 u16 &old_parent_id = m_env->attachement_parent_ids[getId()];
1431                 if (parent_id != old_parent_id) {
1432                         if (GenericCAO *old_parent = m_env->getGenericCAO(old_parent_id)) {
1433                                 old_parent->m_children.erase(std::remove(
1434                                         m_children.begin(), m_children.end(),
1435                                         getId()), m_children.end());
1436                         }
1437                         if (GenericCAO *new_parent = m_env->getGenericCAO(parent_id))
1438                                 new_parent->m_children.push_back(getId());
1439
1440                         old_parent_id = parent_id;
1441                 }
1442
1443                 m_attachment_bone = deSerializeString(is);
1444                 m_attachment_position = readV3F1000(is);
1445                 m_attachment_rotation = readV3F1000(is);
1446
1447                 // localplayer itself can't be attached to localplayer
1448                 if (!m_is_local_player) {
1449                         m_attached_to_local = getParent() != NULL && getParent()->isLocalPlayer();
1450                         // Objects attached to the local player should be hidden by default
1451                         m_is_visible = !m_attached_to_local;
1452                 }
1453
1454                 updateAttachments();
1455         } else if (cmd == GENERIC_CMD_PUNCHED) {
1456                 /*s16 damage =*/ readS16(is);
1457                 s16 result_hp = readS16(is);
1458
1459                 // Use this instead of the send damage to not interfere with prediction
1460                 s16 damage = m_hp - result_hp;
1461
1462                 m_hp = result_hp;
1463
1464                 if (damage > 0)
1465                 {
1466                         if (m_hp <= 0)
1467                         {
1468                                 // TODO: Execute defined fast response
1469                                 // As there is no definition, make a smoke puff
1470                                 ClientSimpleObject *simple = createSmokePuff(
1471                                                 m_smgr, m_env, m_position,
1472                                                 m_prop.visual_size * BS);
1473                                 m_env->addSimpleObject(simple);
1474                         } else if (m_reset_textures_timer < 0) {
1475                                 // TODO: Execute defined fast response
1476                                 // Flashing shall suffice as there is no definition
1477                                 m_reset_textures_timer = 0.05;
1478                                 if(damage >= 2)
1479                                         m_reset_textures_timer += 0.05 * damage;
1480                                 updateTextures(m_current_texture_modifier + "^[brighten");
1481                         }
1482                 }
1483         } else if (cmd == GENERIC_CMD_UPDATE_ARMOR_GROUPS) {
1484                 m_armor_groups.clear();
1485                 int armor_groups_size = readU16(is);
1486                 for(int i=0; i<armor_groups_size; i++)
1487                 {
1488                         std::string name = deSerializeString(is);
1489                         int rating = readS16(is);
1490                         m_armor_groups[name] = rating;
1491                 }
1492         } else if (cmd == GENERIC_CMD_UPDATE_NAMETAG_ATTRIBUTES) {
1493                 // Deprecated, for backwards compatibility only.
1494                 readU8(is); // version
1495                 m_prop.nametag_color = readARGB8(is);
1496                 if (m_nametag != NULL) {
1497                         m_nametag->nametag_color = m_prop.nametag_color;
1498                         v3f pos;
1499                         pos.Y = m_prop.collisionbox.MaxEdge.Y + 0.3f;
1500                         m_nametag->nametag_pos = pos;
1501                 }
1502         } else if (cmd == GENERIC_CMD_SPAWN_INFANT) {
1503                 u16 child_id = readU16(is);
1504                 u8 type = readU8(is);
1505
1506                 if (GenericCAO *childobj = m_env->getGenericCAO(child_id)) {
1507                         childobj->processInitData(deSerializeLongString(is));
1508                 } else {
1509                         m_env->addActiveObject(child_id, type, deSerializeLongString(is));
1510                 }
1511         } else {
1512                 warningstream << FUNCTION_NAME
1513                         << ": unknown command or outdated client \""
1514                         << +cmd << "\"" << std::endl;
1515         }
1516 }
1517
1518 /* \pre punchitem != NULL
1519  */
1520 bool GenericCAO::directReportPunch(v3f dir, const ItemStack *punchitem,
1521                 float time_from_last_punch)
1522 {
1523         assert(punchitem);      // pre-condition
1524         const ToolCapabilities *toolcap =
1525                         &punchitem->getToolCapabilities(m_client->idef());
1526         PunchDamageResult result = getPunchDamage(
1527                         m_armor_groups,
1528                         toolcap,
1529                         punchitem,
1530                         time_from_last_punch);
1531
1532         if(result.did_punch && result.damage != 0)
1533         {
1534                 if(result.damage < m_hp)
1535                 {
1536                         m_hp -= result.damage;
1537                 } else {
1538                         m_hp = 0;
1539                         // TODO: Execute defined fast response
1540                         // As there is no definition, make a smoke puff
1541                         ClientSimpleObject *simple = createSmokePuff(
1542                                         m_smgr, m_env, m_position,
1543                                         m_prop.visual_size * BS);
1544                         m_env->addSimpleObject(simple);
1545                 }
1546                 // TODO: Execute defined fast response
1547                 // Flashing shall suffice as there is no definition
1548                 if (m_reset_textures_timer < 0) {
1549                         m_reset_textures_timer = 0.05;
1550                         if (result.damage >= 2)
1551                                 m_reset_textures_timer += 0.05 * result.damage;
1552                         updateTextures(m_current_texture_modifier + "^[brighten");
1553                 }
1554         }
1555
1556         return false;
1557 }
1558
1559 std::string GenericCAO::debugInfoText()
1560 {
1561         std::ostringstream os(std::ios::binary);
1562         os<<"GenericCAO hp="<<m_hp<<"\n";
1563         os<<"armor={";
1564         for(ItemGroupList::const_iterator i = m_armor_groups.begin();
1565                         i != m_armor_groups.end(); ++i)
1566         {
1567                 os<<i->first<<"="<<i->second<<", ";
1568         }
1569         os<<"}";
1570         return os.str();
1571 }
1572
1573 // Prototype
1574 GenericCAO proto_GenericCAO(NULL, NULL);