]> git.lizzy.rs Git - dragonfireclient.git/blob - src/client/content_cao.cpp
fix: some code tidy about includes & irr namespaces
[dragonfireclient.git] / src / client / content_cao.cpp
1 /*
2 Minetest
3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "content_cao.h"
21 #include <IBillboardSceneNode.h>
22 #include <ICameraSceneNode.h>
23 #include <ITextSceneNode.h>
24 #include <IMeshManipulator.h>
25 #include <IAnimatedMeshSceneNode.h>
26 #include "client/client.h"
27 #include "client/sound.h"
28 #include "client/tile.h"
29 #include "util/basic_macros.h"
30 #include "util/numeric.h" // For IntervalLimiter & setPitchYawRoll
31 #include "util/serialize.h"
32 #include "camera.h" // CameraModes
33 #include "collision.h"
34 #include "content_cso.h"
35 #include "environment.h"
36 #include "itemdef.h"
37 #include "localplayer.h"
38 #include "map.h"
39 #include "mesh.h"
40 #include "nodedef.h"
41 #include "serialization.h" // For decompressZlib
42 #include "settings.h"
43 #include "sound.h"
44 #include "tool.h"
45 #include "wieldmesh.h"
46 #include <algorithm>
47 #include <cmath>
48 #include "client/shader.h"
49 #include "client/minimap.h"
50
51 class Settings;
52 struct ToolCapabilities;
53
54 std::unordered_map<u16, ClientActiveObject::Factory> ClientActiveObject::m_types;
55
56 template<typename T>
57 void SmoothTranslator<T>::init(T current)
58 {
59         val_old = current;
60         val_current = current;
61         val_target = current;
62         anim_time = 0;
63         anim_time_counter = 0;
64         aim_is_end = true;
65 }
66
67 template<typename T>
68 void SmoothTranslator<T>::update(T new_target, bool is_end_position, float update_interval)
69 {
70         aim_is_end = is_end_position;
71         val_old = val_current;
72         val_target = new_target;
73         if (update_interval > 0) {
74                 anim_time = update_interval;
75         } else {
76                 if (anim_time < 0.001 || anim_time > 1.0)
77                         anim_time = anim_time_counter;
78                 else
79                         anim_time = anim_time * 0.9 + anim_time_counter * 0.1;
80         }
81         anim_time_counter = 0;
82 }
83
84 template<typename T>
85 void SmoothTranslator<T>::translate(f32 dtime)
86 {
87         anim_time_counter = anim_time_counter + dtime;
88         T val_diff = val_target - val_old;
89         f32 moveratio = 1.0;
90         if (anim_time > 0.001)
91                 moveratio = anim_time_counter / anim_time;
92         f32 move_end = aim_is_end ? 1.0 : 1.5;
93
94         // Move a bit less than should, to avoid oscillation
95         moveratio = std::min(moveratio * 0.8f, move_end);
96         val_current = val_old + val_diff * moveratio;
97 }
98
99 void SmoothTranslatorWrapped::translate(f32 dtime)
100 {
101         anim_time_counter = anim_time_counter + dtime;
102         f32 val_diff = std::abs(val_target - val_old);
103         if (val_diff > 180.f)
104                 val_diff = 360.f - val_diff;
105
106         f32 moveratio = 1.0;
107         if (anim_time > 0.001)
108                 moveratio = anim_time_counter / anim_time;
109         f32 move_end = aim_is_end ? 1.0 : 1.5;
110
111         // Move a bit less than should, to avoid oscillation
112         moveratio = std::min(moveratio * 0.8f, move_end);
113         wrappedApproachShortest(val_current, val_target,
114                 val_diff * moveratio, 360.f);
115 }
116
117 void SmoothTranslatorWrappedv3f::translate(f32 dtime)
118 {
119         anim_time_counter = anim_time_counter + dtime;
120
121         v3f val_diff_v3f;
122         val_diff_v3f.X = std::abs(val_target.X - val_old.X);
123         val_diff_v3f.Y = std::abs(val_target.Y - val_old.Y);
124         val_diff_v3f.Z = std::abs(val_target.Z - val_old.Z);
125
126         if (val_diff_v3f.X > 180.f)
127                 val_diff_v3f.X = 360.f - val_diff_v3f.X;
128
129         if (val_diff_v3f.Y > 180.f)
130                 val_diff_v3f.Y = 360.f - val_diff_v3f.Y;
131
132         if (val_diff_v3f.Z > 180.f)
133                 val_diff_v3f.Z = 360.f - val_diff_v3f.Z;
134
135         f32 moveratio = 1.0;
136         if (anim_time > 0.001)
137                 moveratio = anim_time_counter / anim_time;
138         f32 move_end = aim_is_end ? 1.0 : 1.5;
139
140         // Move a bit less than should, to avoid oscillation
141         moveratio = std::min(moveratio * 0.8f, move_end);
142         wrappedApproachShortest(val_current.X, val_target.X,
143                 val_diff_v3f.X * moveratio, 360.f);
144
145         wrappedApproachShortest(val_current.Y, val_target.Y,
146                 val_diff_v3f.Y * moveratio, 360.f);
147
148         wrappedApproachShortest(val_current.Z, val_target.Z,
149                 val_diff_v3f.Z * moveratio, 360.f);
150 }
151
152 /*
153         Other stuff
154 */
155
156 static void setBillboardTextureMatrix(scene::IBillboardSceneNode *bill,
157                 float txs, float tys, int col, int row)
158 {
159         video::SMaterial& material = bill->getMaterial(0);
160         core::matrix4& matrix = material.getTextureMatrix(0);
161         matrix.setTextureTranslate(txs*col, tys*row);
162         matrix.setTextureScale(txs, tys);
163 }
164
165 // Evaluate transform chain recursively; irrlicht does not do this for us
166 static void updatePositionRecursive(scene::ISceneNode *node)
167 {
168         scene::ISceneNode *parent = node->getParent();
169         if (parent)
170                 updatePositionRecursive(parent);
171         node->updateAbsolutePosition();
172 }
173
174 /*
175         TestCAO
176 */
177
178 class TestCAO : public ClientActiveObject
179 {
180 public:
181         TestCAO(Client *client, ClientEnvironment *env);
182         virtual ~TestCAO() = default;
183
184         ActiveObjectType getType() const
185         {
186                 return ACTIVEOBJECT_TYPE_TEST;
187         }
188
189         static ClientActiveObject* create(Client *client, ClientEnvironment *env);
190
191         void addToScene(ITextureSource *tsrc, scene::ISceneManager *smgr);
192         void removeFromScene(bool permanent);
193         void updateLight(u32 day_night_ratio);
194         void updateNodePos();
195
196         void step(float dtime, ClientEnvironment *env);
197
198         void processMessage(const std::string &data);
199
200         bool getCollisionBox(aabb3f *toset) const { return false; }
201 private:
202         scene::IMeshSceneNode *m_node;
203         v3f m_position;
204 };
205
206 // Prototype
207 TestCAO proto_TestCAO(NULL, NULL);
208
209 TestCAO::TestCAO(Client *client, ClientEnvironment *env):
210         ClientActiveObject(0, client, env),
211         m_node(NULL),
212         m_position(v3f(0,10*BS,0))
213 {
214         ClientActiveObject::registerType(getType(), create);
215 }
216
217 ClientActiveObject* TestCAO::create(Client *client, ClientEnvironment *env)
218 {
219         return new TestCAO(client, env);
220 }
221
222 void TestCAO::addToScene(ITextureSource *tsrc, scene::ISceneManager *smgr)
223 {
224         if(m_node != NULL)
225                 return;
226
227         //video::IVideoDriver* driver = smgr->getVideoDriver();
228
229         scene::SMesh *mesh = new scene::SMesh();
230         scene::IMeshBuffer *buf = new scene::SMeshBuffer();
231         video::SColor c(255,255,255,255);
232         video::S3DVertex vertices[4] =
233         {
234                 video::S3DVertex(-BS/2,-BS/4,0, 0,0,0, c, 0,1),
235                 video::S3DVertex(BS/2,-BS/4,0, 0,0,0, c, 1,1),
236                 video::S3DVertex(BS/2,BS/4,0, 0,0,0, c, 1,0),
237                 video::S3DVertex(-BS/2,BS/4,0, 0,0,0, c, 0,0),
238         };
239         u16 indices[] = {0,1,2,2,3,0};
240         buf->append(vertices, 4, indices, 6);
241         // Set material
242         buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
243         buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false);
244         buf->getMaterial().setTexture(0, tsrc->getTextureForMesh("rat.png"));
245         buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
246         buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
247         buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
248         // Add to mesh
249         mesh->addMeshBuffer(buf);
250         buf->drop();
251         m_node = smgr->addMeshSceneNode(mesh, NULL);
252         mesh->drop();
253         updateNodePos();
254 }
255
256 void TestCAO::removeFromScene(bool permanent)
257 {
258         if (!m_node)
259                 return;
260
261         m_node->remove();
262         m_node = NULL;
263 }
264
265 void TestCAO::updateLight(u32 day_night_ratio)
266 {
267 }
268
269 void TestCAO::updateNodePos()
270 {
271         if (!m_node)
272                 return;
273
274         m_node->setPosition(m_position);
275         //m_node->setRotation(v3f(0, 45, 0));
276 }
277
278 void TestCAO::step(float dtime, ClientEnvironment *env)
279 {
280         if(m_node)
281         {
282                 v3f rot = m_node->getRotation();
283                 //infostream<<"dtime="<<dtime<<", rot.Y="<<rot.Y<<std::endl;
284                 rot.Y += dtime * 180;
285                 m_node->setRotation(rot);
286         }
287 }
288
289 void TestCAO::processMessage(const std::string &data)
290 {
291         infostream<<"TestCAO: Got data: "<<data<<std::endl;
292         std::istringstream is(data, std::ios::binary);
293         u16 cmd;
294         is>>cmd;
295         if(cmd == 0)
296         {
297                 v3f newpos;
298                 is>>newpos.X;
299                 is>>newpos.Y;
300                 is>>newpos.Z;
301                 m_position = newpos;
302                 updateNodePos();
303         }
304 }
305
306 /*
307         GenericCAO
308 */
309
310 #include "clientobject.h"
311
312 GenericCAO::GenericCAO(Client *client, ClientEnvironment *env):
313                 ClientActiveObject(0, client, env)
314 {
315         if (client == NULL) {
316                 ClientActiveObject::registerType(getType(), create);
317         } else {
318                 m_client = client;
319         }
320 }
321
322 bool GenericCAO::getCollisionBox(aabb3f *toset) const
323 {
324         if (m_prop.physical)
325         {
326                 //update collision box
327                 toset->MinEdge = m_prop.collisionbox.MinEdge * BS;
328                 toset->MaxEdge = m_prop.collisionbox.MaxEdge * BS;
329
330                 toset->MinEdge += m_position;
331                 toset->MaxEdge += m_position;
332
333                 return true;
334         }
335
336         return false;
337 }
338
339 bool GenericCAO::collideWithObjects() const
340 {
341         return m_prop.collideWithObjects;
342 }
343
344 void GenericCAO::initialize(const std::string &data)
345 {
346         infostream<<"GenericCAO: Got init data"<<std::endl;
347         processInitData(data);
348
349         if (m_is_player) {
350                 // Check if it's the current player
351                 LocalPlayer *player = m_env->getLocalPlayer();
352                 if (player && strcmp(player->getName(), m_name.c_str()) == 0) {
353                         m_is_local_player = true;
354                         m_is_visible = false;
355                         player->setCAO(this);
356
357                         m_prop.show_on_minimap = false;
358                 }
359         }
360
361         m_enable_shaders = g_settings->getBool("enable_shaders");
362 }
363
364 void GenericCAO::processInitData(const std::string &data)
365 {
366         std::istringstream is(data, std::ios::binary);
367         const u8 version = readU8(is);
368
369         if (version < 1) {
370                 errorstream << "GenericCAO: Unsupported init data version"
371                                 << std::endl;
372                 return;
373         }
374
375         // PROTOCOL_VERSION >= 37
376         m_name = deSerializeString16(is);
377         m_is_player = readU8(is);
378         m_id = readU16(is);
379         m_position = readV3F32(is);
380         m_rotation = readV3F32(is);
381         m_hp = readU16(is);
382
383         const u8 num_messages = readU8(is);
384
385         for (int i = 0; i < num_messages; i++) {
386                 std::string message = deSerializeString32(is);
387                 processMessage(message);
388         }
389
390         m_rotation = wrapDegrees_0_360_v3f(m_rotation);
391         pos_translator.init(m_position);
392         rot_translator.init(m_rotation);
393         updateNodePos();
394 }
395
396 GenericCAO::~GenericCAO()
397 {
398         removeFromScene(true);
399 }
400
401 bool GenericCAO::getSelectionBox(aabb3f *toset) const
402 {
403         if (!m_prop.is_visible || !m_is_visible || m_is_local_player
404                         || !m_prop.pointable) {
405                 return false;
406         }
407         *toset = m_selection_box;
408         return true;
409 }
410
411 const v3f GenericCAO::getPosition() const
412 {
413         if (!getParent())
414                 return pos_translator.val_current;
415
416         // Calculate real position in world based on MatrixNode
417         if (m_matrixnode) {
418                 v3s16 camera_offset = m_env->getCameraOffset();
419                 return m_matrixnode->getAbsolutePosition() +
420                                 intToFloat(camera_offset, BS);
421         }
422
423         return m_position;
424 }
425
426 const bool GenericCAO::isImmortal()
427 {
428         return itemgroup_get(getGroups(), "immortal");
429 }
430
431 scene::ISceneNode *GenericCAO::getSceneNode() const
432 {
433         if (m_meshnode) {
434                 return m_meshnode;
435         }
436
437         if (m_animated_meshnode) {
438                 return m_animated_meshnode;
439         }
440
441         if (m_wield_meshnode) {
442                 return m_wield_meshnode;
443         }
444
445         if (m_spritenode) {
446                 return m_spritenode;
447         }
448         return NULL;
449 }
450
451 scene::IAnimatedMeshSceneNode *GenericCAO::getAnimatedMeshSceneNode() const
452 {
453         return m_animated_meshnode;
454 }
455
456 void GenericCAO::setChildrenVisible(bool toset)
457 {
458         for (u16 cao_id : m_attachment_child_ids) {
459                 GenericCAO *obj = m_env->getGenericCAO(cao_id);
460                 if (obj) {
461                         // Check if the entity is forced to appear in first person.
462                         obj->setVisible(obj->m_force_visible ? true : toset);
463                 }
464         }
465 }
466
467 void GenericCAO::setAttachment(int parent_id, const std::string &bone,
468                 v3f position, v3f rotation, bool force_visible)
469 {
470         int old_parent = m_attachment_parent_id;
471         m_attachment_parent_id = parent_id;
472         m_attachment_bone = bone;
473         m_attachment_position = position;
474         m_attachment_rotation = rotation;
475         m_force_visible = force_visible;
476
477         ClientActiveObject *parent = m_env->getActiveObject(parent_id);
478
479         if (parent_id != old_parent) {
480                 if (auto *o = m_env->getActiveObject(old_parent))
481                         o->removeAttachmentChild(m_id);
482                 if (parent)
483                         parent->addAttachmentChild(m_id);
484         }
485         updateAttachments();
486
487         // Forcibly show attachments if required by set_attach
488         if (m_force_visible) {
489                 m_is_visible = true;
490         } else if (!m_is_local_player) {
491                 // Objects attached to the local player should be hidden in first person
492                 m_is_visible = !m_attached_to_local ||
493                         m_client->getCamera()->getCameraMode() != CAMERA_MODE_FIRST;
494                 m_force_visible = false;
495         } else {
496                 // Local players need to have this set,
497                 // otherwise first person attachments fail.
498                 m_is_visible = true;
499         }
500 }
501
502 void GenericCAO::getAttachment(int *parent_id, std::string *bone, v3f *position,
503         v3f *rotation, bool *force_visible) const
504 {
505         *parent_id = m_attachment_parent_id;
506         *bone = m_attachment_bone;
507         *position = m_attachment_position;
508         *rotation = m_attachment_rotation;
509         *force_visible = m_force_visible;
510 }
511
512 void GenericCAO::clearChildAttachments()
513 {
514         // Cannot use for-loop here: setAttachment() modifies 'm_attachment_child_ids'!
515         while (!m_attachment_child_ids.empty()) {
516                 int child_id = *m_attachment_child_ids.begin();
517
518                 if (ClientActiveObject *child = m_env->getActiveObject(child_id))
519                         child->setAttachment(0, "", v3f(), v3f(), false);
520
521                 removeAttachmentChild(child_id);
522         }
523 }
524
525 void GenericCAO::clearParentAttachment()
526 {
527         if (m_attachment_parent_id)
528                 setAttachment(0, "", m_attachment_position, m_attachment_rotation, false);
529         else
530                 setAttachment(0, "", v3f(), v3f(), false);
531 }
532
533 void GenericCAO::addAttachmentChild(int child_id)
534 {
535         m_attachment_child_ids.insert(child_id);
536 }
537
538 void GenericCAO::removeAttachmentChild(int child_id)
539 {
540         m_attachment_child_ids.erase(child_id);
541 }
542
543 ClientActiveObject* GenericCAO::getParent() const
544 {
545         return m_attachment_parent_id ? m_env->getActiveObject(m_attachment_parent_id) :
546                         nullptr;
547 }
548
549 void GenericCAO::removeFromScene(bool permanent)
550 {
551         // Should be true when removing the object permanently
552         // and false when refreshing (eg: updating visuals)
553         if (m_env && permanent) {
554                 // The client does not know whether this object does re-appear to
555                 // a later time, thus do not clear child attachments.
556
557                 clearParentAttachment();
558         }
559
560         if (m_meshnode) {
561                 m_meshnode->remove();
562                 m_meshnode->drop();
563                 m_meshnode = nullptr;
564         } else if (m_animated_meshnode) {
565                 m_animated_meshnode->remove();
566                 m_animated_meshnode->drop();
567                 m_animated_meshnode = nullptr;
568         } else if (m_wield_meshnode) {
569                 m_wield_meshnode->remove();
570                 m_wield_meshnode->drop();
571                 m_wield_meshnode = nullptr;
572         } else if (m_spritenode) {
573                 m_spritenode->remove();
574                 m_spritenode->drop();
575                 m_spritenode = nullptr;
576         }
577
578         if (m_matrixnode) {
579                 m_matrixnode->remove();
580                 m_matrixnode->drop();
581                 m_matrixnode = nullptr;
582         }
583
584         if (m_nametag) {
585                 m_client->getCamera()->removeNametag(m_nametag);
586                 m_nametag = nullptr;
587         }
588
589         if (m_marker && m_client->getMinimap())
590                 m_client->getMinimap()->removeMarker(&m_marker);
591 }
592
593 void GenericCAO::addToScene(ITextureSource *tsrc, scene::ISceneManager *smgr)
594 {
595         m_smgr = smgr;
596
597         if (getSceneNode() != NULL) {
598                 return;
599         }
600
601         m_visuals_expired = false;
602
603         if (!m_prop.is_visible)
604                 return;
605
606         infostream << "GenericCAO::addToScene(): " << m_prop.visual << std::endl;
607
608         if (m_enable_shaders) {
609                 IShaderSource *shader_source = m_client->getShaderSource();
610                 MaterialType material_type;
611
612                 if (m_prop.shaded && m_prop.glow == 0)
613                         material_type = (m_prop.use_texture_alpha) ?
614                                 TILE_MATERIAL_ALPHA : TILE_MATERIAL_BASIC;
615                 else
616                         material_type = (m_prop.use_texture_alpha) ?
617                                 TILE_MATERIAL_PLAIN_ALPHA : TILE_MATERIAL_PLAIN;
618
619                 u32 shader_id = shader_source->getShader("object_shader", material_type, NDT_NORMAL);
620                 m_material_type = shader_source->getShaderInfo(shader_id).material;
621         } else {
622                 m_material_type = (m_prop.use_texture_alpha) ?
623                         video::EMT_TRANSPARENT_ALPHA_CHANNEL : video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
624         }
625
626         auto grabMatrixNode = [this] {
627                 m_matrixnode = m_smgr->addDummyTransformationSceneNode();
628                 m_matrixnode->grab();
629         };
630
631         auto setSceneNodeMaterial = [this] (scene::ISceneNode *node) {
632                 node->setMaterialFlag(video::EMF_LIGHTING, false);
633                 node->setMaterialFlag(video::EMF_BILINEAR_FILTER, false);
634                 node->setMaterialFlag(video::EMF_FOG_ENABLE, true);
635                 node->setMaterialType(m_material_type);
636
637                 if (m_enable_shaders) {
638                         node->setMaterialFlag(video::EMF_GOURAUD_SHADING, false);
639                         node->setMaterialFlag(video::EMF_NORMALIZE_NORMALS, true);
640                 }
641         };
642
643         if (m_prop.visual == "sprite") {
644                 grabMatrixNode();
645                 m_spritenode = m_smgr->addBillboardSceneNode(
646                                 m_matrixnode, v2f(1, 1), v3f(0,0,0), -1);
647                 m_spritenode->grab();
648                 m_spritenode->setMaterialTexture(0,
649                                 tsrc->getTextureForMesh("unknown_node.png"));
650
651                 setSceneNodeMaterial(m_spritenode);
652
653                 m_spritenode->setSize(v2f(m_prop.visual_size.X,
654                                 m_prop.visual_size.Y) * BS);
655                 {
656                         const float txs = 1.0 / 1;
657                         const float tys = 1.0 / 1;
658                         setBillboardTextureMatrix(m_spritenode,
659                                         txs, tys, 0, 0);
660                 }
661         } else if (m_prop.visual == "upright_sprite") {
662                 grabMatrixNode();
663                 scene::SMesh *mesh = new scene::SMesh();
664                 double dx = BS * m_prop.visual_size.X / 2;
665                 double dy = BS * m_prop.visual_size.Y / 2;
666                 video::SColor c(0xFFFFFFFF);
667
668                 { // Front
669                         scene::IMeshBuffer *buf = new scene::SMeshBuffer();
670                         video::S3DVertex vertices[4] = {
671                                 video::S3DVertex(-dx, -dy, 0, 0,0,1, c, 1,1),
672                                 video::S3DVertex( dx, -dy, 0, 0,0,1, c, 0,1),
673                                 video::S3DVertex( dx,  dy, 0, 0,0,1, c, 0,0),
674                                 video::S3DVertex(-dx,  dy, 0, 0,0,1, c, 1,0),
675                         };
676                         if (m_is_player) {
677                                 // Move minimal Y position to 0 (feet position)
678                                 for (video::S3DVertex &vertex : vertices)
679                                         vertex.Pos.Y += dy;
680                         }
681                         u16 indices[] = {0,1,2,2,3,0};
682                         buf->append(vertices, 4, indices, 6);
683                         // Set material
684                         buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
685                         buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
686                         buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
687                         buf->getMaterial().MaterialType = m_material_type;
688
689                         if (m_enable_shaders) {
690                                 buf->getMaterial().EmissiveColor = c;
691                                 buf->getMaterial().setFlag(video::EMF_GOURAUD_SHADING, false);
692                                 buf->getMaterial().setFlag(video::EMF_NORMALIZE_NORMALS, true);
693                         }
694
695                         // Add to mesh
696                         mesh->addMeshBuffer(buf);
697                         buf->drop();
698                 }
699                 { // Back
700                         scene::IMeshBuffer *buf = new scene::SMeshBuffer();
701                         video::S3DVertex vertices[4] = {
702                                 video::S3DVertex( dx,-dy, 0, 0,0,-1, c, 1,1),
703                                 video::S3DVertex(-dx,-dy, 0, 0,0,-1, c, 0,1),
704                                 video::S3DVertex(-dx, dy, 0, 0,0,-1, c, 0,0),
705                                 video::S3DVertex( dx, dy, 0, 0,0,-1, c, 1,0),
706                         };
707                         if (m_is_player) {
708                                 // Move minimal Y position to 0 (feet position)
709                                 for (video::S3DVertex &vertex : vertices)
710                                         vertex.Pos.Y += dy;
711                         }
712                         u16 indices[] = {0,1,2,2,3,0};
713                         buf->append(vertices, 4, indices, 6);
714                         // Set material
715                         buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
716                         buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
717                         buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
718                         buf->getMaterial().MaterialType = m_material_type;
719
720                         if (m_enable_shaders) {
721                                 buf->getMaterial().EmissiveColor = c;
722                                 buf->getMaterial().setFlag(video::EMF_GOURAUD_SHADING, false);
723                                 buf->getMaterial().setFlag(video::EMF_NORMALIZE_NORMALS, true);
724                         }
725
726                         // Add to mesh
727                         mesh->addMeshBuffer(buf);
728                         buf->drop();
729                 }
730                 m_meshnode = m_smgr->addMeshSceneNode(mesh, m_matrixnode);
731                 m_meshnode->grab();
732                 mesh->drop();
733                 // Set it to use the materials of the meshbuffers directly.
734                 // This is needed for changing the texture in the future
735                 m_meshnode->setReadOnlyMaterials(true);
736         } else if (m_prop.visual == "cube") {
737                 grabMatrixNode();
738                 scene::IMesh *mesh = createCubeMesh(v3f(BS,BS,BS));
739                 m_meshnode = m_smgr->addMeshSceneNode(mesh, m_matrixnode);
740                 m_meshnode->grab();
741                 mesh->drop();
742
743                 m_meshnode->setScale(m_prop.visual_size);
744                 m_meshnode->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
745                         m_prop.backface_culling);
746
747                 setSceneNodeMaterial(m_meshnode);
748         } else if (m_prop.visual == "mesh") {
749                 grabMatrixNode();
750                 scene::IAnimatedMesh *mesh = m_client->getMesh(m_prop.mesh, true);
751                 if (mesh) {
752                         m_animated_meshnode = m_smgr->addAnimatedMeshSceneNode(mesh, m_matrixnode);
753                         m_animated_meshnode->grab();
754                         mesh->drop(); // The scene node took hold of it
755
756                         if (!checkMeshNormals(mesh)) {
757                                 infostream << "GenericCAO: recalculating normals for mesh "
758                                         << m_prop.mesh << std::endl;
759                                 m_smgr->getMeshManipulator()->
760                                                 recalculateNormals(mesh, true, false);
761                         }
762
763                         m_animated_meshnode->animateJoints(); // Needed for some animations
764                         m_animated_meshnode->setScale(m_prop.visual_size);
765
766                         // set vertex colors to ensure alpha is set
767                         setMeshColor(m_animated_meshnode->getMesh(), video::SColor(0xFFFFFFFF));
768
769                         setAnimatedMeshColor(m_animated_meshnode, video::SColor(0xFFFFFFFF));
770
771                         setSceneNodeMaterial(m_animated_meshnode);
772
773                         m_animated_meshnode->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
774                                 m_prop.backface_culling);
775                 } else
776                         errorstream<<"GenericCAO::addToScene(): Could not load mesh "<<m_prop.mesh<<std::endl;
777         } else if (m_prop.visual == "wielditem" || m_prop.visual == "item") {
778                 grabMatrixNode();
779                 ItemStack item;
780                 if (m_prop.wield_item.empty()) {
781                         // Old format, only textures are specified.
782                         infostream << "textures: " << m_prop.textures.size() << std::endl;
783                         if (!m_prop.textures.empty()) {
784                                 infostream << "textures[0]: " << m_prop.textures[0]
785                                         << std::endl;
786                                 IItemDefManager *idef = m_client->idef();
787                                 item = ItemStack(m_prop.textures[0], 1, 0, idef);
788                         }
789                 } else {
790                         infostream << "serialized form: " << m_prop.wield_item << std::endl;
791                         item.deSerialize(m_prop.wield_item, m_client->idef());
792                 }
793                 m_wield_meshnode = new WieldMeshSceneNode(m_smgr, -1);
794                 m_wield_meshnode->setItem(item, m_client,
795                         (m_prop.visual == "wielditem"));
796
797                 m_wield_meshnode->setScale(m_prop.visual_size / 2.0f);
798                 m_wield_meshnode->setColor(video::SColor(0xFFFFFFFF));
799         } else {
800                 infostream<<"GenericCAO::addToScene(): \""<<m_prop.visual
801                                 <<"\" not supported"<<std::endl;
802         }
803
804         /* don't update while punch texture modifier is active */
805         if (m_reset_textures_timer < 0)
806                 updateTextures(m_current_texture_modifier);
807
808         scene::ISceneNode *node = getSceneNode();
809
810         if (node && m_matrixnode)
811                 node->setParent(m_matrixnode);
812
813         updateNametag();
814         updateMarker();
815         updateNodePos();
816         updateAnimation();
817         updateBonePosition();
818         updateAttachments();
819         setNodeLight(m_last_light);
820         updateMeshCulling();
821 }
822
823 void GenericCAO::updateLight(u32 day_night_ratio)
824 {
825         if (m_glow < 0)
826                 return;
827
828         u8 light_at_pos = 0;
829         bool pos_ok = false;
830
831         v3s16 pos[3];
832         u16 npos = getLightPosition(pos);
833         for (u16 i = 0; i < npos; i++) {
834                 bool this_ok;
835                 MapNode n = m_env->getMap().getNode(pos[i], &this_ok);
836                 if (this_ok) {
837                         u8 this_light = n.getLightBlend(day_night_ratio, m_client->ndef());
838                         light_at_pos = MYMAX(light_at_pos, this_light);
839                         pos_ok = true;
840                 }
841         }
842         if (!pos_ok)
843                 light_at_pos = blend_light(day_night_ratio, LIGHT_SUN, 0);
844
845         u8 light = decode_light(light_at_pos + m_glow);
846         if (light != m_last_light) {
847                 m_last_light = light;
848                 setNodeLight(light);
849         }
850 }
851
852 void GenericCAO::setNodeLight(u8 light)
853 {
854         video::SColor color(255, light, light, light);
855
856         if (m_prop.visual == "wielditem" || m_prop.visual == "item") {
857                 if (m_wield_meshnode)
858                         m_wield_meshnode->setNodeLightColor(color);
859                 return;
860         }
861
862         if (m_enable_shaders) {
863                 if (m_prop.visual == "upright_sprite") {
864                         if (!m_meshnode)
865                                 return;
866
867                         scene::IMesh *mesh = m_meshnode->getMesh();
868                         for (u32 i = 0; i < mesh->getMeshBufferCount(); ++i) {
869                                 scene::IMeshBuffer *buf = mesh->getMeshBuffer(i);
870                                 buf->getMaterial().EmissiveColor = color;
871                         }
872                 } else {
873                         scene::ISceneNode *node = getSceneNode();
874                         if (!node)
875                                 return;
876
877                         for (u32 i = 0; i < node->getMaterialCount(); ++i) {
878                                 video::SMaterial &material = node->getMaterial(i);
879                                 material.EmissiveColor = color;
880                         }
881                 }
882         } else {
883                 if (m_meshnode) {
884                         setMeshColor(m_meshnode->getMesh(), color);
885                 } else if (m_animated_meshnode) {
886                         setAnimatedMeshColor(m_animated_meshnode, color);
887                 } else if (m_spritenode) {
888                         m_spritenode->setColor(color);
889                 }
890         }
891 }
892
893 u16 GenericCAO::getLightPosition(v3s16 *pos)
894 {
895         const auto &box = m_prop.collisionbox;
896         pos[0] = floatToInt(m_position + box.MinEdge * BS, BS);
897         pos[1] = floatToInt(m_position + box.MaxEdge * BS, BS);
898
899         // Skip center pos if it falls into the same node as Min or MaxEdge
900         if ((box.MaxEdge - box.MinEdge).getLengthSQ() < 3.0f)
901                 return 2;
902         pos[2] = floatToInt(m_position + box.getCenter() * BS, BS);
903         return 3;
904 }
905
906 void GenericCAO::updateMarker()
907 {
908         if (!m_client->getMinimap())
909                 return;
910
911         if (!m_prop.show_on_minimap) {
912                 if (m_marker)
913                         m_client->getMinimap()->removeMarker(&m_marker);
914                 return;
915         }
916
917         if (m_marker)
918                 return;
919
920         scene::ISceneNode *node = getSceneNode();
921         if (!node)
922                 return;
923         m_marker = m_client->getMinimap()->addMarker(node);
924 }
925
926 void GenericCAO::updateNametag()
927 {
928         if (m_is_local_player) // No nametag for local player
929                 return;
930
931         if (m_prop.nametag.empty() || m_prop.nametag_color.getAlpha() == 0) {
932                 // Delete nametag
933                 if (m_nametag) {
934                         m_client->getCamera()->removeNametag(m_nametag);
935                         m_nametag = nullptr;
936                 }
937                 return;
938         }
939
940         scene::ISceneNode *node = getSceneNode();
941         if (!node)
942                 return;
943
944         v3f pos;
945         pos.Y = m_prop.selectionbox.MaxEdge.Y + 0.3f;
946         if (!m_nametag) {
947                 // Add nametag
948                 m_nametag = m_client->getCamera()->addNametag(node,
949                         m_prop.nametag, m_prop.nametag_color,
950                         m_prop.nametag_bgcolor, pos);
951         } else {
952                 // Update nametag
953                 m_nametag->text = m_prop.nametag;
954                 m_nametag->textcolor = m_prop.nametag_color;
955                 m_nametag->bgcolor = m_prop.nametag_bgcolor;
956                 m_nametag->pos = pos;
957         }
958 }
959
960 void GenericCAO::updateNodePos()
961 {
962         if (getParent() != NULL)
963                 return;
964
965         scene::ISceneNode *node = getSceneNode();
966
967         if (node) {
968                 v3s16 camera_offset = m_env->getCameraOffset();
969                 v3f pos = pos_translator.val_current -
970                                 intToFloat(camera_offset, BS);
971                 getPosRotMatrix().setTranslation(pos);
972                 if (node != m_spritenode) { // rotate if not a sprite
973                         v3f rot = m_is_local_player ? -m_rotation : -rot_translator.val_current;
974                         setPitchYawRoll(getPosRotMatrix(), rot);
975                 }
976         }
977 }
978
979 void GenericCAO::step(float dtime, ClientEnvironment *env)
980 {
981         // Handle model animations and update positions instantly to prevent lags
982         if (m_is_local_player) {
983                 LocalPlayer *player = m_env->getLocalPlayer();
984                 m_position = player->getPosition();
985                 pos_translator.val_current = m_position;
986                 m_rotation.Y = wrapDegrees_0_360(player->getYaw());
987                 rot_translator.val_current = m_rotation;
988
989                 if (m_is_visible) {
990                         int old_anim = player->last_animation;
991                         float old_anim_speed = player->last_animation_speed;
992                         m_velocity = v3f(0,0,0);
993                         m_acceleration = v3f(0,0,0);
994                         const PlayerControl &controls = player->getPlayerControl();
995
996                         bool walking = false;
997                         if (controls.up || controls.down || controls.left || controls.right ||
998                                         controls.forw_move_joystick_axis != 0.f ||
999                                         controls.sidew_move_joystick_axis != 0.f)
1000                                 walking = true;
1001
1002                         f32 new_speed = player->local_animation_speed;
1003                         v2s32 new_anim = v2s32(0,0);
1004                         bool allow_update = false;
1005
1006                         // increase speed if using fast or flying fast
1007                         if((g_settings->getBool("fast_move") &&
1008                                         m_client->checkLocalPrivilege("fast")) &&
1009                                         (controls.aux1 ||
1010                                         (!player->touching_ground &&
1011                                         g_settings->getBool("free_move") &&
1012                                         m_client->checkLocalPrivilege("fly"))))
1013                                         new_speed *= 1.5;
1014                         // slowdown speed if sneeking
1015                         if (controls.sneak && walking)
1016                                 new_speed /= 2;
1017
1018                         if (walking && (controls.dig || controls.place)) {
1019                                 new_anim = player->local_animations[3];
1020                                 player->last_animation = WD_ANIM;
1021                         } else if (walking) {
1022                                 new_anim = player->local_animations[1];
1023                                 player->last_animation = WALK_ANIM;
1024                         } else if (controls.dig || controls.place) {
1025                                 new_anim = player->local_animations[2];
1026                                 player->last_animation = DIG_ANIM;
1027                         }
1028
1029                         // Apply animations if input detected and not attached
1030                         // or set idle animation
1031                         if ((new_anim.X + new_anim.Y) > 0 && !getParent()) {
1032                                 allow_update = true;
1033                                 m_animation_range = new_anim;
1034                                 m_animation_speed = new_speed;
1035                                 player->last_animation_speed = m_animation_speed;
1036                         } else {
1037                                 player->last_animation = NO_ANIM;
1038
1039                                 if (old_anim != NO_ANIM) {
1040                                         m_animation_range = player->local_animations[0];
1041                                         updateAnimation();
1042                                 }
1043                         }
1044
1045                         // Update local player animations
1046                         if ((player->last_animation != old_anim ||
1047                                         m_animation_speed != old_anim_speed) &&
1048                                         player->last_animation != NO_ANIM && allow_update)
1049                                 updateAnimation();
1050
1051                 }
1052         }
1053
1054         if (m_visuals_expired && m_smgr) {
1055                 m_visuals_expired = false;
1056
1057                 // Attachments, part 1: All attached objects must be unparented first,
1058                 // or Irrlicht causes a segmentation fault
1059                 for (u16 cao_id : m_attachment_child_ids) {
1060                         ClientActiveObject *obj = m_env->getActiveObject(cao_id);
1061                         if (obj) {
1062                                 scene::ISceneNode *child_node = obj->getSceneNode();
1063                                 // The node's parent is always an IDummyTraformationSceneNode,
1064                                 // so we need to reparent that one instead.
1065                                 if (child_node)
1066                                         child_node->getParent()->setParent(m_smgr->getRootSceneNode());
1067                         }
1068                 }
1069
1070                 removeFromScene(false);
1071                 addToScene(m_client->tsrc(), m_smgr);
1072
1073                 // Attachments, part 2: Now that the parent has been refreshed, put its attachments back
1074                 for (u16 cao_id : m_attachment_child_ids) {
1075                         ClientActiveObject *obj = m_env->getActiveObject(cao_id);
1076                         if (obj)
1077                                 obj->updateAttachments();
1078                 }
1079         }
1080
1081         // Make sure m_is_visible is always applied
1082         scene::ISceneNode *node = getSceneNode();
1083         if (node)
1084                 node->setVisible(m_is_visible);
1085
1086         if(getParent() != NULL) // Attachments should be glued to their parent by Irrlicht
1087         {
1088                 // Set these for later
1089                 m_position = getPosition();
1090                 m_velocity = v3f(0,0,0);
1091                 m_acceleration = v3f(0,0,0);
1092                 pos_translator.val_current = m_position;
1093                 pos_translator.val_target = m_position;
1094         } else {
1095                 rot_translator.translate(dtime);
1096                 v3f lastpos = pos_translator.val_current;
1097
1098                 if(m_prop.physical)
1099                 {
1100                         aabb3f box = m_prop.collisionbox;
1101                         box.MinEdge *= BS;
1102                         box.MaxEdge *= BS;
1103                         collisionMoveResult moveresult;
1104                         f32 pos_max_d = BS*0.125; // Distance per iteration
1105                         v3f p_pos = m_position;
1106                         v3f p_velocity = m_velocity;
1107                         moveresult = collisionMoveSimple(env,env->getGameDef(),
1108                                         pos_max_d, box, m_prop.stepheight, dtime,
1109                                         &p_pos, &p_velocity, m_acceleration,
1110                                         this, m_prop.collideWithObjects);
1111                         // Apply results
1112                         m_position = p_pos;
1113                         m_velocity = p_velocity;
1114
1115                         bool is_end_position = moveresult.collides;
1116                         pos_translator.update(m_position, is_end_position, dtime);
1117                 } else {
1118                         m_position += dtime * m_velocity + 0.5 * dtime * dtime * m_acceleration;
1119                         m_velocity += dtime * m_acceleration;
1120                         pos_translator.update(m_position, pos_translator.aim_is_end,
1121                                         pos_translator.anim_time);
1122                 }
1123                 pos_translator.translate(dtime);
1124                 updateNodePos();
1125
1126                 float moved = lastpos.getDistanceFrom(pos_translator.val_current);
1127                 m_step_distance_counter += moved;
1128                 if (m_step_distance_counter > 1.5f * BS) {
1129                         m_step_distance_counter = 0.0f;
1130                         if (!m_is_local_player && m_prop.makes_footstep_sound) {
1131                                 const NodeDefManager *ndef = m_client->ndef();
1132                                 v3s16 p = floatToInt(getPosition() +
1133                                         v3f(0.0f, (m_prop.collisionbox.MinEdge.Y - 0.5f) * BS, 0.0f), BS);
1134                                 MapNode n = m_env->getMap().getNode(p);
1135                                 SimpleSoundSpec spec = ndef->get(n).sound_footstep;
1136                                 // Reduce footstep gain, as non-local-player footsteps are
1137                                 // somehow louder.
1138                                 spec.gain *= 0.6f;
1139                                 m_client->sound()->playSoundAt(spec, false, getPosition());
1140                         }
1141                 }
1142         }
1143
1144         m_anim_timer += dtime;
1145         if(m_anim_timer >= m_anim_framelength)
1146         {
1147                 m_anim_timer -= m_anim_framelength;
1148                 m_anim_frame++;
1149                 if(m_anim_frame >= m_anim_num_frames)
1150                         m_anim_frame = 0;
1151         }
1152
1153         updateTexturePos();
1154
1155         if(m_reset_textures_timer >= 0)
1156         {
1157                 m_reset_textures_timer -= dtime;
1158                 if(m_reset_textures_timer <= 0) {
1159                         m_reset_textures_timer = -1;
1160                         updateTextures(m_previous_texture_modifier);
1161                 }
1162         }
1163
1164         if (!getParent() && node && fabs(m_prop.automatic_rotate) > 0.001f) {
1165                 // This is the child node's rotation. It is only used for automatic_rotate.
1166                 v3f local_rot = node->getRotation();
1167                 local_rot.Y = modulo360f(local_rot.Y - dtime * core::RADTODEG *
1168                                 m_prop.automatic_rotate);
1169                 node->setRotation(local_rot);
1170         }
1171
1172         if (!getParent() && m_prop.automatic_face_movement_dir &&
1173                         (fabs(m_velocity.Z) > 0.001f || fabs(m_velocity.X) > 0.001f)) {
1174                 float target_yaw = atan2(m_velocity.Z, m_velocity.X) * 180 / M_PI
1175                                 + m_prop.automatic_face_movement_dir_offset;
1176                 float max_rotation_per_sec =
1177                                 m_prop.automatic_face_movement_max_rotation_per_sec;
1178
1179                 if (max_rotation_per_sec > 0) {
1180                         wrappedApproachShortest(m_rotation.Y, target_yaw,
1181                                 dtime * max_rotation_per_sec, 360.f);
1182                 } else {
1183                         // Negative values of max_rotation_per_sec mean disabled.
1184                         m_rotation.Y = target_yaw;
1185                 }
1186
1187                 rot_translator.val_current = m_rotation;
1188                 updateNodePos();
1189         }
1190
1191         if (m_animated_meshnode) {
1192                 // Everything must be updated; the whole transform
1193                 // chain as well as the animated mesh node.
1194                 // Otherwise, bone attachments would be relative to
1195                 // a position that's one frame old.
1196                 if (m_matrixnode)
1197                         updatePositionRecursive(m_matrixnode);
1198                 m_animated_meshnode->updateAbsolutePosition();
1199                 m_animated_meshnode->animateJoints();
1200                 updateBonePosition();
1201         }
1202 }
1203
1204 void GenericCAO::updateTexturePos()
1205 {
1206         if(m_spritenode)
1207         {
1208                 scene::ICameraSceneNode* camera =
1209                                 m_spritenode->getSceneManager()->getActiveCamera();
1210                 if(!camera)
1211                         return;
1212                 v3f cam_to_entity = m_spritenode->getAbsolutePosition()
1213                                 - camera->getAbsolutePosition();
1214                 cam_to_entity.normalize();
1215
1216                 int row = m_tx_basepos.Y;
1217                 int col = m_tx_basepos.X;
1218
1219                 // Yawpitch goes rightwards
1220                 if (m_tx_select_horiz_by_yawpitch) {
1221                         if (cam_to_entity.Y > 0.75)
1222                                 col += 5;
1223                         else if (cam_to_entity.Y < -0.75)
1224                                 col += 4;
1225                         else {
1226                                 float mob_dir =
1227                                                 atan2(cam_to_entity.Z, cam_to_entity.X) / M_PI * 180.;
1228                                 float dir = mob_dir - m_rotation.Y;
1229                                 dir = wrapDegrees_180(dir);
1230                                 if (std::fabs(wrapDegrees_180(dir - 0)) <= 45.1f)
1231                                         col += 2;
1232                                 else if(std::fabs(wrapDegrees_180(dir - 90)) <= 45.1f)
1233                                         col += 3;
1234                                 else if(std::fabs(wrapDegrees_180(dir - 180)) <= 45.1f)
1235                                         col += 0;
1236                                 else if(std::fabs(wrapDegrees_180(dir + 90)) <= 45.1f)
1237                                         col += 1;
1238                                 else
1239                                         col += 4;
1240                         }
1241                 }
1242
1243                 // Animation goes downwards
1244                 row += m_anim_frame;
1245
1246                 float txs = m_tx_size.X;
1247                 float tys = m_tx_size.Y;
1248                 setBillboardTextureMatrix(m_spritenode, txs, tys, col, row);
1249         }
1250
1251         else if (m_meshnode) {
1252                 if (m_prop.visual == "upright_sprite") {
1253                         int row = m_tx_basepos.Y;
1254                         int col = m_tx_basepos.X;
1255
1256                         // Animation goes downwards
1257                         row += m_anim_frame;
1258
1259                         const auto &tx = m_tx_size;
1260                         v2f t[4] = { // cf. vertices in GenericCAO::addToScene()
1261                                 tx * v2f(col+1, row+1),
1262                                 tx * v2f(col, row+1),
1263                                 tx * v2f(col, row),
1264                                 tx * v2f(col+1, row),
1265                         };
1266                         auto mesh = m_meshnode->getMesh();
1267                         setMeshBufferTextureCoords(mesh->getMeshBuffer(0), t, 4);
1268                         setMeshBufferTextureCoords(mesh->getMeshBuffer(1), t, 4);
1269                 }
1270         }
1271 }
1272
1273 // Do not pass by reference, see header.
1274 void GenericCAO::updateTextures(std::string mod)
1275 {
1276         ITextureSource *tsrc = m_client->tsrc();
1277
1278         bool use_trilinear_filter = g_settings->getBool("trilinear_filter");
1279         bool use_bilinear_filter = g_settings->getBool("bilinear_filter");
1280         bool use_anisotropic_filter = g_settings->getBool("anisotropic_filter");
1281
1282         m_previous_texture_modifier = m_current_texture_modifier;
1283         m_current_texture_modifier = mod;
1284         m_glow = m_prop.glow;
1285
1286         if (m_spritenode) {
1287                 if (m_prop.visual == "sprite") {
1288                         std::string texturestring = "unknown_node.png";
1289                         if (!m_prop.textures.empty())
1290                                 texturestring = m_prop.textures[0];
1291                         texturestring += mod;
1292                         m_spritenode->getMaterial(0).MaterialType = m_material_type;
1293                         m_spritenode->getMaterial(0).MaterialTypeParam = 0.5f;
1294                         m_spritenode->setMaterialTexture(0,
1295                                         tsrc->getTextureForMesh(texturestring));
1296
1297                         // This allows setting per-material colors. However, until a real lighting
1298                         // system is added, the code below will have no effect. Once MineTest
1299                         // has directional lighting, it should work automatically.
1300                         if (!m_prop.colors.empty()) {
1301                                 m_spritenode->getMaterial(0).AmbientColor = m_prop.colors[0];
1302                                 m_spritenode->getMaterial(0).DiffuseColor = m_prop.colors[0];
1303                                 m_spritenode->getMaterial(0).SpecularColor = m_prop.colors[0];
1304                         }
1305
1306                         m_spritenode->getMaterial(0).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1307                         m_spritenode->getMaterial(0).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1308                         m_spritenode->getMaterial(0).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1309                 }
1310         }
1311
1312         else if (m_animated_meshnode) {
1313                 if (m_prop.visual == "mesh") {
1314                         for (u32 i = 0; i < m_prop.textures.size() &&
1315                                         i < m_animated_meshnode->getMaterialCount(); ++i) {
1316                                 std::string texturestring = m_prop.textures[i];
1317                                 if (texturestring.empty())
1318                                         continue; // Empty texture string means don't modify that material
1319                                 texturestring += mod;
1320                                 video::ITexture* texture = tsrc->getTextureForMesh(texturestring);
1321                                 if (!texture) {
1322                                         errorstream<<"GenericCAO::updateTextures(): Could not load texture "<<texturestring<<std::endl;
1323                                         continue;
1324                                 }
1325
1326                                 // Set material flags and texture
1327                                 video::SMaterial& material = m_animated_meshnode->getMaterial(i);
1328                                 material.MaterialType = m_material_type;
1329                                 material.MaterialTypeParam = 0.5f;
1330                                 material.TextureLayer[0].Texture = texture;
1331                                 material.setFlag(video::EMF_LIGHTING, true);
1332                                 material.setFlag(video::EMF_BILINEAR_FILTER, false);
1333                                 material.setFlag(video::EMF_BACK_FACE_CULLING, m_prop.backface_culling);
1334
1335                                 // don't filter low-res textures, makes them look blurry
1336                                 // player models have a res of 64
1337                                 const core::dimension2d<u32> &size = texture->getOriginalSize();
1338                                 const u32 res = std::min(size.Height, size.Width);
1339                                 use_trilinear_filter &= res > 64;
1340                                 use_bilinear_filter &= res > 64;
1341
1342                                 m_animated_meshnode->getMaterial(i)
1343                                                 .setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1344                                 m_animated_meshnode->getMaterial(i)
1345                                                 .setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1346                                 m_animated_meshnode->getMaterial(i)
1347                                                 .setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1348                         }
1349                         for (u32 i = 0; i < m_prop.colors.size() &&
1350                         i < m_animated_meshnode->getMaterialCount(); ++i)
1351                         {
1352                                 // This allows setting per-material colors. However, until a real lighting
1353                                 // system is added, the code below will have no effect. Once MineTest
1354                                 // has directional lighting, it should work automatically.
1355                                 m_animated_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i];
1356                                 m_animated_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i];
1357                                 m_animated_meshnode->getMaterial(i).SpecularColor = m_prop.colors[i];
1358                         }
1359                 }
1360         }
1361
1362         else if (m_meshnode) {
1363                 if(m_prop.visual == "cube")
1364                 {
1365                         for (u32 i = 0; i < 6; ++i)
1366                         {
1367                                 std::string texturestring = "unknown_node.png";
1368                                 if(m_prop.textures.size() > i)
1369                                         texturestring = m_prop.textures[i];
1370                                 texturestring += mod;
1371
1372
1373                                 // Set material flags and texture
1374                                 video::SMaterial& material = m_meshnode->getMaterial(i);
1375                                 material.MaterialType = m_material_type;
1376                                 material.MaterialTypeParam = 0.5f;
1377                                 material.setFlag(video::EMF_LIGHTING, false);
1378                                 material.setFlag(video::EMF_BILINEAR_FILTER, false);
1379                                 material.setTexture(0,
1380                                                 tsrc->getTextureForMesh(texturestring));
1381                                 material.getTextureMatrix(0).makeIdentity();
1382
1383                                 // This allows setting per-material colors. However, until a real lighting
1384                                 // system is added, the code below will have no effect. Once MineTest
1385                                 // has directional lighting, it should work automatically.
1386                                 if(m_prop.colors.size() > i)
1387                                 {
1388                                         m_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i];
1389                                         m_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i];
1390                                         m_meshnode->getMaterial(i).SpecularColor = m_prop.colors[i];
1391                                 }
1392
1393                                 m_meshnode->getMaterial(i).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1394                                 m_meshnode->getMaterial(i).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1395                                 m_meshnode->getMaterial(i).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1396                         }
1397                 } else if (m_prop.visual == "upright_sprite") {
1398                         scene::IMesh *mesh = m_meshnode->getMesh();
1399                         {
1400                                 std::string tname = "unknown_object.png";
1401                                 if (!m_prop.textures.empty())
1402                                         tname = m_prop.textures[0];
1403                                 tname += mod;
1404                                 scene::IMeshBuffer *buf = mesh->getMeshBuffer(0);
1405                                 buf->getMaterial().setTexture(0,
1406                                                 tsrc->getTextureForMesh(tname));
1407
1408                                 // This allows setting per-material colors. However, until a real lighting
1409                                 // system is added, the code below will have no effect. Once MineTest
1410                                 // has directional lighting, it should work automatically.
1411                                 if(!m_prop.colors.empty()) {
1412                                         buf->getMaterial().AmbientColor = m_prop.colors[0];
1413                                         buf->getMaterial().DiffuseColor = m_prop.colors[0];
1414                                         buf->getMaterial().SpecularColor = m_prop.colors[0];
1415                                 }
1416
1417                                 buf->getMaterial().setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1418                                 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1419                                 buf->getMaterial().setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1420                         }
1421                         {
1422                                 std::string tname = "unknown_object.png";
1423                                 if (m_prop.textures.size() >= 2)
1424                                         tname = m_prop.textures[1];
1425                                 else if (!m_prop.textures.empty())
1426                                         tname = m_prop.textures[0];
1427                                 tname += mod;
1428                                 scene::IMeshBuffer *buf = mesh->getMeshBuffer(1);
1429                                 buf->getMaterial().setTexture(0,
1430                                                 tsrc->getTextureForMesh(tname));
1431
1432                                 // This allows setting per-material colors. However, until a real lighting
1433                                 // system is added, the code below will have no effect. Once MineTest
1434                                 // has directional lighting, it should work automatically.
1435                                 if (m_prop.colors.size() >= 2) {
1436                                         buf->getMaterial().AmbientColor = m_prop.colors[1];
1437                                         buf->getMaterial().DiffuseColor = m_prop.colors[1];
1438                                         buf->getMaterial().SpecularColor = m_prop.colors[1];
1439                                 } else if (!m_prop.colors.empty()) {
1440                                         buf->getMaterial().AmbientColor = m_prop.colors[0];
1441                                         buf->getMaterial().DiffuseColor = m_prop.colors[0];
1442                                         buf->getMaterial().SpecularColor = m_prop.colors[0];
1443                                 }
1444
1445                                 buf->getMaterial().setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1446                                 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1447                                 buf->getMaterial().setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1448                         }
1449                         // Set mesh color (only if lighting is disabled)
1450                         if (!m_prop.colors.empty() && m_glow < 0)
1451                                 setMeshColor(mesh, m_prop.colors[0]);
1452                 }
1453         }
1454         // Prevent showing the player after changing texture
1455         if (m_is_local_player)
1456                 updateMeshCulling();
1457 }
1458
1459 void GenericCAO::updateAnimation()
1460 {
1461         if (!m_animated_meshnode)
1462                 return;
1463
1464         if (m_animated_meshnode->getStartFrame() != m_animation_range.X ||
1465                 m_animated_meshnode->getEndFrame() != m_animation_range.Y)
1466                         m_animated_meshnode->setFrameLoop(m_animation_range.X, m_animation_range.Y);
1467         if (m_animated_meshnode->getAnimationSpeed() != m_animation_speed)
1468                 m_animated_meshnode->setAnimationSpeed(m_animation_speed);
1469         m_animated_meshnode->setTransitionTime(m_animation_blend);
1470         if (m_animated_meshnode->getLoopMode() != m_animation_loop)
1471                 m_animated_meshnode->setLoopMode(m_animation_loop);
1472 }
1473
1474 void GenericCAO::updateAnimationSpeed()
1475 {
1476         if (!m_animated_meshnode)
1477                 return;
1478
1479         m_animated_meshnode->setAnimationSpeed(m_animation_speed);
1480 }
1481
1482 void GenericCAO::updateBonePosition()
1483 {
1484         if (m_bone_position.empty() || !m_animated_meshnode)
1485                 return;
1486
1487         m_animated_meshnode->setJointMode(scene::EJUOR_CONTROL); // To write positions to the mesh on render
1488         for (auto &it : m_bone_position) {
1489                 std::string bone_name = it.first;
1490                 scene::IBoneSceneNode* bone = m_animated_meshnode->getJointNode(bone_name.c_str());
1491                 if (bone) {
1492                         bone->setPosition(it.second.X);
1493                         bone->setRotation(it.second.Y);
1494                 }
1495         }
1496
1497         // search through bones to find mistakenly rotated bones due to bug in Irrlicht
1498         for (u32 i = 0; i < m_animated_meshnode->getJointCount(); ++i) {
1499                 scene::IBoneSceneNode *bone = m_animated_meshnode->getJointNode(i);
1500                 if (!bone)
1501                         continue;
1502
1503                 //If bone is manually positioned there is no need to perform the bug check
1504                 bool skip = false;
1505                 for (auto &it : m_bone_position) {
1506                         if (it.first == bone->getName()) {
1507                                 skip = true;
1508                                 break;
1509                         }
1510                 }
1511                 if (skip)
1512                         continue;
1513
1514                 // Workaround for Irrlicht bug
1515                 // We check each bone to see if it has been rotated ~180deg from its expected position due to a bug in Irricht
1516                 // when using EJUOR_CONTROL joint control. If the bug is detected we update the bone to the proper position
1517                 // and update the bones transformation.
1518                 v3f bone_rot = bone->getRelativeTransformation().getRotationDegrees();
1519                 float offset = fabsf(bone_rot.X - bone->getRotation().X);
1520                 if (offset > 179.9f && offset < 180.1f) {
1521                         bone->setRotation(bone_rot);
1522                         bone->updateAbsolutePosition();
1523                 }
1524         }
1525         // The following is needed for set_bone_pos to propagate to
1526         // attached objects correctly.
1527         // Irrlicht ought to do this, but doesn't when using EJUOR_CONTROL.
1528         for (u32 i = 0; i < m_animated_meshnode->getJointCount(); ++i) {
1529                 auto bone = m_animated_meshnode->getJointNode(i);
1530                 // Look for the root bone.
1531                 if (bone && bone->getParent() == m_animated_meshnode) {
1532                         // Update entire skeleton.
1533                         bone->updateAbsolutePositionOfAllChildren();
1534                         break;
1535                 }
1536         }
1537 }
1538
1539 void GenericCAO::updateAttachments()
1540 {
1541         ClientActiveObject *parent = getParent();
1542
1543         m_attached_to_local = parent && parent->isLocalPlayer();
1544
1545         /*
1546         Following cases exist:
1547                 m_attachment_parent_id == 0 && !parent
1548                         This object is not attached
1549                 m_attachment_parent_id != 0 && parent
1550                         This object is attached
1551                 m_attachment_parent_id != 0 && !parent
1552                         This object will be attached as soon the parent is known
1553                 m_attachment_parent_id == 0 && parent
1554                         Impossible case
1555         */
1556
1557         if (!parent) { // Detach or don't attach
1558                 if (m_matrixnode) {
1559                         v3s16 camera_offset = m_env->getCameraOffset();
1560                         v3f old_pos = getPosition();
1561
1562                         m_matrixnode->setParent(m_smgr->getRootSceneNode());
1563                         getPosRotMatrix().setTranslation(old_pos - intToFloat(camera_offset, BS));
1564                         m_matrixnode->updateAbsolutePosition();
1565                 }
1566         }
1567         else // Attach
1568         {
1569                 parent->updateAttachments();
1570                 scene::ISceneNode *parent_node = parent->getSceneNode();
1571                 scene::IAnimatedMeshSceneNode *parent_animated_mesh_node =
1572                                 parent->getAnimatedMeshSceneNode();
1573                 if (parent_animated_mesh_node && !m_attachment_bone.empty()) {
1574                         parent_node = parent_animated_mesh_node->getJointNode(m_attachment_bone.c_str());
1575                 }
1576
1577                 if (m_matrixnode && parent_node) {
1578                         m_matrixnode->setParent(parent_node);
1579                         parent_node->updateAbsolutePosition();
1580                         getPosRotMatrix().setTranslation(m_attachment_position);
1581                         //setPitchYawRoll(getPosRotMatrix(), m_attachment_rotation);
1582                         // use Irrlicht eulers instead
1583                         getPosRotMatrix().setRotationDegrees(m_attachment_rotation);
1584                         m_matrixnode->updateAbsolutePosition();
1585                 }
1586         }
1587 }
1588
1589 bool GenericCAO::visualExpiryRequired(const ObjectProperties &new_) const
1590 {
1591         const ObjectProperties &old = m_prop;
1592         /* Visuals do not need to be expired for:
1593          * - nametag props: handled by updateNametag()
1594          * - textures:      handled by updateTextures()
1595          * - sprite props:  handled by updateTexturePos()
1596          * - glow:          handled by updateLight()
1597          * - any other properties that do not change appearance
1598          */
1599
1600         bool uses_legacy_texture = new_.wield_item.empty() &&
1601                 (new_.visual == "wielditem" || new_.visual == "item");
1602         // Ordered to compare primitive types before std::vectors
1603         return old.backface_culling != new_.backface_culling ||
1604                 old.is_visible != new_.is_visible ||
1605                 old.mesh != new_.mesh ||
1606                 old.shaded != new_.shaded ||
1607                 old.use_texture_alpha != new_.use_texture_alpha ||
1608                 old.visual != new_.visual ||
1609                 old.visual_size != new_.visual_size ||
1610                 old.wield_item != new_.wield_item ||
1611                 old.colors != new_.colors ||
1612                 (uses_legacy_texture && old.textures != new_.textures);
1613 }
1614
1615 void GenericCAO::processMessage(const std::string &data)
1616 {
1617         //infostream<<"GenericCAO: Got message"<<std::endl;
1618         std::istringstream is(data, std::ios::binary);
1619         // command
1620         u8 cmd = readU8(is);
1621         if (cmd == AO_CMD_SET_PROPERTIES) {
1622                 ObjectProperties newprops;
1623                 newprops.show_on_minimap = m_is_player; // default
1624
1625                 newprops.deSerialize(is);
1626
1627                 // Check what exactly changed
1628                 bool expire_visuals = visualExpiryRequired(newprops);
1629                 bool textures_changed = m_prop.textures != newprops.textures;
1630
1631                 // Apply changes
1632                 m_prop = std::move(newprops);
1633
1634                 m_selection_box = m_prop.selectionbox;
1635                 m_selection_box.MinEdge *= BS;
1636                 m_selection_box.MaxEdge *= BS;
1637
1638                 m_tx_size.X = 1.0f / m_prop.spritediv.X;
1639                 m_tx_size.Y = 1.0f / m_prop.spritediv.Y;
1640
1641                 if(!m_initial_tx_basepos_set){
1642                         m_initial_tx_basepos_set = true;
1643                         m_tx_basepos = m_prop.initial_sprite_basepos;
1644                 }
1645                 if (m_is_local_player) {
1646                         LocalPlayer *player = m_env->getLocalPlayer();
1647                         player->makes_footstep_sound = m_prop.makes_footstep_sound;
1648                         aabb3f collision_box = m_prop.collisionbox;
1649                         collision_box.MinEdge *= BS;
1650                         collision_box.MaxEdge *= BS;
1651                         player->setCollisionbox(collision_box);
1652                         player->setEyeHeight(m_prop.eye_height);
1653                         player->setZoomFOV(m_prop.zoom_fov);
1654                 }
1655
1656                 if ((m_is_player && !m_is_local_player) && m_prop.nametag.empty())
1657                         m_prop.nametag = m_name;
1658                 if (m_is_local_player)
1659                         m_prop.show_on_minimap = false;
1660
1661                 if (expire_visuals) {
1662                         expireVisuals();
1663                 } else {
1664                         infostream << "GenericCAO: properties updated but expiring visuals"
1665                                 << " not necessary" << std::endl;
1666                         if (textures_changed) {
1667                                 // don't update while punch texture modifier is active
1668                                 if (m_reset_textures_timer < 0)
1669                                         updateTextures(m_current_texture_modifier);
1670                         }
1671                         updateNametag();
1672                         updateMarker();
1673                 }
1674         } else if (cmd == AO_CMD_UPDATE_POSITION) {
1675                 // Not sent by the server if this object is an attachment.
1676                 // We might however get here if the server notices the object being detached before the client.
1677                 m_position = readV3F32(is);
1678                 m_velocity = readV3F32(is);
1679                 m_acceleration = readV3F32(is);
1680                 m_rotation = readV3F32(is);
1681
1682                 m_rotation = wrapDegrees_0_360_v3f(m_rotation);
1683                 bool do_interpolate = readU8(is);
1684                 bool is_end_position = readU8(is);
1685                 float update_interval = readF32(is);
1686
1687                 // Place us a bit higher if we're physical, to not sink into
1688                 // the ground due to sucky collision detection...
1689                 if(m_prop.physical)
1690                         m_position += v3f(0,0.002,0);
1691
1692                 if(getParent() != NULL) // Just in case
1693                         return;
1694
1695                 if(do_interpolate)
1696                 {
1697                         if(!m_prop.physical)
1698                                 pos_translator.update(m_position, is_end_position, update_interval);
1699                 } else {
1700                         pos_translator.init(m_position);
1701                 }
1702                 rot_translator.update(m_rotation, false, update_interval);
1703                 updateNodePos();
1704         } else if (cmd == AO_CMD_SET_TEXTURE_MOD) {
1705                 std::string mod = deSerializeString16(is);
1706
1707                 // immediately reset a engine issued texture modifier if a mod sends a different one
1708                 if (m_reset_textures_timer > 0) {
1709                         m_reset_textures_timer = -1;
1710                         updateTextures(m_previous_texture_modifier);
1711                 }
1712                 updateTextures(mod);
1713         } else if (cmd == AO_CMD_SET_SPRITE) {
1714                 v2s16 p = readV2S16(is);
1715                 int num_frames = readU16(is);
1716                 float framelength = readF32(is);
1717                 bool select_horiz_by_yawpitch = readU8(is);
1718
1719                 m_tx_basepos = p;
1720                 m_anim_num_frames = num_frames;
1721                 m_anim_framelength = framelength;
1722                 m_tx_select_horiz_by_yawpitch = select_horiz_by_yawpitch;
1723
1724                 updateTexturePos();
1725         } else if (cmd == AO_CMD_SET_PHYSICS_OVERRIDE) {
1726                 float override_speed = readF32(is);
1727                 float override_jump = readF32(is);
1728                 float override_gravity = readF32(is);
1729                 // these are sent inverted so we get true when the server sends nothing
1730                 bool sneak = !readU8(is);
1731                 bool sneak_glitch = !readU8(is);
1732                 bool new_move = !readU8(is);
1733
1734
1735                 if(m_is_local_player)
1736                 {
1737                         LocalPlayer *player = m_env->getLocalPlayer();
1738                         player->physics_override_speed = override_speed;
1739                         player->physics_override_jump = override_jump;
1740                         player->physics_override_gravity = override_gravity;
1741                         player->physics_override_sneak = sneak;
1742                         player->physics_override_sneak_glitch = sneak_glitch;
1743                         player->physics_override_new_move = new_move;
1744                 }
1745         } else if (cmd == AO_CMD_SET_ANIMATION) {
1746                 // TODO: change frames send as v2s32 value
1747                 v2f range = readV2F32(is);
1748                 if (!m_is_local_player) {
1749                         m_animation_range = v2s32((s32)range.X, (s32)range.Y);
1750                         m_animation_speed = readF32(is);
1751                         m_animation_blend = readF32(is);
1752                         // these are sent inverted so we get true when the server sends nothing
1753                         m_animation_loop = !readU8(is);
1754                         updateAnimation();
1755                 } else {
1756                         LocalPlayer *player = m_env->getLocalPlayer();
1757                         if(player->last_animation == NO_ANIM)
1758                         {
1759                                 m_animation_range = v2s32((s32)range.X, (s32)range.Y);
1760                                 m_animation_speed = readF32(is);
1761                                 m_animation_blend = readF32(is);
1762                                 // these are sent inverted so we get true when the server sends nothing
1763                                 m_animation_loop = !readU8(is);
1764                         }
1765                         // update animation only if local animations present
1766                         // and received animation is unknown (except idle animation)
1767                         bool is_known = false;
1768                         for (int i = 1;i<4;i++)
1769                         {
1770                                 if(m_animation_range.Y == player->local_animations[i].Y)
1771                                         is_known = true;
1772                         }
1773                         if(!is_known ||
1774                                         (player->local_animations[1].Y + player->local_animations[2].Y < 1))
1775                         {
1776                                         updateAnimation();
1777                         }
1778                 }
1779         } else if (cmd == AO_CMD_SET_ANIMATION_SPEED) {
1780                 m_animation_speed = readF32(is);
1781                 updateAnimationSpeed();
1782         } else if (cmd == AO_CMD_SET_BONE_POSITION) {
1783                 std::string bone = deSerializeString16(is);
1784                 v3f position = readV3F32(is);
1785                 v3f rotation = readV3F32(is);
1786                 m_bone_position[bone] = core::vector2d<v3f>(position, rotation);
1787
1788                 // updateBonePosition(); now called every step
1789         } else if (cmd == AO_CMD_ATTACH_TO) {
1790                 u16 parent_id = readS16(is);
1791                 std::string bone = deSerializeString16(is);
1792                 v3f position = readV3F32(is);
1793                 v3f rotation = readV3F32(is);
1794                 bool force_visible = readU8(is); // Returns false for EOF
1795
1796                 setAttachment(parent_id, bone, position, rotation, force_visible);
1797         } else if (cmd == AO_CMD_PUNCHED) {
1798                 u16 result_hp = readU16(is);
1799
1800                 // Use this instead of the send damage to not interfere with prediction
1801                 s32 damage = (s32)m_hp - (s32)result_hp;
1802
1803                 m_hp = result_hp;
1804
1805                 if (m_is_local_player)
1806                         m_env->getLocalPlayer()->hp = m_hp;
1807
1808                 if (damage > 0)
1809                 {
1810                         if (m_hp == 0)
1811                         {
1812                                 // TODO: Execute defined fast response
1813                                 // As there is no definition, make a smoke puff
1814                                 ClientSimpleObject *simple = createSmokePuff(
1815                                                 m_smgr, m_env, m_position,
1816                                                 v2f(m_prop.visual_size.X, m_prop.visual_size.Y) * BS);
1817                                 m_env->addSimpleObject(simple);
1818                         } else if (m_reset_textures_timer < 0 && !m_prop.damage_texture_modifier.empty()) {
1819                                 m_reset_textures_timer = 0.05;
1820                                 if(damage >= 2)
1821                                         m_reset_textures_timer += 0.05 * damage;
1822                                 updateTextures(m_current_texture_modifier + m_prop.damage_texture_modifier);
1823                         }
1824                 }
1825
1826                 if (m_hp == 0) {
1827                         // Same as 'Server::DiePlayer'
1828                         clearParentAttachment();
1829                         // Same as 'ObjectRef::l_remove'
1830                         if (!m_is_player)
1831                                 clearChildAttachments();
1832                 }
1833         } else if (cmd == AO_CMD_UPDATE_ARMOR_GROUPS) {
1834                 m_armor_groups.clear();
1835                 int armor_groups_size = readU16(is);
1836                 for(int i=0; i<armor_groups_size; i++)
1837                 {
1838                         std::string name = deSerializeString16(is);
1839                         int rating = readS16(is);
1840                         m_armor_groups[name] = rating;
1841                 }
1842         } else if (cmd == AO_CMD_SPAWN_INFANT) {
1843                 u16 child_id = readU16(is);
1844                 u8 type = readU8(is); // maybe this will be useful later
1845                 (void)type;
1846
1847                 addAttachmentChild(child_id);
1848         } else if (cmd == AO_CMD_OBSOLETE1) {
1849                 // Don't do anything and also don't log a warning
1850         } else {
1851                 warningstream << FUNCTION_NAME
1852                         << ": unknown command or outdated client \""
1853                         << +cmd << "\"" << std::endl;
1854         }
1855 }
1856
1857 /* \pre punchitem != NULL
1858  */
1859 bool GenericCAO::directReportPunch(v3f dir, const ItemStack *punchitem,
1860                 float time_from_last_punch)
1861 {
1862         assert(punchitem);      // pre-condition
1863         const ToolCapabilities *toolcap =
1864                         &punchitem->getToolCapabilities(m_client->idef());
1865         PunchDamageResult result = getPunchDamage(
1866                         m_armor_groups,
1867                         toolcap,
1868                         punchitem,
1869                         time_from_last_punch);
1870
1871         if(result.did_punch && result.damage != 0)
1872         {
1873                 if(result.damage < m_hp)
1874                 {
1875                         m_hp -= result.damage;
1876                 } else {
1877                         m_hp = 0;
1878                         // TODO: Execute defined fast response
1879                         // As there is no definition, make a smoke puff
1880                         ClientSimpleObject *simple = createSmokePuff(
1881                                         m_smgr, m_env, m_position,
1882                                         v2f(m_prop.visual_size.X, m_prop.visual_size.Y) * BS);
1883                         m_env->addSimpleObject(simple);
1884                 }
1885                 if (m_reset_textures_timer < 0 && !m_prop.damage_texture_modifier.empty()) {
1886                         m_reset_textures_timer = 0.05;
1887                         if (result.damage >= 2)
1888                                 m_reset_textures_timer += 0.05 * result.damage;
1889                         updateTextures(m_current_texture_modifier + m_prop.damage_texture_modifier);
1890                 }
1891         }
1892
1893         return false;
1894 }
1895
1896 std::string GenericCAO::debugInfoText()
1897 {
1898         std::ostringstream os(std::ios::binary);
1899         os<<"GenericCAO hp="<<m_hp<<"\n";
1900         os<<"armor={";
1901         for(ItemGroupList::const_iterator i = m_armor_groups.begin();
1902                         i != m_armor_groups.end(); ++i)
1903         {
1904                 os<<i->first<<"="<<i->second<<", ";
1905         }
1906         os<<"}";
1907         return os.str();
1908 }
1909
1910 void GenericCAO::updateMeshCulling()
1911 {
1912         if (!m_is_local_player)
1913                 return;
1914
1915         const bool hidden = m_client->getCamera()->getCameraMode() == CAMERA_MODE_FIRST;
1916
1917         if (m_meshnode && m_prop.visual == "upright_sprite") {
1918                 u32 buffers = m_meshnode->getMesh()->getMeshBufferCount();
1919                 for (u32 i = 0; i < buffers; i++) {
1920                         video::SMaterial &mat = m_meshnode->getMesh()->getMeshBuffer(i)->getMaterial();
1921                         // upright sprite has no backface culling
1922                         mat.setFlag(video::EMF_FRONT_FACE_CULLING, hidden);
1923                 }
1924                 return;
1925         }
1926
1927         scene::ISceneNode *node = getSceneNode();
1928         if (!node)
1929                 return;
1930
1931         if (hidden) {
1932                 // Hide the mesh by culling both front and
1933                 // back faces. Serious hackyness but it works for our
1934                 // purposes. This also preserves the skeletal armature.
1935                 node->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
1936                         true);
1937                 node->setMaterialFlag(video::EMF_FRONT_FACE_CULLING,
1938                         true);
1939         } else {
1940                 // Restore mesh visibility.
1941                 node->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
1942                         m_prop.backface_culling);
1943                 node->setMaterialFlag(video::EMF_FRONT_FACE_CULLING,
1944                         false);
1945         }
1946 }
1947
1948 // Prototype
1949 GenericCAO proto_GenericCAO(NULL, NULL);