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