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