644a71e6ef17789bcbca7e56339e64440e307cbf
[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
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                                 (m_prop.use_texture_alpha) ? TILE_MATERIAL_ALPHA : 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                 m_meshnode->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
718                         m_prop.backface_culling);
719
720                 setSceneNodeMaterial(m_meshnode);
721         } else if (m_prop.visual == "mesh") {
722                 grabMatrixNode();
723                 scene::IAnimatedMesh *mesh = m_client->getMesh(m_prop.mesh, true);
724                 if (mesh) {
725                         m_animated_meshnode = RenderingEngine::get_scene_manager()->
726                                 addAnimatedMeshSceneNode(mesh, m_matrixnode);
727                         m_animated_meshnode->grab();
728                         mesh->drop(); // The scene node took hold of it
729
730                         if (!checkMeshNormals(mesh)) {
731                                 infostream << "GenericCAO: recalculating normals for mesh "
732                                         << m_prop.mesh << std::endl;
733                                 m_smgr->getMeshManipulator()->
734                                                 recalculateNormals(mesh, true, false);
735                         }
736
737                         m_animated_meshnode->animateJoints(); // Needed for some animations
738                         m_animated_meshnode->setScale(m_prop.visual_size);
739
740                         // set vertex colors to ensure alpha is set
741                         setMeshColor(m_animated_meshnode->getMesh(), video::SColor(0xFFFFFFFF));
742
743                         setAnimatedMeshColor(m_animated_meshnode, video::SColor(0xFFFFFFFF));
744
745                         setSceneNodeMaterial(m_animated_meshnode);
746
747                         m_animated_meshnode->setMaterialFlag(video::EMF_BACK_FACE_CULLING,
748                                 m_prop.backface_culling);
749                 } else
750                         errorstream<<"GenericCAO::addToScene(): Could not load mesh "<<m_prop.mesh<<std::endl;
751         } else if (m_prop.visual == "wielditem" || m_prop.visual == "item") {
752                 grabMatrixNode();
753                 ItemStack item;
754                 if (m_prop.wield_item.empty()) {
755                         // Old format, only textures are specified.
756                         infostream << "textures: " << m_prop.textures.size() << std::endl;
757                         if (!m_prop.textures.empty()) {
758                                 infostream << "textures[0]: " << m_prop.textures[0]
759                                         << std::endl;
760                                 IItemDefManager *idef = m_client->idef();
761                                 item = ItemStack(m_prop.textures[0], 1, 0, idef);
762                         }
763                 } else {
764                         infostream << "serialized form: " << m_prop.wield_item << std::endl;
765                         item.deSerialize(m_prop.wield_item, m_client->idef());
766                 }
767                 m_wield_meshnode = new WieldMeshSceneNode(
768                         RenderingEngine::get_scene_manager(), -1);
769                 m_wield_meshnode->setItem(item, m_client,
770                         (m_prop.visual == "wielditem"));
771
772                 m_wield_meshnode->setScale(m_prop.visual_size / 2.0f);
773                 m_wield_meshnode->setColor(video::SColor(0xFFFFFFFF));
774         } else {
775                 infostream<<"GenericCAO::addToScene(): \""<<m_prop.visual
776                                 <<"\" not supported"<<std::endl;
777         }
778
779         /* don't update while punch texture modifier is active */
780         if (m_reset_textures_timer < 0)
781                 updateTextures(m_current_texture_modifier);
782
783         scene::ISceneNode *node = getSceneNode();
784
785         if (node && m_matrixnode)
786                 node->setParent(m_matrixnode);
787
788         updateNametag();
789         updateNodePos();
790         updateAnimation();
791         updateBonePosition();
792         updateAttachments();
793         setNodeLight(m_last_light);
794 }
795
796 void GenericCAO::updateLight(u32 day_night_ratio)
797 {
798         if (m_glow < 0)
799                 return;
800
801         u8 light_at_pos = 0;
802         bool pos_ok;
803
804         v3s16 p = getLightPosition();
805         MapNode n = m_env->getMap().getNode(p, &pos_ok);
806         if (pos_ok)
807                 light_at_pos = n.getLightBlend(day_night_ratio, m_client->ndef());
808         else
809                 light_at_pos = blend_light(day_night_ratio, LIGHT_SUN, 0);
810
811         u8 light = decode_light(light_at_pos + m_glow);
812         if (light != m_last_light) {
813                 m_last_light = light;
814                 setNodeLight(light);
815         }
816 }
817
818 void GenericCAO::setNodeLight(u8 light)
819 {
820         video::SColor color(255, light, light, light);
821
822         if (m_prop.visual == "wielditem" || m_prop.visual == "item") {
823                 if (m_wield_meshnode)
824                         m_wield_meshnode->setNodeLightColor(color);
825                 return;
826         }
827
828         if (m_enable_shaders) {
829                 if (m_prop.visual == "upright_sprite") {
830                         if (!m_meshnode)
831                                 return;
832
833                         scene::IMesh *mesh = m_meshnode->getMesh();
834                         for (u32 i = 0; i < mesh->getMeshBufferCount(); ++i) {
835                                 scene::IMeshBuffer *buf = mesh->getMeshBuffer(i);
836                                 buf->getMaterial().EmissiveColor = color;
837                         }
838                 } else {
839                         scene::ISceneNode *node = getSceneNode();
840                         if (!node)
841                                 return;
842
843                         for (u32 i = 0; i < node->getMaterialCount(); ++i) {
844                                 video::SMaterial &material = node->getMaterial(i);
845                                 material.EmissiveColor = color;
846                         }
847                 }
848         } else {
849                 if (m_meshnode) {
850                         setMeshColor(m_meshnode->getMesh(), color);
851                 } else if (m_animated_meshnode) {
852                         setAnimatedMeshColor(m_animated_meshnode, color);
853                 } else if (m_spritenode) {
854                         m_spritenode->setColor(color);
855                 }
856         }
857 }
858
859 v3s16 GenericCAO::getLightPosition()
860 {
861         if (m_is_player)
862                 return floatToInt(m_position + v3f(0, 0.5 * BS, 0), BS);
863
864         return floatToInt(m_position, BS);
865 }
866
867 void GenericCAO::updateNametag()
868 {
869         if (m_is_local_player) // No nametag for local player
870                 return;
871
872         if (m_prop.nametag.empty()) {
873                 // Delete nametag
874                 if (m_nametag) {
875                         m_client->getCamera()->removeNametag(m_nametag);
876                         m_nametag = nullptr;
877                 }
878                 return;
879         }
880
881         scene::ISceneNode *node = getSceneNode();
882         if (!node)
883                 return;
884
885         v3f pos;
886         pos.Y = m_prop.selectionbox.MaxEdge.Y + 0.3f;
887         if (!m_nametag) {
888                 // Add nametag
889                 m_nametag = m_client->getCamera()->addNametag(node,
890                         m_prop.nametag, m_prop.nametag_color, pos);
891         } else {
892                 // Update nametag
893                 m_nametag->nametag_text = m_prop.nametag;
894                 m_nametag->nametag_color = m_prop.nametag_color;
895                 m_nametag->nametag_pos = pos;
896         }
897 }
898
899 void GenericCAO::updateNodePos()
900 {
901         if (getParent() != NULL)
902                 return;
903
904         scene::ISceneNode *node = getSceneNode();
905
906         if (node) {
907                 v3s16 camera_offset = m_env->getCameraOffset();
908                 v3f pos = pos_translator.val_current -
909                                 intToFloat(camera_offset, BS);
910                 getPosRotMatrix().setTranslation(pos);
911                 if (node != m_spritenode) { // rotate if not a sprite
912                         v3f rot = m_is_local_player ? -m_rotation : -rot_translator.val_current;
913                         setPitchYawRoll(getPosRotMatrix(), rot);
914                 }
915         }
916 }
917
918 void GenericCAO::step(float dtime, ClientEnvironment *env)
919 {
920         if (m_animated_meshnode) {
921                 m_animated_meshnode->animateJoints();
922                 updateBonePosition();
923         }
924
925         // Handle model animations and update positions instantly to prevent lags
926         if (m_is_local_player) {
927                 LocalPlayer *player = m_env->getLocalPlayer();
928                 m_position = player->getPosition();
929                 pos_translator.val_current = m_position;
930                 m_rotation.Y = wrapDegrees_0_360(player->getYaw());
931                 rot_translator.val_current = m_rotation;
932
933                 if (m_is_visible) {
934                         int old_anim = player->last_animation;
935                         float old_anim_speed = player->last_animation_speed;
936                         m_velocity = v3f(0,0,0);
937                         m_acceleration = v3f(0,0,0);
938                         const PlayerControl &controls = player->getPlayerControl();
939
940                         bool walking = false;
941                         if (controls.up || controls.down || controls.left || controls.right ||
942                                         controls.forw_move_joystick_axis != 0.f ||
943                                         controls.sidew_move_joystick_axis != 0.f)
944                                 walking = true;
945
946                         f32 new_speed = player->local_animation_speed;
947                         v2s32 new_anim = v2s32(0,0);
948                         bool allow_update = false;
949
950                         // increase speed if using fast or flying fast
951                         if((g_settings->getBool("fast_move") &&
952                                         m_client->checkLocalPrivilege("fast")) &&
953                                         (controls.aux1 ||
954                                         (!player->touching_ground &&
955                                         g_settings->getBool("free_move") &&
956                                         m_client->checkLocalPrivilege("fly"))))
957                                         new_speed *= 1.5;
958                         // slowdown speed if sneeking
959                         if (controls.sneak && walking)
960                                 new_speed /= 2;
961
962                         if (walking && (controls.LMB || controls.RMB)) {
963                                 new_anim = player->local_animations[3];
964                                 player->last_animation = WD_ANIM;
965                         } else if(walking) {
966                                 new_anim = player->local_animations[1];
967                                 player->last_animation = WALK_ANIM;
968                         } else if(controls.LMB || controls.RMB) {
969                                 new_anim = player->local_animations[2];
970                                 player->last_animation = DIG_ANIM;
971                         }
972
973                         // Apply animations if input detected and not attached
974                         // or set idle animation
975                         if ((new_anim.X + new_anim.Y) > 0 && !getParent()) {
976                                 allow_update = true;
977                                 m_animation_range = new_anim;
978                                 m_animation_speed = new_speed;
979                                 player->last_animation_speed = m_animation_speed;
980                         } else {
981                                 player->last_animation = NO_ANIM;
982
983                                 if (old_anim != NO_ANIM) {
984                                         m_animation_range = player->local_animations[0];
985                                         updateAnimation();
986                                 }
987                         }
988
989                         // Update local player animations
990                         if ((player->last_animation != old_anim ||
991                                 m_animation_speed != old_anim_speed) &&
992                                 player->last_animation != NO_ANIM && allow_update)
993                                         updateAnimation();
994
995                 }
996         }
997
998         if (m_visuals_expired && m_smgr) {
999                 m_visuals_expired = false;
1000
1001                 // Attachments, part 1: All attached objects must be unparented first,
1002                 // or Irrlicht causes a segmentation fault
1003                 for (u16 cao_id : m_attachment_child_ids) {
1004                         ClientActiveObject *obj = m_env->getActiveObject(cao_id);
1005                         if (obj) {
1006                                 scene::ISceneNode *child_node = obj->getSceneNode();
1007                                 // The node's parent is always an IDummyTraformationSceneNode,
1008                                 // so we need to reparent that one instead.
1009                                 if (child_node)
1010                                         child_node->getParent()->setParent(m_smgr->getRootSceneNode());
1011                         }
1012                 }
1013
1014                 removeFromScene(false);
1015                 addToScene(m_client->tsrc());
1016
1017                 // Attachments, part 2: Now that the parent has been refreshed, put its attachments back
1018                 for (u16 cao_id : m_attachment_child_ids) {
1019                         ClientActiveObject *obj = m_env->getActiveObject(cao_id);
1020                         if (obj)
1021                                 obj->updateAttachments();
1022                 }
1023         }
1024
1025         // Make sure m_is_visible is always applied
1026         scene::ISceneNode *node = getSceneNode();
1027         if (node)
1028                 node->setVisible(m_is_visible);
1029
1030         if(getParent() != NULL) // Attachments should be glued to their parent by Irrlicht
1031         {
1032                 // Set these for later
1033                 m_position = getPosition();
1034                 m_velocity = v3f(0,0,0);
1035                 m_acceleration = v3f(0,0,0);
1036                 pos_translator.val_current = m_position;
1037                 pos_translator.val_target = m_position;
1038         } else {
1039                 rot_translator.translate(dtime);
1040                 v3f lastpos = pos_translator.val_current;
1041
1042                 if(m_prop.physical)
1043                 {
1044                         aabb3f box = m_prop.collisionbox;
1045                         box.MinEdge *= BS;
1046                         box.MaxEdge *= BS;
1047                         collisionMoveResult moveresult;
1048                         f32 pos_max_d = BS*0.125; // Distance per iteration
1049                         v3f p_pos = m_position;
1050                         v3f p_velocity = m_velocity;
1051                         moveresult = collisionMoveSimple(env,env->getGameDef(),
1052                                         pos_max_d, box, m_prop.stepheight, dtime,
1053                                         &p_pos, &p_velocity, m_acceleration,
1054                                         this, m_prop.collideWithObjects);
1055                         // Apply results
1056                         m_position = p_pos;
1057                         m_velocity = p_velocity;
1058
1059                         bool is_end_position = moveresult.collides;
1060                         pos_translator.update(m_position, is_end_position, dtime);
1061                 } else {
1062                         m_position += dtime * m_velocity + 0.5 * dtime * dtime * m_acceleration;
1063                         m_velocity += dtime * m_acceleration;
1064                         pos_translator.update(m_position, pos_translator.aim_is_end,
1065                                         pos_translator.anim_time);
1066                 }
1067                 pos_translator.translate(dtime);
1068                 updateNodePos();
1069
1070                 float moved = lastpos.getDistanceFrom(pos_translator.val_current);
1071                 m_step_distance_counter += moved;
1072                 if (m_step_distance_counter > 1.5f * BS) {
1073                         m_step_distance_counter = 0.0f;
1074                         if (!m_is_local_player && m_prop.makes_footstep_sound) {
1075                                 const NodeDefManager *ndef = m_client->ndef();
1076                                 v3s16 p = floatToInt(getPosition() +
1077                                         v3f(0.0f, (m_prop.collisionbox.MinEdge.Y - 0.5f) * BS, 0.0f), BS);
1078                                 MapNode n = m_env->getMap().getNode(p);
1079                                 SimpleSoundSpec spec = ndef->get(n).sound_footstep;
1080                                 // Reduce footstep gain, as non-local-player footsteps are
1081                                 // somehow louder.
1082                                 spec.gain *= 0.6f;
1083                                 m_client->sound()->playSoundAt(spec, false, getPosition());
1084                         }
1085                 }
1086         }
1087
1088         m_anim_timer += dtime;
1089         if(m_anim_timer >= m_anim_framelength)
1090         {
1091                 m_anim_timer -= m_anim_framelength;
1092                 m_anim_frame++;
1093                 if(m_anim_frame >= m_anim_num_frames)
1094                         m_anim_frame = 0;
1095         }
1096
1097         updateTexturePos();
1098
1099         if(m_reset_textures_timer >= 0)
1100         {
1101                 m_reset_textures_timer -= dtime;
1102                 if(m_reset_textures_timer <= 0) {
1103                         m_reset_textures_timer = -1;
1104                         updateTextures(m_previous_texture_modifier);
1105                 }
1106         }
1107
1108         if (!getParent() && std::fabs(m_prop.automatic_rotate) > 0.001) {
1109                 // This is the child node's rotation. It is only used for automatic_rotate.
1110                 v3f local_rot = node->getRotation();
1111                 local_rot.Y = modulo360f(local_rot.Y - dtime * core::RADTODEG *
1112                                 m_prop.automatic_rotate);
1113                 node->setRotation(local_rot);
1114         }
1115
1116         if (!getParent() && m_prop.automatic_face_movement_dir &&
1117                         (fabs(m_velocity.Z) > 0.001 || fabs(m_velocity.X) > 0.001)) {
1118                 float target_yaw = atan2(m_velocity.Z, m_velocity.X) * 180 / M_PI
1119                                 + m_prop.automatic_face_movement_dir_offset;
1120                 float max_rotation_per_sec =
1121                                 m_prop.automatic_face_movement_max_rotation_per_sec;
1122
1123                 if (max_rotation_per_sec > 0) {
1124                         wrappedApproachShortest(m_rotation.Y, target_yaw,
1125                                 dtime * max_rotation_per_sec, 360.f);
1126                 } else {
1127                         // Negative values of max_rotation_per_sec mean disabled.
1128                         m_rotation.Y = target_yaw;
1129                 }
1130
1131                 rot_translator.val_current = m_rotation;
1132                 updateNodePos();
1133         }
1134 }
1135
1136 void GenericCAO::updateTexturePos()
1137 {
1138         if(m_spritenode)
1139         {
1140                 scene::ICameraSceneNode* camera =
1141                                 m_spritenode->getSceneManager()->getActiveCamera();
1142                 if(!camera)
1143                         return;
1144                 v3f cam_to_entity = m_spritenode->getAbsolutePosition()
1145                                 - camera->getAbsolutePosition();
1146                 cam_to_entity.normalize();
1147
1148                 int row = m_tx_basepos.Y;
1149                 int col = m_tx_basepos.X;
1150
1151                 if (m_tx_select_horiz_by_yawpitch) {
1152                         if (cam_to_entity.Y > 0.75)
1153                                 col += 5;
1154                         else if (cam_to_entity.Y < -0.75)
1155                                 col += 4;
1156                         else {
1157                                 float mob_dir =
1158                                                 atan2(cam_to_entity.Z, cam_to_entity.X) / M_PI * 180.;
1159                                 float dir = mob_dir - m_rotation.Y;
1160                                 dir = wrapDegrees_180(dir);
1161                                 if (std::fabs(wrapDegrees_180(dir - 0)) <= 45.1f)
1162                                         col += 2;
1163                                 else if(std::fabs(wrapDegrees_180(dir - 90)) <= 45.1f)
1164                                         col += 3;
1165                                 else if(std::fabs(wrapDegrees_180(dir - 180)) <= 45.1f)
1166                                         col += 0;
1167                                 else if(std::fabs(wrapDegrees_180(dir + 90)) <= 45.1f)
1168                                         col += 1;
1169                                 else
1170                                         col += 4;
1171                         }
1172                 }
1173
1174                 // Animation goes downwards
1175                 row += m_anim_frame;
1176
1177                 float txs = m_tx_size.X;
1178                 float tys = m_tx_size.Y;
1179                 setBillboardTextureMatrix(m_spritenode, txs, tys, col, row);
1180         }
1181 }
1182
1183 // Do not pass by reference, see header.
1184 void GenericCAO::updateTextures(std::string mod)
1185 {
1186         ITextureSource *tsrc = m_client->tsrc();
1187
1188         bool use_trilinear_filter = g_settings->getBool("trilinear_filter");
1189         bool use_bilinear_filter = g_settings->getBool("bilinear_filter");
1190         bool use_anisotropic_filter = g_settings->getBool("anisotropic_filter");
1191
1192         m_previous_texture_modifier = m_current_texture_modifier;
1193         m_current_texture_modifier = mod;
1194         m_glow = m_prop.glow;
1195
1196         if (m_spritenode) {
1197                 if (m_prop.visual == "sprite") {
1198                         std::string texturestring = "unknown_node.png";
1199                         if (!m_prop.textures.empty())
1200                                 texturestring = m_prop.textures[0];
1201                         texturestring += mod;
1202                         m_spritenode->getMaterial(0).MaterialType = m_material_type;
1203                         m_spritenode->getMaterial(0).MaterialTypeParam = 0.5f;
1204                         m_spritenode->setMaterialTexture(0,
1205                                         tsrc->getTextureForMesh(texturestring));
1206
1207                         // This allows setting per-material colors. However, until a real lighting
1208                         // system is added, the code below will have no effect. Once MineTest
1209                         // has directional lighting, it should work automatically.
1210                         if (!m_prop.colors.empty()) {
1211                                 m_spritenode->getMaterial(0).AmbientColor = m_prop.colors[0];
1212                                 m_spritenode->getMaterial(0).DiffuseColor = m_prop.colors[0];
1213                                 m_spritenode->getMaterial(0).SpecularColor = m_prop.colors[0];
1214                         }
1215
1216                         m_spritenode->getMaterial(0).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1217                         m_spritenode->getMaterial(0).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1218                         m_spritenode->getMaterial(0).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1219                 }
1220         }
1221
1222         if (m_animated_meshnode) {
1223                 if (m_prop.visual == "mesh") {
1224                         for (u32 i = 0; i < m_prop.textures.size() &&
1225                                         i < m_animated_meshnode->getMaterialCount(); ++i) {
1226                                 std::string texturestring = m_prop.textures[i];
1227                                 if (texturestring.empty())
1228                                         continue; // Empty texture string means don't modify that material
1229                                 texturestring += mod;
1230                                 video::ITexture* texture = tsrc->getTextureForMesh(texturestring);
1231                                 if (!texture) {
1232                                         errorstream<<"GenericCAO::updateTextures(): Could not load texture "<<texturestring<<std::endl;
1233                                         continue;
1234                                 }
1235
1236                                 // Set material flags and texture
1237                                 video::SMaterial& material = m_animated_meshnode->getMaterial(i);
1238                                 material.MaterialType = m_material_type;
1239                                 material.MaterialTypeParam = 0.5f;
1240                                 material.TextureLayer[0].Texture = texture;
1241                                 material.setFlag(video::EMF_LIGHTING, true);
1242                                 material.setFlag(video::EMF_BILINEAR_FILTER, false);
1243                                 material.setFlag(video::EMF_BACK_FACE_CULLING, m_prop.backface_culling);
1244
1245                                 // don't filter low-res textures, makes them look blurry
1246                                 // player models have a res of 64
1247                                 const core::dimension2d<u32> &size = texture->getOriginalSize();
1248                                 const u32 res = std::min(size.Height, size.Width);
1249                                 use_trilinear_filter &= res > 64;
1250                                 use_bilinear_filter &= res > 64;
1251
1252                                 m_animated_meshnode->getMaterial(i)
1253                                                 .setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1254                                 m_animated_meshnode->getMaterial(i)
1255                                                 .setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1256                                 m_animated_meshnode->getMaterial(i)
1257                                                 .setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1258                         }
1259                         for (u32 i = 0; i < m_prop.colors.size() &&
1260                         i < m_animated_meshnode->getMaterialCount(); ++i)
1261                         {
1262                                 // This allows setting per-material colors. However, until a real lighting
1263                                 // system is added, the code below will have no effect. Once MineTest
1264                                 // has directional lighting, it should work automatically.
1265                                 m_animated_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i];
1266                                 m_animated_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i];
1267                                 m_animated_meshnode->getMaterial(i).SpecularColor = m_prop.colors[i];
1268                         }
1269                 }
1270         }
1271         if(m_meshnode)
1272         {
1273                 if(m_prop.visual == "cube")
1274                 {
1275                         for (u32 i = 0; i < 6; ++i)
1276                         {
1277                                 std::string texturestring = "unknown_node.png";
1278                                 if(m_prop.textures.size() > i)
1279                                         texturestring = m_prop.textures[i];
1280                                 texturestring += mod;
1281
1282
1283                                 // Set material flags and texture
1284                                 video::SMaterial& material = m_meshnode->getMaterial(i);
1285                                 material.MaterialType = m_material_type;
1286                                 material.MaterialTypeParam = 0.5f;
1287                                 material.setFlag(video::EMF_LIGHTING, false);
1288                                 material.setFlag(video::EMF_BILINEAR_FILTER, false);
1289                                 material.setTexture(0,
1290                                                 tsrc->getTextureForMesh(texturestring));
1291                                 material.getTextureMatrix(0).makeIdentity();
1292
1293                                 // This allows setting per-material colors. However, until a real lighting
1294                                 // system is added, the code below will have no effect. Once MineTest
1295                                 // has directional lighting, it should work automatically.
1296                                 if(m_prop.colors.size() > i)
1297                                 {
1298                                         m_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i];
1299                                         m_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i];
1300                                         m_meshnode->getMaterial(i).SpecularColor = m_prop.colors[i];
1301                                 }
1302
1303                                 m_meshnode->getMaterial(i).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1304                                 m_meshnode->getMaterial(i).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1305                                 m_meshnode->getMaterial(i).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1306                         }
1307                 } else if (m_prop.visual == "upright_sprite") {
1308                         scene::IMesh *mesh = m_meshnode->getMesh();
1309                         {
1310                                 std::string tname = "unknown_object.png";
1311                                 if (!m_prop.textures.empty())
1312                                         tname = m_prop.textures[0];
1313                                 tname += mod;
1314                                 scene::IMeshBuffer *buf = mesh->getMeshBuffer(0);
1315                                 buf->getMaterial().setTexture(0,
1316                                                 tsrc->getTextureForMesh(tname));
1317
1318                                 // This allows setting per-material colors. However, until a real lighting
1319                                 // system is added, the code below will have no effect. Once MineTest
1320                                 // has directional lighting, it should work automatically.
1321                                 if(!m_prop.colors.empty()) {
1322                                         buf->getMaterial().AmbientColor = m_prop.colors[0];
1323                                         buf->getMaterial().DiffuseColor = m_prop.colors[0];
1324                                         buf->getMaterial().SpecularColor = m_prop.colors[0];
1325                                 }
1326
1327                                 buf->getMaterial().setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1328                                 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1329                                 buf->getMaterial().setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1330                         }
1331                         {
1332                                 std::string tname = "unknown_object.png";
1333                                 if (m_prop.textures.size() >= 2)
1334                                         tname = m_prop.textures[1];
1335                                 else if (!m_prop.textures.empty())
1336                                         tname = m_prop.textures[0];
1337                                 tname += mod;
1338                                 scene::IMeshBuffer *buf = mesh->getMeshBuffer(1);
1339                                 buf->getMaterial().setTexture(0,
1340                                                 tsrc->getTextureForMesh(tname));
1341
1342                                 // This allows setting per-material colors. However, until a real lighting
1343                                 // system is added, the code below will have no effect. Once MineTest
1344                                 // has directional lighting, it should work automatically.
1345                                 if (m_prop.colors.size() >= 2) {
1346                                         buf->getMaterial().AmbientColor = m_prop.colors[1];
1347                                         buf->getMaterial().DiffuseColor = m_prop.colors[1];
1348                                         buf->getMaterial().SpecularColor = m_prop.colors[1];
1349                                 } else if (!m_prop.colors.empty()) {
1350                                         buf->getMaterial().AmbientColor = m_prop.colors[0];
1351                                         buf->getMaterial().DiffuseColor = m_prop.colors[0];
1352                                         buf->getMaterial().SpecularColor = m_prop.colors[0];
1353                                 }
1354
1355                                 buf->getMaterial().setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1356                                 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1357                                 buf->getMaterial().setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1358                         }
1359                         // Set mesh color (only if lighting is disabled)
1360                         if (!m_prop.colors.empty() && m_glow < 0)
1361                                 setMeshColor(mesh, m_prop.colors[0]);
1362                 }
1363         }
1364 }
1365
1366 void GenericCAO::updateAnimation()
1367 {
1368         if (!m_animated_meshnode)
1369                 return;
1370
1371         if (m_animated_meshnode->getStartFrame() != m_animation_range.X ||
1372                 m_animated_meshnode->getEndFrame() != m_animation_range.Y)
1373                         m_animated_meshnode->setFrameLoop(m_animation_range.X, m_animation_range.Y);
1374         if (m_animated_meshnode->getAnimationSpeed() != m_animation_speed)
1375                 m_animated_meshnode->setAnimationSpeed(m_animation_speed);
1376         m_animated_meshnode->setTransitionTime(m_animation_blend);
1377 // Requires Irrlicht 1.8 or greater
1378 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR > 1
1379         if (m_animated_meshnode->getLoopMode() != m_animation_loop)
1380                 m_animated_meshnode->setLoopMode(m_animation_loop);
1381 #endif
1382 }
1383
1384 void GenericCAO::updateAnimationSpeed()
1385 {
1386         if (!m_animated_meshnode)
1387                 return;
1388
1389         m_animated_meshnode->setAnimationSpeed(m_animation_speed);
1390 }
1391
1392 void GenericCAO::updateBonePosition()
1393 {
1394         if (m_bone_position.empty() || !m_animated_meshnode)
1395                 return;
1396
1397         m_animated_meshnode->setJointMode(irr::scene::EJUOR_CONTROL); // To write positions to the mesh on render
1398         for (auto &it : m_bone_position) {
1399                 std::string bone_name = it.first;
1400                 irr::scene::IBoneSceneNode* bone = m_animated_meshnode->getJointNode(bone_name.c_str());
1401                 if (bone) {
1402                         bone->setPosition(it.second.X);
1403                         bone->setRotation(it.second.Y);
1404                 }
1405         }
1406
1407         // search through bones to find mistakenly rotated bones due to bug in Irrlicht
1408         for (u32 i = 0; i < m_animated_meshnode->getJointCount(); ++i) {
1409                 irr::scene::IBoneSceneNode *bone = m_animated_meshnode->getJointNode(i);
1410                 if (!bone)
1411                         continue;
1412
1413                 //If bone is manually positioned there is no need to perform the bug check
1414                 bool skip = false;
1415                 for (auto &it : m_bone_position) {
1416                         if (it.first == bone->getName()) {
1417                                 skip = true;
1418                                 break;
1419                         }
1420                 }
1421                 if (skip)
1422                         continue;
1423
1424                 // Workaround for Irrlicht bug
1425                 // We check each bone to see if it has been rotated ~180deg from its expected position due to a bug in Irricht
1426                 // when using EJUOR_CONTROL joint control. If the bug is detected we update the bone to the proper position
1427                 // and update the bones transformation.
1428                 v3f bone_rot = bone->getRelativeTransformation().getRotationDegrees();
1429                 float offset = fabsf(bone_rot.X - bone->getRotation().X);
1430                 if (offset > 179.9f && offset < 180.1f) {
1431                         bone->setRotation(bone_rot);
1432                         bone->updateAbsolutePosition();
1433                 }
1434         }
1435 }
1436
1437 void GenericCAO::updateAttachments()
1438 {
1439         ClientActiveObject *parent = getParent();
1440
1441         m_attached_to_local = parent && parent->isLocalPlayer();
1442
1443         /*
1444         Following cases exist:
1445                 m_attachment_parent_id == 0 && !parent
1446                         This object is not attached
1447                 m_attachment_parent_id != 0 && parent
1448                         This object is attached
1449                 m_attachment_parent_id != 0 && !parent
1450                         This object will be attached as soon the parent is known
1451                 m_attachment_parent_id == 0 && parent
1452                         Impossible case
1453         */
1454
1455         if (!parent) { // Detach or don't attach
1456                 if (m_matrixnode) {
1457                         v3s16 camera_offset = m_env->getCameraOffset();
1458                         v3f old_pos = getPosition();
1459
1460                         m_matrixnode->setParent(m_smgr->getRootSceneNode());
1461                         getPosRotMatrix().setTranslation(old_pos - intToFloat(camera_offset, BS));
1462                         m_matrixnode->updateAbsolutePosition();
1463                 }
1464         }
1465         else // Attach
1466         {
1467                 parent->updateAttachments();
1468                 scene::ISceneNode *parent_node = parent->getSceneNode();
1469                 scene::IAnimatedMeshSceneNode *parent_animated_mesh_node =
1470                                 parent->getAnimatedMeshSceneNode();
1471                 if (parent_animated_mesh_node && !m_attachment_bone.empty()) {
1472                         parent_node = parent_animated_mesh_node->getJointNode(m_attachment_bone.c_str());
1473                 }
1474
1475                 if (m_matrixnode && parent_node) {
1476                         m_matrixnode->setParent(parent_node);
1477                         parent_node->updateAbsolutePosition();
1478                         getPosRotMatrix().setTranslation(m_attachment_position);
1479                         //setPitchYawRoll(getPosRotMatrix(), m_attachment_rotation);
1480                         // use Irrlicht eulers instead
1481                         getPosRotMatrix().setRotationDegrees(m_attachment_rotation);
1482                         m_matrixnode->updateAbsolutePosition();
1483                 }
1484         }
1485 }
1486
1487 bool GenericCAO::visualExpiryRequired(const ObjectProperties &new_) const
1488 {
1489         const ObjectProperties &old = m_prop;
1490         /* Visuals do not need to be expired for:
1491          * - nametag props: handled by updateNametag()
1492          * - textures:      handled by updateTextures()
1493          * - sprite props:  handled by updateTexturePos()
1494          * - glow:          handled by updateLight()
1495          * - any other properties that do not change appearance
1496          */
1497         // Ordered to compare primitive types before std::vectors
1498         return old.backface_culling != new_.backface_culling ||
1499                 old.is_visible != new_.is_visible ||
1500                 old.mesh != new_.mesh ||
1501                 old.use_texture_alpha != new_.use_texture_alpha ||
1502                 old.visual != new_.visual ||
1503                 old.visual_size != new_.visual_size ||
1504                 old.wield_item != new_.wield_item ||
1505                 old.colors != new_.colors;
1506 }
1507
1508 void GenericCAO::processMessage(const std::string &data)
1509 {
1510         //infostream<<"GenericCAO: Got message"<<std::endl;
1511         std::istringstream is(data, std::ios::binary);
1512         // command
1513         u8 cmd = readU8(is);
1514         if (cmd == AO_CMD_SET_PROPERTIES) {
1515                 ObjectProperties newprops;
1516                 newprops.deSerialize(is);
1517
1518                 // Check what exactly changed
1519                 bool expire_visuals = visualExpiryRequired(newprops);
1520                 bool textures_changed = m_prop.textures != newprops.textures;
1521
1522                 // Apply changes
1523                 m_prop = std::move(newprops);
1524
1525                 m_selection_box = m_prop.selectionbox;
1526                 m_selection_box.MinEdge *= BS;
1527                 m_selection_box.MaxEdge *= BS;
1528
1529                 m_tx_size.X = 1.0f / m_prop.spritediv.X;
1530                 m_tx_size.Y = 1.0f / m_prop.spritediv.Y;
1531
1532                 if(!m_initial_tx_basepos_set){
1533                         m_initial_tx_basepos_set = true;
1534                         m_tx_basepos = m_prop.initial_sprite_basepos;
1535                 }
1536                 if (m_is_local_player) {
1537                         LocalPlayer *player = m_env->getLocalPlayer();
1538                         player->makes_footstep_sound = m_prop.makes_footstep_sound;
1539                         aabb3f collision_box = m_prop.collisionbox;
1540                         collision_box.MinEdge *= BS;
1541                         collision_box.MaxEdge *= BS;
1542                         player->setCollisionbox(collision_box);
1543                         player->setEyeHeight(m_prop.eye_height);
1544                         player->setZoomFOV(m_prop.zoom_fov);
1545                 }
1546
1547                 if ((m_is_player && !m_is_local_player) && m_prop.nametag.empty())
1548                         m_prop.nametag = m_name;
1549
1550                 if (expire_visuals) {
1551                         expireVisuals();
1552                 } else {
1553                         infostream << "GenericCAO: properties updated but expiring visuals"
1554                                 << " not necessary" << std::endl;
1555                         if (textures_changed) {
1556                                 // don't update while punch texture modifier is active
1557                                 if (m_reset_textures_timer < 0)
1558                                         updateTextures(m_current_texture_modifier);
1559                         }
1560                         updateNametag();
1561                 }
1562         } else if (cmd == AO_CMD_UPDATE_POSITION) {
1563                 // Not sent by the server if this object is an attachment.
1564                 // We might however get here if the server notices the object being detached before the client.
1565                 m_position = readV3F32(is);
1566                 m_velocity = readV3F32(is);
1567                 m_acceleration = readV3F32(is);
1568                 m_rotation = readV3F32(is);
1569
1570                 m_rotation = wrapDegrees_0_360_v3f(m_rotation);
1571                 bool do_interpolate = readU8(is);
1572                 bool is_end_position = readU8(is);
1573                 float update_interval = readF32(is);
1574
1575                 // Place us a bit higher if we're physical, to not sink into
1576                 // the ground due to sucky collision detection...
1577                 if(m_prop.physical)
1578                         m_position += v3f(0,0.002,0);
1579
1580                 if(getParent() != NULL) // Just in case
1581                         return;
1582
1583                 if(do_interpolate)
1584                 {
1585                         if(!m_prop.physical)
1586                                 pos_translator.update(m_position, is_end_position, update_interval);
1587                 } else {
1588                         pos_translator.init(m_position);
1589                 }
1590                 rot_translator.update(m_rotation, false, update_interval);
1591                 updateNodePos();
1592         } else if (cmd == AO_CMD_SET_TEXTURE_MOD) {
1593                 std::string mod = deSerializeString(is);
1594
1595                 // immediately reset a engine issued texture modifier if a mod sends a different one
1596                 if (m_reset_textures_timer > 0) {
1597                         m_reset_textures_timer = -1;
1598                         updateTextures(m_previous_texture_modifier);
1599                 }
1600                 updateTextures(mod);
1601         } else if (cmd == AO_CMD_SET_SPRITE) {
1602                 v2s16 p = readV2S16(is);
1603                 int num_frames = readU16(is);
1604                 float framelength = readF32(is);
1605                 bool select_horiz_by_yawpitch = readU8(is);
1606
1607                 m_tx_basepos = p;
1608                 m_anim_num_frames = num_frames;
1609                 m_anim_framelength = framelength;
1610                 m_tx_select_horiz_by_yawpitch = select_horiz_by_yawpitch;
1611
1612                 updateTexturePos();
1613         } else if (cmd == AO_CMD_SET_PHYSICS_OVERRIDE) {
1614                 float override_speed = readF32(is);
1615                 float override_jump = readF32(is);
1616                 float override_gravity = readF32(is);
1617                 // these are sent inverted so we get true when the server sends nothing
1618                 bool sneak = !readU8(is);
1619                 bool sneak_glitch = !readU8(is);
1620                 bool new_move = !readU8(is);
1621
1622
1623                 if(m_is_local_player)
1624                 {
1625                         LocalPlayer *player = m_env->getLocalPlayer();
1626                         player->physics_override_speed = override_speed;
1627                         player->physics_override_jump = override_jump;
1628                         player->physics_override_gravity = override_gravity;
1629                         player->physics_override_sneak = sneak;
1630                         player->physics_override_sneak_glitch = sneak_glitch;
1631                         player->physics_override_new_move = new_move;
1632                 }
1633         } else if (cmd == AO_CMD_SET_ANIMATION) {
1634                 // TODO: change frames send as v2s32 value
1635                 v2f range = readV2F32(is);
1636                 if (!m_is_local_player) {
1637                         m_animation_range = v2s32((s32)range.X, (s32)range.Y);
1638                         m_animation_speed = readF32(is);
1639                         m_animation_blend = readF32(is);
1640                         // these are sent inverted so we get true when the server sends nothing
1641                         m_animation_loop = !readU8(is);
1642                         updateAnimation();
1643                 } else {
1644                         LocalPlayer *player = m_env->getLocalPlayer();
1645                         if(player->last_animation == NO_ANIM)
1646                         {
1647                                 m_animation_range = v2s32((s32)range.X, (s32)range.Y);
1648                                 m_animation_speed = readF32(is);
1649                                 m_animation_blend = readF32(is);
1650                                 // these are sent inverted so we get true when the server sends nothing
1651                                 m_animation_loop = !readU8(is);
1652                         }
1653                         // update animation only if local animations present
1654                         // and received animation is unknown (except idle animation)
1655                         bool is_known = false;
1656                         for (int i = 1;i<4;i++)
1657                         {
1658                                 if(m_animation_range.Y == player->local_animations[i].Y)
1659                                         is_known = true;
1660                         }
1661                         if(!is_known ||
1662                                         (player->local_animations[1].Y + player->local_animations[2].Y < 1))
1663                         {
1664                                         updateAnimation();
1665                         }
1666                 }
1667         } else if (cmd == AO_CMD_SET_ANIMATION_SPEED) {
1668                 m_animation_speed = readF32(is);
1669                 updateAnimationSpeed();
1670         } else if (cmd == AO_CMD_SET_BONE_POSITION) {
1671                 std::string bone = deSerializeString(is);
1672                 v3f position = readV3F32(is);
1673                 v3f rotation = readV3F32(is);
1674                 m_bone_position[bone] = core::vector2d<v3f>(position, rotation);
1675
1676                 // updateBonePosition(); now called every step
1677         } else if (cmd == AO_CMD_ATTACH_TO) {
1678                 u16 parent_id = readS16(is);
1679                 std::string bone = deSerializeString(is);
1680                 v3f position = readV3F32(is);
1681                 v3f rotation = readV3F32(is);
1682
1683                 setAttachment(parent_id, bone, position, rotation);
1684
1685                 // localplayer itself can't be attached to localplayer
1686                 if (!m_is_local_player)
1687                         m_is_visible = !m_attached_to_local;
1688         } else if (cmd == AO_CMD_PUNCHED) {
1689                 u16 result_hp = readU16(is);
1690
1691                 // Use this instead of the send damage to not interfere with prediction
1692                 s32 damage = (s32)m_hp - (s32)result_hp;
1693
1694                 m_hp = result_hp;
1695
1696                 if (m_is_local_player)
1697                         m_env->getLocalPlayer()->hp = m_hp;
1698
1699                 if (damage > 0)
1700                 {
1701                         if (m_hp == 0)
1702                         {
1703                                 // TODO: Execute defined fast response
1704                                 // As there is no definition, make a smoke puff
1705                                 ClientSimpleObject *simple = createSmokePuff(
1706                                                 m_smgr, m_env, m_position,
1707                                                 v2f(m_prop.visual_size.X, m_prop.visual_size.Y) * BS);
1708                                 m_env->addSimpleObject(simple);
1709                         } else if (m_reset_textures_timer < 0 && !m_prop.damage_texture_modifier.empty()) {
1710                                 m_reset_textures_timer = 0.05;
1711                                 if(damage >= 2)
1712                                         m_reset_textures_timer += 0.05 * damage;
1713                                 updateTextures(m_current_texture_modifier + m_prop.damage_texture_modifier);
1714                         }
1715                 }
1716
1717                 if (m_hp == 0) {
1718                         // Same as 'Server::DiePlayer'
1719                         clearParentAttachment();
1720                         // Same as 'ObjectRef::l_remove'
1721                         if (!m_is_player)
1722                                 clearChildAttachments();
1723                 }
1724         } else if (cmd == AO_CMD_UPDATE_ARMOR_GROUPS) {
1725                 m_armor_groups.clear();
1726                 int armor_groups_size = readU16(is);
1727                 for(int i=0; i<armor_groups_size; i++)
1728                 {
1729                         std::string name = deSerializeString(is);
1730                         int rating = readS16(is);
1731                         m_armor_groups[name] = rating;
1732                 }
1733         } else if (cmd == AO_CMD_SPAWN_INFANT) {
1734                 u16 child_id = readU16(is);
1735                 u8 type = readU8(is); // maybe this will be useful later
1736                 (void)type;
1737
1738                 addAttachmentChild(child_id);
1739         } else if (cmd == AO_CMD_OBSOLETE1) {
1740                 // Don't do anything and also don't log a warning
1741         } else {
1742                 warningstream << FUNCTION_NAME
1743                         << ": unknown command or outdated client \""
1744                         << +cmd << "\"" << std::endl;
1745         }
1746 }
1747
1748 /* \pre punchitem != NULL
1749  */
1750 bool GenericCAO::directReportPunch(v3f dir, const ItemStack *punchitem,
1751                 float time_from_last_punch)
1752 {
1753         assert(punchitem);      // pre-condition
1754         const ToolCapabilities *toolcap =
1755                         &punchitem->getToolCapabilities(m_client->idef());
1756         PunchDamageResult result = getPunchDamage(
1757                         m_armor_groups,
1758                         toolcap,
1759                         punchitem,
1760                         time_from_last_punch);
1761
1762         if(result.did_punch && result.damage != 0)
1763         {
1764                 if(result.damage < m_hp)
1765                 {
1766                         m_hp -= result.damage;
1767                 } else {
1768                         m_hp = 0;
1769                         // TODO: Execute defined fast response
1770                         // As there is no definition, make a smoke puff
1771                         ClientSimpleObject *simple = createSmokePuff(
1772                                         m_smgr, m_env, m_position,
1773                                         v2f(m_prop.visual_size.X, m_prop.visual_size.Y) * BS);
1774                         m_env->addSimpleObject(simple);
1775                 }
1776                 if (m_reset_textures_timer < 0 && !m_prop.damage_texture_modifier.empty()) {
1777                         m_reset_textures_timer = 0.05;
1778                         if (result.damage >= 2)
1779                                 m_reset_textures_timer += 0.05 * result.damage;
1780                         updateTextures(m_current_texture_modifier + m_prop.damage_texture_modifier);
1781                 }
1782         }
1783
1784         return false;
1785 }
1786
1787 std::string GenericCAO::debugInfoText()
1788 {
1789         std::ostringstream os(std::ios::binary);
1790         os<<"GenericCAO hp="<<m_hp<<"\n";
1791         os<<"armor={";
1792         for(ItemGroupList::const_iterator i = m_armor_groups.begin();
1793                         i != m_armor_groups.end(); ++i)
1794         {
1795                 os<<i->first<<"="<<i->second<<", ";
1796         }
1797         os<<"}";
1798         return os.str();
1799 }
1800
1801 // Prototype
1802 GenericCAO proto_GenericCAO(NULL, NULL);