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