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