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