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