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