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