]> git.lizzy.rs Git - dragonfireclient.git/blob - src/client/content_cao.cpp
Add on_object_add callback
[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 || g_settings->getBool("freecam");
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         if (m_client->modsLoaded())
833                 m_client->getScript()->on_object_add(m_id);
834
835         if (m_client->modsLoaded())
836                 m_client->getScript()->on_object_properties_change(m_id);
837 }
838
839 void GenericCAO::updateLight(u32 day_night_ratio)
840 {
841         if (m_glow < 0)
842                 return;
843
844         u8 light_at_pos = 0;
845         bool pos_ok = false;
846
847         v3s16 pos[3];
848         u16 npos = getLightPosition(pos);
849         for (u16 i = 0; i < npos; i++) {
850                 bool this_ok;
851                 MapNode n = m_env->getMap().getNode(pos[i], &this_ok);
852                 if (this_ok) {
853                         u8 this_light = n.getLightBlend(day_night_ratio, m_client->ndef());
854                         light_at_pos = MYMAX(light_at_pos, this_light);
855                         pos_ok = true;
856                 }
857         }
858         if (!pos_ok)
859                 light_at_pos = blend_light(day_night_ratio, LIGHT_SUN, 0);
860
861         u8 light = decode_light(light_at_pos + m_glow);
862         if (g_settings->getBool("fullbright"))
863                 light = 255;
864         if (light != m_last_light) {
865                 m_last_light = light;
866                 setNodeLight(light);
867         }
868 }
869
870 void GenericCAO::setNodeLight(u8 light)
871 {
872         video::SColor color(255, light, light, light);
873
874         if (m_prop.visual == "wielditem" || m_prop.visual == "item") {
875                 if (m_wield_meshnode)
876                         m_wield_meshnode->setNodeLightColor(color);
877                 return;
878         }
879
880         if (m_enable_shaders) {
881                 if (m_prop.visual == "upright_sprite") {
882                         if (!m_meshnode)
883                                 return;
884
885                         scene::IMesh *mesh = m_meshnode->getMesh();
886                         for (u32 i = 0; i < mesh->getMeshBufferCount(); ++i) {
887                                 scene::IMeshBuffer *buf = mesh->getMeshBuffer(i);
888                                 buf->getMaterial().EmissiveColor = color;
889                         }
890                 } else {
891                         scene::ISceneNode *node = getSceneNode();
892                         if (!node)
893                                 return;
894
895                         for (u32 i = 0; i < node->getMaterialCount(); ++i) {
896                                 video::SMaterial &material = node->getMaterial(i);
897                                 material.EmissiveColor = color;
898                         }
899                 }
900         } else {
901                 if (m_meshnode) {
902                         setMeshColor(m_meshnode->getMesh(), color);
903                 } else if (m_animated_meshnode) {
904                         setAnimatedMeshColor(m_animated_meshnode, color);
905                 } else if (m_spritenode) {
906                         m_spritenode->setColor(color);
907                 }
908         }
909 }
910
911 u16 GenericCAO::getLightPosition(v3s16 *pos)
912 {
913         const auto &box = m_prop.collisionbox;
914         pos[0] = floatToInt(m_position + box.MinEdge * BS, BS);
915         pos[1] = floatToInt(m_position + box.MaxEdge * BS, BS);
916
917         // Skip center pos if it falls into the same node as Min or MaxEdge
918         if ((box.MaxEdge - box.MinEdge).getLengthSQ() < 3.0f)
919                 return 2;
920         pos[2] = floatToInt(m_position + box.getCenter() * BS, BS);
921         return 3;
922 }
923
924 void GenericCAO::updateMarker()
925 {
926         if (!m_client->getMinimap())
927                 return;
928
929         if (!m_prop.show_on_minimap) {
930                 if (m_marker)
931                         m_client->getMinimap()->removeMarker(&m_marker);
932                 return;
933         }
934
935         if (m_marker)
936                 return;
937
938         scene::ISceneNode *node = getSceneNode();
939         if (!node)
940                 return;
941         m_marker = m_client->getMinimap()->addMarker(node);
942 }
943
944 void GenericCAO::updateNametag()
945 {
946         //if (m_is_local_player && ! g_settings->getBool("freecam")) // No nametag for local player
947                 //return;
948
949         if (m_prop.nametag.empty() || m_prop.nametag_color.getAlpha() == 0) {
950                 // Delete nametag
951                 if (m_nametag) {
952                         m_client->getCamera()->removeNametag(m_nametag);
953                         m_nametag = nullptr;
954                 }
955                 return;
956         }
957
958         scene::ISceneNode *node = getSceneNode();
959         if (!node)
960                 return;
961
962         v3f pos;
963         pos.Y = m_prop.selectionbox.MaxEdge.Y + 0.3f;
964         if (!m_nametag) {
965                 // Add nametag
966                 m_nametag = m_client->getCamera()->addNametag(node,
967                         m_prop.nametag, m_prop.nametag_color,
968                         m_prop.nametag_bgcolor, pos, nametag_images);
969         } else {
970                 // Update nametag
971                 m_nametag->text = m_prop.nametag;
972                 m_nametag->textcolor = m_prop.nametag_color;
973                 m_nametag->bgcolor = m_prop.nametag_bgcolor;
974                 m_nametag->pos = pos;
975                 m_nametag->setImages(nametag_images);
976         }
977 }
978
979 void GenericCAO::updateNodePos()
980 {
981         if (getParent() != NULL)
982                 return;
983
984         scene::ISceneNode *node = getSceneNode();
985
986         if (node) {
987                 v3s16 camera_offset = m_env->getCameraOffset();
988                 v3f pos = pos_translator.val_current -
989                                 intToFloat(camera_offset, BS);
990                 getPosRotMatrix().setTranslation(pos);
991                 if (node != m_spritenode) { // rotate if not a sprite
992                         v3f rot = m_is_local_player ? -m_rotation : -rot_translator.val_current;
993                         setPitchYawRoll(getPosRotMatrix(), rot);
994                 }
995         }
996 }
997
998 void GenericCAO::step(float dtime, ClientEnvironment *env)
999 {
1000         // Handle model animations and update positions instantly to prevent lags
1001         if (m_is_local_player) {
1002                 LocalPlayer *player = m_env->getLocalPlayer();
1003                 m_position = player->getLegitPosition();
1004                 pos_translator.val_current = m_position;
1005                 if (! g_settings->getBool("freecam")) {
1006                         m_rotation.Y = wrapDegrees_0_360(player->getYaw());
1007                         rot_translator.val_current = m_rotation;
1008                 }
1009
1010                 if (m_is_visible) {
1011                         int old_anim = player->last_animation;
1012                         float old_anim_speed = player->last_animation_speed;
1013                         m_velocity = v3f(0,0,0);
1014                         m_acceleration = v3f(0,0,0);
1015                         const PlayerControl &controls = player->getPlayerControl();
1016
1017                         bool walking = false;
1018                         if ((controls.up || controls.down || controls.left || controls.right ||
1019                                         controls.forw_move_joystick_axis != 0.f ||
1020                                         controls.sidew_move_joystick_axis != 0.f) && ! g_settings->getBool("freecam"))
1021                                 walking = true;
1022
1023                         f32 new_speed = player->local_animation_speed;
1024                         v2s32 new_anim = v2s32(0,0);
1025                         bool allow_update = false;
1026
1027                         // increase speed if using fast or flying fast
1028                         if(((g_settings->getBool("fast_move") &&
1029                                         m_client->checkLocalPrivilege("fast")) &&
1030                                         (controls.aux1 ||
1031                                         (!player->touching_ground &&
1032                                         g_settings->getBool("free_move") &&
1033                                         m_client->checkLocalPrivilege("fly")))) || g_settings->getBool("freecam"))
1034                                         new_speed *= 1.5;
1035                         // slowdown speed if sneeking
1036                         if (controls.sneak && walking && ! g_settings->getBool("no_slow"))
1037                                 new_speed /= 2;
1038
1039                         if (walking && (controls.dig || controls.place)) {
1040                                 new_anim = player->local_animations[3];
1041                                 player->last_animation = WD_ANIM;
1042                         } else if (walking) {
1043                                 new_anim = player->local_animations[1];
1044                                 player->last_animation = WALK_ANIM;
1045                         } else if (controls.dig || controls.place) {
1046                                 new_anim = player->local_animations[2];
1047                                 player->last_animation = DIG_ANIM;
1048                         }
1049
1050                         // Apply animations if input detected and not attached
1051                         // or set idle animation
1052                         if ((new_anim.X + new_anim.Y) > 0 && !getParent()) {
1053                                 allow_update = true;
1054                                 m_animation_range = new_anim;
1055                                 m_animation_speed = new_speed;
1056                                 player->last_animation_speed = m_animation_speed;
1057                         } else {
1058                                 player->last_animation = NO_ANIM;
1059
1060                                 if (old_anim != NO_ANIM) {
1061                                         m_animation_range = player->local_animations[0];
1062                                         updateAnimation();
1063                                 }
1064                         }
1065
1066                         // Update local player animations
1067                         if ((player->last_animation != old_anim ||
1068                                         m_animation_speed != old_anim_speed) &&
1069                                         player->last_animation != NO_ANIM && allow_update)
1070                                 updateAnimation();
1071
1072                 }
1073         }
1074
1075         if (m_visuals_expired && m_smgr) {
1076                 m_visuals_expired = false;
1077
1078                 // Attachments, part 1: All attached objects must be unparented first,
1079                 // or Irrlicht causes a segmentation fault
1080                 for (u16 cao_id : m_attachment_child_ids) {
1081                         ClientActiveObject *obj = m_env->getActiveObject(cao_id);
1082                         if (obj) {
1083                                 scene::ISceneNode *child_node = obj->getSceneNode();
1084                                 // The node's parent is always an IDummyTraformationSceneNode,
1085                                 // so we need to reparent that one instead.
1086                                 if (child_node)
1087                                         child_node->getParent()->setParent(m_smgr->getRootSceneNode());
1088                         }
1089                 }
1090
1091                 removeFromScene(false);
1092                 addToScene(m_client->tsrc());
1093
1094                 // Attachments, part 2: Now that the parent has been refreshed, put its attachments back
1095                 for (u16 cao_id : m_attachment_child_ids) {
1096                         ClientActiveObject *obj = m_env->getActiveObject(cao_id);
1097                         if (obj)
1098                                 obj->updateAttachments();
1099                 }
1100         }
1101
1102         // Make sure m_is_visible is always applied
1103         scene::ISceneNode *node = getSceneNode();
1104         if (node)
1105                 node->setVisible(m_is_visible);
1106
1107         if(getParent() != NULL) // Attachments should be glued to their parent by Irrlicht
1108         {
1109                 // Set these for later
1110                 m_position = getPosition();
1111                 m_velocity = v3f(0,0,0);
1112                 m_acceleration = v3f(0,0,0);
1113                 pos_translator.val_current = m_position;
1114                 pos_translator.val_target = m_position;
1115         } else {
1116                 rot_translator.translate(dtime);
1117                 v3f lastpos = pos_translator.val_current;
1118
1119                 if(m_prop.physical)
1120                 {
1121                         aabb3f box = m_prop.collisionbox;
1122                         box.MinEdge *= BS;
1123                         box.MaxEdge *= BS;
1124                         collisionMoveResult moveresult;
1125                         f32 pos_max_d = BS*0.125; // Distance per iteration
1126                         v3f p_pos = m_position;
1127                         v3f p_velocity = m_velocity;
1128                         moveresult = collisionMoveSimple(env,env->getGameDef(),
1129                                         pos_max_d, box, m_prop.stepheight, dtime,
1130                                         &p_pos, &p_velocity, m_acceleration,
1131                                         this, m_prop.collideWithObjects);
1132                         // Apply results
1133                         m_position = p_pos;
1134                         m_velocity = p_velocity;
1135
1136                         bool is_end_position = moveresult.collides;
1137                         pos_translator.update(m_position, is_end_position, dtime);
1138                 } else {
1139                         m_position += dtime * m_velocity + 0.5 * dtime * dtime * m_acceleration;
1140                         m_velocity += dtime * m_acceleration;
1141                         pos_translator.update(m_position, pos_translator.aim_is_end,
1142                                         pos_translator.anim_time);
1143                 }
1144                 pos_translator.translate(dtime);
1145                 updateNodePos();
1146
1147                 float moved = lastpos.getDistanceFrom(pos_translator.val_current);
1148                 m_step_distance_counter += moved;
1149                 if (m_step_distance_counter > 1.5f * BS) {
1150                         m_step_distance_counter = 0.0f;
1151                         if (!m_is_local_player && m_prop.makes_footstep_sound) {
1152                                 const NodeDefManager *ndef = m_client->ndef();
1153                                 v3s16 p = floatToInt(getPosition() +
1154                                         v3f(0.0f, (m_prop.collisionbox.MinEdge.Y - 0.5f) * BS, 0.0f), BS);
1155                                 MapNode n = m_env->getMap().getNode(p);
1156                                 SimpleSoundSpec spec = ndef->get(n).sound_footstep;
1157                                 // Reduce footstep gain, as non-local-player footsteps are
1158                                 // somehow louder.
1159                                 spec.gain *= 0.6f;
1160                                 m_client->sound()->playSoundAt(spec, false, getPosition());
1161                         }
1162                 }
1163         }
1164
1165         m_anim_timer += dtime;
1166         if(m_anim_timer >= m_anim_framelength)
1167         {
1168                 m_anim_timer -= m_anim_framelength;
1169                 m_anim_frame++;
1170                 if(m_anim_frame >= m_anim_num_frames)
1171                         m_anim_frame = 0;
1172         }
1173
1174         updateTexturePos();
1175
1176         if(m_reset_textures_timer >= 0)
1177         {
1178                 m_reset_textures_timer -= dtime;
1179                 if(m_reset_textures_timer <= 0) {
1180                         m_reset_textures_timer = -1;
1181                         updateTextures(m_previous_texture_modifier);
1182                 }
1183         }
1184
1185         if (!getParent() && node && fabs(m_prop.automatic_rotate) > 0.001f) {
1186                 // This is the child node's rotation. It is only used for automatic_rotate.
1187                 v3f local_rot = node->getRotation();
1188                 local_rot.Y = modulo360f(local_rot.Y - dtime * core::RADTODEG *
1189                                 m_prop.automatic_rotate);
1190                 node->setRotation(local_rot);
1191         }
1192
1193         if (!getParent() && m_prop.automatic_face_movement_dir &&
1194                         (fabs(m_velocity.Z) > 0.001f || fabs(m_velocity.X) > 0.001f)) {
1195                 float target_yaw = atan2(m_velocity.Z, m_velocity.X) * 180 / M_PI
1196                                 + m_prop.automatic_face_movement_dir_offset;
1197                 float max_rotation_per_sec =
1198                                 m_prop.automatic_face_movement_max_rotation_per_sec;
1199
1200                 if (max_rotation_per_sec > 0) {
1201                         wrappedApproachShortest(m_rotation.Y, target_yaw,
1202                                 dtime * max_rotation_per_sec, 360.f);
1203                 } else {
1204                         // Negative values of max_rotation_per_sec mean disabled.
1205                         m_rotation.Y = target_yaw;
1206                 }
1207
1208                 rot_translator.val_current = m_rotation;
1209                 updateNodePos();
1210         }
1211
1212         if (m_animated_meshnode) {
1213                 // Everything must be updated; the whole transform
1214                 // chain as well as the animated mesh node.
1215                 // Otherwise, bone attachments would be relative to
1216                 // a position that's one frame old.
1217                 if (m_matrixnode)
1218                         updatePositionRecursive(m_matrixnode);
1219                 m_animated_meshnode->updateAbsolutePosition();
1220                 m_animated_meshnode->animateJoints();
1221                 updateBonePosition();
1222         }
1223 }
1224
1225 void GenericCAO::updateTexturePos()
1226 {
1227         if(m_spritenode)
1228         {
1229                 scene::ICameraSceneNode* camera =
1230                                 m_spritenode->getSceneManager()->getActiveCamera();
1231                 if(!camera)
1232                         return;
1233                 v3f cam_to_entity = m_spritenode->getAbsolutePosition()
1234                                 - camera->getAbsolutePosition();
1235                 cam_to_entity.normalize();
1236
1237                 int row = m_tx_basepos.Y;
1238                 int col = m_tx_basepos.X;
1239
1240                 // Yawpitch goes rightwards
1241                 if (m_tx_select_horiz_by_yawpitch) {
1242                         if (cam_to_entity.Y > 0.75)
1243                                 col += 5;
1244                         else if (cam_to_entity.Y < -0.75)
1245                                 col += 4;
1246                         else {
1247                                 float mob_dir =
1248                                                 atan2(cam_to_entity.Z, cam_to_entity.X) / M_PI * 180.;
1249                                 float dir = mob_dir - m_rotation.Y;
1250                                 dir = wrapDegrees_180(dir);
1251                                 if (std::fabs(wrapDegrees_180(dir - 0)) <= 45.1f)
1252                                         col += 2;
1253                                 else if(std::fabs(wrapDegrees_180(dir - 90)) <= 45.1f)
1254                                         col += 3;
1255                                 else if(std::fabs(wrapDegrees_180(dir - 180)) <= 45.1f)
1256                                         col += 0;
1257                                 else if(std::fabs(wrapDegrees_180(dir + 90)) <= 45.1f)
1258                                         col += 1;
1259                                 else
1260                                         col += 4;
1261                         }
1262                 }
1263
1264                 // Animation goes downwards
1265                 row += m_anim_frame;
1266
1267                 float txs = m_tx_size.X;
1268                 float tys = m_tx_size.Y;
1269                 setBillboardTextureMatrix(m_spritenode, txs, tys, col, row);
1270         }
1271
1272         else if (m_meshnode) {
1273                 if (m_prop.visual == "upright_sprite") {
1274                         int row = m_tx_basepos.Y;
1275                         int col = m_tx_basepos.X;
1276
1277                         // Animation goes downwards
1278                         row += m_anim_frame;
1279
1280                         const auto &tx = m_tx_size;
1281                         v2f t[4] = { // cf. vertices in GenericCAO::addToScene()
1282                                 tx * v2f(col+1, row+1),
1283                                 tx * v2f(col, row+1),
1284                                 tx * v2f(col, row),
1285                                 tx * v2f(col+1, row),
1286                         };
1287                         auto mesh = m_meshnode->getMesh();
1288                         setMeshBufferTextureCoords(mesh->getMeshBuffer(0), t, 4);
1289                         setMeshBufferTextureCoords(mesh->getMeshBuffer(1), t, 4);
1290                 }
1291         }
1292 }
1293
1294 // Do not pass by reference, see header.
1295 void GenericCAO::updateTextures(std::string mod)
1296 {
1297         ITextureSource *tsrc = m_client->tsrc();
1298
1299         bool use_trilinear_filter = g_settings->getBool("trilinear_filter");
1300         bool use_bilinear_filter = g_settings->getBool("bilinear_filter");
1301         bool use_anisotropic_filter = g_settings->getBool("anisotropic_filter");
1302
1303         m_previous_texture_modifier = m_current_texture_modifier;
1304         m_current_texture_modifier = mod;
1305         m_glow = m_prop.glow;
1306
1307         if (m_spritenode) {
1308                 if (m_prop.visual == "sprite") {
1309                         std::string texturestring = "unknown_node.png";
1310                         if (!m_prop.textures.empty())
1311                                 texturestring = m_prop.textures[0];
1312                         texturestring += mod;
1313                         m_spritenode->getMaterial(0).MaterialType = m_material_type;
1314                         m_spritenode->getMaterial(0).MaterialTypeParam = 0.5f;
1315                         m_spritenode->setMaterialTexture(0,
1316                                         tsrc->getTextureForMesh(texturestring));
1317
1318                         // This allows setting per-material colors. However, until a real lighting
1319                         // system is added, the code below will have no effect. Once MineTest
1320                         // has directional lighting, it should work automatically.
1321                         if (!m_prop.colors.empty()) {
1322                                 m_spritenode->getMaterial(0).AmbientColor = m_prop.colors[0];
1323                                 m_spritenode->getMaterial(0).DiffuseColor = m_prop.colors[0];
1324                                 m_spritenode->getMaterial(0).SpecularColor = m_prop.colors[0];
1325                         }
1326
1327                         m_spritenode->getMaterial(0).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1328                         m_spritenode->getMaterial(0).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1329                         m_spritenode->getMaterial(0).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1330                 }
1331         }
1332
1333         else if (m_animated_meshnode) {
1334                 if (m_prop.visual == "mesh") {
1335                         for (u32 i = 0; i < m_prop.textures.size() &&
1336                                         i < m_animated_meshnode->getMaterialCount(); ++i) {
1337                                 std::string texturestring = m_prop.textures[i];
1338                                 if (texturestring.empty())
1339                                         continue; // Empty texture string means don't modify that material
1340                                 texturestring += mod;
1341                                 video::ITexture* texture = tsrc->getTextureForMesh(texturestring);
1342                                 if (!texture) {
1343                                         errorstream<<"GenericCAO::updateTextures(): Could not load texture "<<texturestring<<std::endl;
1344                                         continue;
1345                                 }
1346
1347                                 // Set material flags and texture
1348                                 video::SMaterial& material = m_animated_meshnode->getMaterial(i);
1349                                 material.MaterialType = m_material_type;
1350                                 material.MaterialTypeParam = 0.5f;
1351                                 material.TextureLayer[0].Texture = texture;
1352                                 material.setFlag(video::EMF_LIGHTING, true);
1353                                 material.setFlag(video::EMF_BILINEAR_FILTER, false);
1354                                 material.setFlag(video::EMF_BACK_FACE_CULLING, m_prop.backface_culling);
1355
1356                                 // don't filter low-res textures, makes them look blurry
1357                                 // player models have a res of 64
1358                                 const core::dimension2d<u32> &size = texture->getOriginalSize();
1359                                 const u32 res = std::min(size.Height, size.Width);
1360                                 use_trilinear_filter &= res > 64;
1361                                 use_bilinear_filter &= res > 64;
1362
1363                                 m_animated_meshnode->getMaterial(i)
1364                                                 .setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1365                                 m_animated_meshnode->getMaterial(i)
1366                                                 .setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1367                                 m_animated_meshnode->getMaterial(i)
1368                                                 .setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1369                         }
1370                         for (u32 i = 0; i < m_prop.colors.size() &&
1371                         i < m_animated_meshnode->getMaterialCount(); ++i)
1372                         {
1373                                 // This allows setting per-material colors. However, until a real lighting
1374                                 // system is added, the code below will have no effect. Once MineTest
1375                                 // has directional lighting, it should work automatically.
1376                                 m_animated_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i];
1377                                 m_animated_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i];
1378                                 m_animated_meshnode->getMaterial(i).SpecularColor = m_prop.colors[i];
1379                         }
1380                 }
1381         }
1382
1383         else if (m_meshnode) {
1384                 if(m_prop.visual == "cube")
1385                 {
1386                         for (u32 i = 0; i < 6; ++i)
1387                         {
1388                                 std::string texturestring = "unknown_node.png";
1389                                 if(m_prop.textures.size() > i)
1390                                         texturestring = m_prop.textures[i];
1391                                 texturestring += mod;
1392
1393
1394                                 // Set material flags and texture
1395                                 video::SMaterial& material = m_meshnode->getMaterial(i);
1396                                 material.MaterialType = m_material_type;
1397                                 material.MaterialTypeParam = 0.5f;
1398                                 material.setFlag(video::EMF_LIGHTING, false);
1399                                 material.setFlag(video::EMF_BILINEAR_FILTER, false);
1400                                 material.setTexture(0,
1401                                                 tsrc->getTextureForMesh(texturestring));
1402                                 material.getTextureMatrix(0).makeIdentity();
1403
1404                                 // This allows setting per-material colors. However, until a real lighting
1405                                 // system is added, the code below will have no effect. Once MineTest
1406                                 // has directional lighting, it should work automatically.
1407                                 if(m_prop.colors.size() > i)
1408                                 {
1409                                         m_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i];
1410                                         m_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i];
1411                                         m_meshnode->getMaterial(i).SpecularColor = m_prop.colors[i];
1412                                 }
1413
1414                                 m_meshnode->getMaterial(i).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1415                                 m_meshnode->getMaterial(i).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1416                                 m_meshnode->getMaterial(i).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1417                         }
1418                 } else if (m_prop.visual == "upright_sprite") {
1419                         scene::IMesh *mesh = m_meshnode->getMesh();
1420                         {
1421                                 std::string tname = "unknown_object.png";
1422                                 if (!m_prop.textures.empty())
1423                                         tname = m_prop.textures[0];
1424                                 tname += mod;
1425                                 scene::IMeshBuffer *buf = mesh->getMeshBuffer(0);
1426                                 buf->getMaterial().setTexture(0,
1427                                                 tsrc->getTextureForMesh(tname));
1428
1429                                 // This allows setting per-material colors. However, until a real lighting
1430                                 // system is added, the code below will have no effect. Once MineTest
1431                                 // has directional lighting, it should work automatically.
1432                                 if(!m_prop.colors.empty()) {
1433                                         buf->getMaterial().AmbientColor = m_prop.colors[0];
1434                                         buf->getMaterial().DiffuseColor = m_prop.colors[0];
1435                                         buf->getMaterial().SpecularColor = m_prop.colors[0];
1436                                 }
1437
1438                                 buf->getMaterial().setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1439                                 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1440                                 buf->getMaterial().setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1441                         }
1442                         {
1443                                 std::string tname = "unknown_object.png";
1444                                 if (m_prop.textures.size() >= 2)
1445                                         tname = m_prop.textures[1];
1446                                 else if (!m_prop.textures.empty())
1447                                         tname = m_prop.textures[0];
1448                                 tname += mod;
1449                                 scene::IMeshBuffer *buf = mesh->getMeshBuffer(1);
1450                                 buf->getMaterial().setTexture(0,
1451                                                 tsrc->getTextureForMesh(tname));
1452
1453                                 // This allows setting per-material colors. However, until a real lighting
1454                                 // system is added, the code below will have no effect. Once MineTest
1455                                 // has directional lighting, it should work automatically.
1456                                 if (m_prop.colors.size() >= 2) {
1457                                         buf->getMaterial().AmbientColor = m_prop.colors[1];
1458                                         buf->getMaterial().DiffuseColor = m_prop.colors[1];
1459                                         buf->getMaterial().SpecularColor = m_prop.colors[1];
1460                                 } else if (!m_prop.colors.empty()) {
1461                                         buf->getMaterial().AmbientColor = m_prop.colors[0];
1462                                         buf->getMaterial().DiffuseColor = m_prop.colors[0];
1463                                         buf->getMaterial().SpecularColor = m_prop.colors[0];
1464                                 }
1465
1466                                 buf->getMaterial().setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1467                                 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1468                                 buf->getMaterial().setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1469                         }
1470                         // Set mesh color (only if lighting is disabled)
1471                         if (!m_prop.colors.empty() && m_glow < 0)
1472                                 setMeshColor(mesh, m_prop.colors[0]);
1473                 }
1474         }
1475         // Prevent showing the player after changing texture
1476         if (m_is_local_player)
1477                 updateMeshCulling();
1478 }
1479
1480 void GenericCAO::updateAnimation()
1481 {
1482         if (!m_animated_meshnode)
1483                 return;
1484
1485         if (m_animated_meshnode->getStartFrame() != m_animation_range.X ||
1486                 m_animated_meshnode->getEndFrame() != m_animation_range.Y)
1487                         m_animated_meshnode->setFrameLoop(m_animation_range.X, m_animation_range.Y);
1488         if (m_animated_meshnode->getAnimationSpeed() != m_animation_speed)
1489                 m_animated_meshnode->setAnimationSpeed(m_animation_speed);
1490         m_animated_meshnode->setTransitionTime(m_animation_blend);
1491 // Requires Irrlicht 1.8 or greater
1492 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR > 1
1493         if (m_animated_meshnode->getLoopMode() != m_animation_loop)
1494                 m_animated_meshnode->setLoopMode(m_animation_loop);
1495 #endif
1496 }
1497
1498 void GenericCAO::updateAnimationSpeed()
1499 {
1500         if (!m_animated_meshnode)
1501                 return;
1502
1503         m_animated_meshnode->setAnimationSpeed(m_animation_speed);
1504 }
1505
1506 void GenericCAO::updateBonePosition()
1507 {
1508         if (m_bone_position.empty() || !m_animated_meshnode)
1509                 return;
1510
1511         m_animated_meshnode->setJointMode(irr::scene::EJUOR_CONTROL); // To write positions to the mesh on render
1512         for (auto &it : m_bone_position) {
1513                 std::string bone_name = it.first;
1514                 irr::scene::IBoneSceneNode* bone = m_animated_meshnode->getJointNode(bone_name.c_str());
1515                 if (bone) {
1516                         bone->setPosition(it.second.X);
1517                         bone->setRotation(it.second.Y);
1518                 }
1519         }
1520
1521         // search through bones to find mistakenly rotated bones due to bug in Irrlicht
1522         for (u32 i = 0; i < m_animated_meshnode->getJointCount(); ++i) {
1523                 irr::scene::IBoneSceneNode *bone = m_animated_meshnode->getJointNode(i);
1524                 if (!bone)
1525                         continue;
1526
1527                 //If bone is manually positioned there is no need to perform the bug check
1528                 bool skip = false;
1529                 for (auto &it : m_bone_position) {
1530                         if (it.first == bone->getName()) {
1531                                 skip = true;
1532                                 break;
1533                         }
1534                 }
1535                 if (skip)
1536                         continue;
1537
1538                 // Workaround for Irrlicht bug
1539                 // We check each bone to see if it has been rotated ~180deg from its expected position due to a bug in Irricht
1540                 // when using EJUOR_CONTROL joint control. If the bug is detected we update the bone to the proper position
1541                 // and update the bones transformation.
1542                 v3f bone_rot = bone->getRelativeTransformation().getRotationDegrees();
1543                 float offset = fabsf(bone_rot.X - bone->getRotation().X);
1544                 if (offset > 179.9f && offset < 180.1f) {
1545                         bone->setRotation(bone_rot);
1546                         bone->updateAbsolutePosition();
1547                 }
1548         }
1549         // The following is needed for set_bone_pos to propagate to
1550         // attached objects correctly.
1551         // Irrlicht ought to do this, but doesn't when using EJUOR_CONTROL.
1552         for (u32 i = 0; i < m_animated_meshnode->getJointCount(); ++i) {
1553                 auto bone = m_animated_meshnode->getJointNode(i);
1554                 // Look for the root bone.
1555                 if (bone && bone->getParent() == m_animated_meshnode) {
1556                         // Update entire skeleton.
1557                         bone->updateAbsolutePositionOfAllChildren();
1558                         break;
1559                 }
1560         }
1561 }
1562
1563 void GenericCAO::updateAttachments()
1564 {
1565         ClientActiveObject *parent = getParent();
1566
1567         m_attached_to_local = parent && parent->isLocalPlayer();
1568
1569         /*
1570         Following cases exist:
1571                 m_attachment_parent_id == 0 && !parent
1572                         This object is not attached
1573                 m_attachment_parent_id != 0 && parent
1574                         This object is attached
1575                 m_attachment_parent_id != 0 && !parent
1576                         This object will be attached as soon the parent is known
1577                 m_attachment_parent_id == 0 && parent
1578                         Impossible case
1579         */
1580
1581         if (!parent) { // Detach or don't attach
1582                 if (m_matrixnode) {
1583                         v3s16 camera_offset = m_env->getCameraOffset();
1584                         v3f old_pos = getPosition();
1585
1586                         m_matrixnode->setParent(m_smgr->getRootSceneNode());
1587                         getPosRotMatrix().setTranslation(old_pos - intToFloat(camera_offset, BS));
1588                         m_matrixnode->updateAbsolutePosition();
1589                 }
1590         }
1591         else // Attach
1592         {
1593                 parent->updateAttachments();
1594                 scene::ISceneNode *parent_node = parent->getSceneNode();
1595                 scene::IAnimatedMeshSceneNode *parent_animated_mesh_node =
1596                                 parent->getAnimatedMeshSceneNode();
1597                 if (parent_animated_mesh_node && !m_attachment_bone.empty()) {
1598                         parent_node = parent_animated_mesh_node->getJointNode(m_attachment_bone.c_str());
1599                 }
1600
1601                 if (m_matrixnode && parent_node) {
1602                         m_matrixnode->setParent(parent_node);
1603                         parent_node->updateAbsolutePosition();
1604                         getPosRotMatrix().setTranslation(m_attachment_position);
1605                         //setPitchYawRoll(getPosRotMatrix(), m_attachment_rotation);
1606                         // use Irrlicht eulers instead
1607                         getPosRotMatrix().setRotationDegrees(m_attachment_rotation);
1608                         m_matrixnode->updateAbsolutePosition();
1609                 }
1610         }
1611 }
1612
1613 bool GenericCAO::visualExpiryRequired(const ObjectProperties &new_) const
1614 {
1615         const ObjectProperties &old = m_prop;
1616         /* Visuals do not need to be expired for:
1617          * - nametag props: handled by updateNametag()
1618          * - textures:      handled by updateTextures()
1619          * - sprite props:  handled by updateTexturePos()
1620          * - glow:          handled by updateLight()
1621          * - any other properties that do not change appearance
1622          */
1623
1624         bool uses_legacy_texture = new_.wield_item.empty() &&
1625                 (new_.visual == "wielditem" || new_.visual == "item");
1626         // Ordered to compare primitive types before std::vectors
1627         return old.backface_culling != new_.backface_culling ||
1628                 old.is_visible != new_.is_visible ||
1629                 old.mesh != new_.mesh ||
1630                 old.shaded != new_.shaded ||
1631                 old.use_texture_alpha != new_.use_texture_alpha ||
1632                 old.visual != new_.visual ||
1633                 old.visual_size != new_.visual_size ||
1634                 old.wield_item != new_.wield_item ||
1635                 old.colors != new_.colors ||
1636                 (uses_legacy_texture && old.textures != new_.textures);
1637 }
1638
1639 void GenericCAO::setProperties(ObjectProperties newprops)
1640 {
1641         // Check what exactly changed
1642         bool expire_visuals = visualExpiryRequired(newprops);
1643         bool textures_changed = m_prop.textures != newprops.textures;
1644
1645         // Apply changes
1646         m_prop = std::move(newprops);
1647
1648         m_selection_box = m_prop.selectionbox;
1649         m_selection_box.MinEdge *= BS;
1650         m_selection_box.MaxEdge *= BS;
1651
1652         m_tx_size.X = 1.0f / m_prop.spritediv.X;
1653         m_tx_size.Y = 1.0f / m_prop.spritediv.Y;
1654
1655         if(!m_initial_tx_basepos_set){
1656                 m_initial_tx_basepos_set = true;
1657                 m_tx_basepos = m_prop.initial_sprite_basepos;
1658         }
1659         if (m_is_local_player) {
1660                 LocalPlayer *player = m_env->getLocalPlayer();
1661                 player->makes_footstep_sound = m_prop.makes_footstep_sound;
1662                 aabb3f collision_box = m_prop.collisionbox;
1663                 collision_box.MinEdge *= BS;
1664                 collision_box.MaxEdge *= BS;
1665                 player->setCollisionbox(collision_box);
1666                 player->setEyeHeight(m_prop.eye_height);
1667                 player->setZoomFOV(m_prop.zoom_fov);
1668         }
1669
1670         if ((m_is_player && !m_is_local_player) && m_prop.nametag.empty())
1671                 m_prop.nametag = m_name;
1672         if (m_is_local_player)
1673                 m_prop.show_on_minimap = false;
1674
1675         if (expire_visuals) {
1676                 expireVisuals();
1677         } else {
1678                 infostream << "GenericCAO: properties updated but expiring visuals"
1679                         << " not necessary" << std::endl;
1680                 if (textures_changed) {
1681                         // don't update while punch texture modifier is active
1682                         if (m_reset_textures_timer < 0)
1683                                 updateTextures(m_current_texture_modifier);
1684                 }
1685                 updateNametag();
1686                 updateMarker();
1687         }
1688 }
1689
1690 void GenericCAO::processMessage(const std::string &data)
1691 {
1692         //infostream<<"GenericCAO: Got message"<<std::endl;
1693         std::istringstream is(data, std::ios::binary);
1694         // command
1695         u8 cmd = readU8(is);
1696         if (cmd == AO_CMD_SET_PROPERTIES) {
1697                 ObjectProperties newprops;
1698                 newprops.show_on_minimap = m_is_player; // default
1699
1700                 newprops.deSerialize(is);
1701                 setProperties(newprops);
1702
1703                 // notify CSM
1704                 if (m_client->modsLoaded())
1705                         m_client->getScript()->on_object_properties_change(m_id);
1706
1707         } else if (cmd == AO_CMD_UPDATE_POSITION) {
1708                 // Not sent by the server if this object is an attachment.
1709                 // We might however get here if the server notices the object being detached before the client.
1710                 m_position = readV3F32(is);
1711                 m_velocity = readV3F32(is);
1712                 m_acceleration = readV3F32(is);
1713                 m_rotation = readV3F32(is);
1714
1715                 m_rotation = wrapDegrees_0_360_v3f(m_rotation);
1716                 bool do_interpolate = readU8(is);
1717                 bool is_end_position = readU8(is);
1718                 float update_interval = readF32(is);
1719
1720                 // Place us a bit higher if we're physical, to not sink into
1721                 // the ground due to sucky collision detection...
1722                 if(m_prop.physical)
1723                         m_position += v3f(0,0.002,0);
1724
1725                 if(getParent() != NULL) // Just in case
1726                         return;
1727
1728                 if(do_interpolate)
1729                 {
1730                         if(!m_prop.physical)
1731                                 pos_translator.update(m_position, is_end_position, update_interval);
1732                 } else {
1733                         pos_translator.init(m_position);
1734                 }
1735                 rot_translator.update(m_rotation, false, update_interval);
1736                 updateNodePos();
1737         } else if (cmd == AO_CMD_SET_TEXTURE_MOD) {
1738                 std::string mod = deSerializeString16(is);
1739
1740                 // immediately reset a engine issued texture modifier if a mod sends a different one
1741                 if (m_reset_textures_timer > 0) {
1742                         m_reset_textures_timer = -1;
1743                         updateTextures(m_previous_texture_modifier);
1744                 }
1745                 updateTextures(mod);
1746         } else if (cmd == AO_CMD_SET_SPRITE) {
1747                 v2s16 p = readV2S16(is);
1748                 int num_frames = readU16(is);
1749                 float framelength = readF32(is);
1750                 bool select_horiz_by_yawpitch = readU8(is);
1751
1752                 m_tx_basepos = p;
1753                 m_anim_num_frames = num_frames;
1754                 m_anim_framelength = framelength;
1755                 m_tx_select_horiz_by_yawpitch = select_horiz_by_yawpitch;
1756
1757                 updateTexturePos();
1758         } else if (cmd == AO_CMD_SET_PHYSICS_OVERRIDE) {
1759                 float override_speed = readF32(is);
1760                 float override_jump = readF32(is);
1761                 float override_gravity = readF32(is);
1762                 // these are sent inverted so we get true when the server sends nothing
1763                 bool sneak = !readU8(is);
1764                 bool sneak_glitch = !readU8(is);
1765                 bool new_move = !readU8(is);
1766
1767
1768                 if(m_is_local_player)
1769                 {
1770                         Client *client = m_env->getGameDef();
1771
1772                         if (client->modsLoaded() && client->getScript()->on_recieve_physics_override(override_speed, override_jump, override_gravity, sneak, sneak_glitch, new_move))
1773                                 return;
1774
1775                         LocalPlayer *player = m_env->getLocalPlayer();
1776                         player->physics_override_speed = override_speed;
1777                         player->physics_override_jump = override_jump;
1778                         player->physics_override_gravity = override_gravity;
1779                         player->physics_override_sneak = sneak;
1780                         player->physics_override_sneak_glitch = sneak_glitch;
1781                         player->physics_override_new_move = new_move;
1782                 }
1783         } else if (cmd == AO_CMD_SET_ANIMATION) {
1784                 // TODO: change frames send as v2s32 value
1785                 v2f range = readV2F32(is);
1786                 if (!m_is_local_player) {
1787                         m_animation_range = v2s32((s32)range.X, (s32)range.Y);
1788                         m_animation_speed = readF32(is);
1789                         m_animation_blend = readF32(is);
1790                         // these are sent inverted so we get true when the server sends nothing
1791                         m_animation_loop = !readU8(is);
1792                         updateAnimation();
1793                 } else {
1794                         LocalPlayer *player = m_env->getLocalPlayer();
1795                         if(player->last_animation == NO_ANIM)
1796                         {
1797                                 m_animation_range = v2s32((s32)range.X, (s32)range.Y);
1798                                 m_animation_speed = readF32(is);
1799                                 m_animation_blend = readF32(is);
1800                                 // these are sent inverted so we get true when the server sends nothing
1801                                 m_animation_loop = !readU8(is);
1802                         }
1803                         // update animation only if local animations present
1804                         // and received animation is unknown (except idle animation)
1805                         bool is_known = false;
1806                         for (int i = 1;i<4;i++)
1807                         {
1808                                 if(m_animation_range.Y == player->local_animations[i].Y)
1809                                         is_known = true;
1810                         }
1811                         if(!is_known ||
1812                                         (player->local_animations[1].Y + player->local_animations[2].Y < 1))
1813                         {
1814                                         updateAnimation();
1815                         }
1816                 }
1817         } else if (cmd == AO_CMD_SET_ANIMATION_SPEED) {
1818                 m_animation_speed = readF32(is);
1819                 updateAnimationSpeed();
1820         } else if (cmd == AO_CMD_SET_BONE_POSITION) {
1821                 std::string bone = deSerializeString16(is);
1822                 v3f position = readV3F32(is);
1823                 v3f rotation = readV3F32(is);
1824                 m_bone_position[bone] = core::vector2d<v3f>(position, rotation);
1825
1826                 // updateBonePosition(); now called every step
1827         } else if (cmd == AO_CMD_ATTACH_TO) {
1828                 u16 parent_id = readS16(is);
1829                 std::string bone = deSerializeString16(is);
1830                 v3f position = readV3F32(is);
1831                 v3f rotation = readV3F32(is);
1832                 bool force_visible = readU8(is); // Returns false for EOF
1833
1834                 setAttachment(parent_id, bone, position, rotation, force_visible);
1835         } else if (cmd == AO_CMD_PUNCHED) {
1836                 u16 result_hp = readU16(is);
1837
1838                 // Use this instead of the send damage to not interfere with prediction
1839                 s32 damage = (s32)m_hp - (s32)result_hp;
1840
1841                 m_hp = result_hp;
1842
1843                 if (m_is_local_player)
1844                         m_env->getLocalPlayer()->hp = m_hp;
1845
1846                 if (damage > 0)
1847                 {
1848                         if (m_hp == 0)
1849                         {
1850                                 // TODO: Execute defined fast response
1851                                 // As there is no definition, make a smoke puff
1852                                 ClientSimpleObject *simple = createSmokePuff(
1853                                                 m_smgr, m_env, m_position,
1854                                                 v2f(m_prop.visual_size.X, m_prop.visual_size.Y) * BS);
1855                                 m_env->addSimpleObject(simple);
1856                         } else if (m_reset_textures_timer < 0 && !m_prop.damage_texture_modifier.empty()) {
1857                                 m_reset_textures_timer = 0.05;
1858                                 if(damage >= 2)
1859                                         m_reset_textures_timer += 0.05 * damage;
1860                                 updateTextures(m_current_texture_modifier + m_prop.damage_texture_modifier);
1861                         }
1862                 }
1863
1864                 if (m_hp == 0) {
1865                         // Same as 'Server::DiePlayer'
1866                         clearParentAttachment();
1867                         // Same as 'ObjectRef::l_remove'
1868                         if (!m_is_player)
1869                                 clearChildAttachments();
1870                 } else {
1871                         if (m_client->modsLoaded())
1872                                 m_client->getScript()->on_object_hp_change(m_id);
1873                 }
1874         } else if (cmd == AO_CMD_UPDATE_ARMOR_GROUPS) {
1875                 m_armor_groups.clear();
1876                 int armor_groups_size = readU16(is);
1877                 for(int i=0; i<armor_groups_size; i++)
1878                 {
1879                         std::string name = deSerializeString16(is);
1880                         int rating = readS16(is);
1881                         m_armor_groups[name] = rating;
1882                 }
1883         } else if (cmd == AO_CMD_SPAWN_INFANT) {
1884                 u16 child_id = readU16(is);
1885                 u8 type = readU8(is); // maybe this will be useful later
1886                 (void)type;
1887
1888                 addAttachmentChild(child_id);
1889         } else if (cmd == AO_CMD_OBSOLETE1) {
1890                 // Don't do anything and also don't log a warning
1891         } else {
1892                 warningstream << FUNCTION_NAME
1893                         << ": unknown command or outdated client \""
1894                         << +cmd << "\"" << std::endl;
1895         }
1896 }
1897
1898 /* \pre punchitem != NULL
1899  */
1900 bool GenericCAO::directReportPunch(v3f dir, const ItemStack *punchitem,
1901                 float time_from_last_punch)
1902 {
1903         assert(punchitem);      // pre-condition
1904         const ToolCapabilities *toolcap =
1905                         &punchitem->getToolCapabilities(m_client->idef());
1906         PunchDamageResult result = getPunchDamage(
1907                         m_armor_groups,
1908                         toolcap,
1909                         punchitem,
1910                         time_from_last_punch);
1911
1912         if(result.did_punch && result.damage != 0)
1913         {
1914                 if(result.damage < m_hp)
1915                 {
1916                         m_hp -= result.damage;
1917                 } else {
1918                         m_hp = 0;
1919                         // TODO: Execute defined fast response
1920                         // As there is no definition, make a smoke puff
1921                         ClientSimpleObject *simple = createSmokePuff(
1922                                         m_smgr, m_env, m_position,
1923                                         v2f(m_prop.visual_size.X, m_prop.visual_size.Y) * BS);
1924                         m_env->addSimpleObject(simple);
1925                 }
1926                 if (m_reset_textures_timer < 0 && !m_prop.damage_texture_modifier.empty()) {
1927                         m_reset_textures_timer = 0.05;
1928                         if (result.damage >= 2)
1929                                 m_reset_textures_timer += 0.05 * result.damage;
1930                         updateTextures(m_current_texture_modifier + m_prop.damage_texture_modifier);
1931                 }
1932         }
1933
1934         return false;
1935 }
1936
1937 std::string GenericCAO::debugInfoText()
1938 {
1939         std::ostringstream os(std::ios::binary);
1940         os<<"GenericCAO hp="<<m_hp<<"\n";
1941         os<<"armor={";
1942         for(ItemGroupList::const_iterator i = m_armor_groups.begin();
1943                         i != m_armor_groups.end(); ++i)
1944         {
1945                 os<<i->first<<"="<<i->second<<", ";
1946         }
1947         os<<"}";
1948         return os.str();
1949 }
1950
1951 void GenericCAO::updateMeshCulling()
1952 {
1953         if (!m_is_local_player)
1954                 return;
1955
1956         const bool hidden = m_client->getCamera()->getCameraMode() == CAMERA_MODE_FIRST && ! g_settings->getBool("freecam");
1957
1958         if (m_meshnode && m_prop.visual == "upright_sprite") {
1959                 u32 buffers = m_meshnode->getMesh()->getMeshBufferCount();
1960                 for (u32 i = 0; i < buffers; i++) {
1961                         video::SMaterial &mat = m_meshnode->getMesh()->getMeshBuffer(i)->getMaterial();
1962                         // upright sprite has no backface culling
1963                         mat.setFlag(video::EMF_FRONT_FACE_CULLING, hidden);
1964                 }
1965                 return;
1966         }
1967
1968         irr::scene::ISceneNode *node = getSceneNode();
1969         if (!node)
1970                 return;
1971
1972         if (hidden) {
1973                 // Hide the mesh by culling both front and
1974                 // back faces. Serious hackyness but it works for our
1975                 // purposes. This also preserves the skeletal armature.
1976                 node->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
1977                         true);
1978                 node->setMaterialFlag(video::EMF_FRONT_FACE_CULLING,
1979                         true);
1980         } else {
1981                 // Restore mesh visibility.
1982                 node->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
1983                         m_prop.backface_culling);
1984                 node->setMaterialFlag(video::EMF_FRONT_FACE_CULLING,
1985                         false);
1986         }
1987 }
1988
1989 // Prototype
1990 GenericCAO proto_GenericCAO(NULL, NULL);