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