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