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