Add cancel button to password change menu. (#5720)
[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/basic_macros.h"
30 #include "client/tile.h"
31 #include "environment.h"
32 #include "collision.h"
33 #include "settings.h"
34 #include "serialization.h" // For decompressZlib
35 #include "clientobject.h"
36 #include "mesh.h"
37 #include "itemdef.h"
38 #include "tool.h"
39 #include "content_cso.h"
40 #include "sound.h"
41 #include "nodedef.h"
42 #include "localplayer.h"
43 #include "map.h"
44 #include "camera.h" // CameraModes
45 #include "wieldmesh.h"
46 #include "log.h"
47 #include <algorithm>
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_previous_texture_modifier(""),
579                 m_current_texture_modifier(""),
580                 m_visuals_expired(false),
581                 m_step_distance_counter(0),
582                 m_last_light(255),
583                 m_is_visible(false)
584 {
585         if (client == NULL) {
586                 ClientActiveObject::registerType(getType(), create);
587         } else {
588                 m_client = client;
589         }
590 }
591
592 bool GenericCAO::getCollisionBox(aabb3f *toset) const
593 {
594         if (m_prop.physical)
595         {
596                 //update collision box
597                 toset->MinEdge = m_prop.collisionbox.MinEdge * BS;
598                 toset->MaxEdge = m_prop.collisionbox.MaxEdge * BS;
599
600                 toset->MinEdge += m_position;
601                 toset->MaxEdge += m_position;
602
603                 return true;
604         }
605
606         return false;
607 }
608
609 bool GenericCAO::collideWithObjects() const
610 {
611         return m_prop.collideWithObjects;
612 }
613
614 void GenericCAO::initialize(const std::string &data)
615 {
616         infostream<<"GenericCAO: Got init data"<<std::endl;
617         processInitData(data);
618
619         if (m_is_player) {
620                 // Check if it's the current player
621                 LocalPlayer *player = m_env->getLocalPlayer();
622                 if (player && strcmp(player->getName(), m_name.c_str()) == 0) {
623                         m_is_local_player = true;
624                         m_is_visible = false;
625                         player->setCAO(this);
626                 }
627                 m_env->addPlayerName(m_name.c_str());
628         }
629 }
630
631 void GenericCAO::processInitData(const std::string &data)
632 {
633         std::istringstream is(data, std::ios::binary);
634         int num_messages = 0;
635         // version
636         u8 version = readU8(is);
637         // check version
638         if (version == 1) { // In PROTOCOL_VERSION 14
639                 m_name = deSerializeString(is);
640                 m_is_player = readU8(is);
641                 m_id = readS16(is);
642                 m_position = readV3F1000(is);
643                 m_yaw = readF1000(is);
644                 m_hp = readS16(is);
645                 num_messages = readU8(is);
646         } else if (version == 0) { // In PROTOCOL_VERSION 13
647                 m_name = deSerializeString(is);
648                 m_is_player = readU8(is);
649                 m_position = readV3F1000(is);
650                 m_yaw = readF1000(is);
651                 m_hp = readS16(is);
652                 num_messages = readU8(is);
653         } else {
654                 errorstream<<"GenericCAO: Unsupported init data version"
655                                 <<std::endl;
656                 return;
657         }
658
659         for (int i = 0; i < num_messages; i++) {
660                 std::string message = deSerializeLongString(is);
661                 processMessage(message);
662         }
663
664         pos_translator.init(m_position);
665         updateNodePos();
666 }
667
668 GenericCAO::~GenericCAO()
669 {
670         if (m_is_player) {
671                 m_env->removePlayerName(m_name.c_str());
672         }
673         removeFromScene(true);
674 }
675
676 aabb3f *GenericCAO::getSelectionBox()
677 {
678         if(!m_prop.is_visible || !m_is_visible || m_is_local_player || getParent() != NULL)
679                 return NULL;
680         return &m_selection_box;
681 }
682
683 v3f GenericCAO::getPosition()
684 {
685         if (getParent() != NULL) {
686                 scene::ISceneNode *node = getSceneNode();
687                 if (node)
688                         return node->getAbsolutePosition();
689                 else
690                         return m_position;
691         }
692         return pos_translator.vect_show;
693 }
694
695 scene::ISceneNode* GenericCAO::getSceneNode()
696 {
697         if (m_meshnode) {
698                 return m_meshnode;
699         } else if (m_animated_meshnode) {
700                 return m_animated_meshnode;
701         } else if (m_wield_meshnode) {
702                 return m_wield_meshnode;
703         } else if (m_spritenode) {
704                 return m_spritenode;
705         }
706         return NULL;
707 }
708
709 scene::IMeshSceneNode* GenericCAO::getMeshSceneNode()
710 {
711         return m_meshnode;
712 }
713
714 scene::IAnimatedMeshSceneNode* GenericCAO::getAnimatedMeshSceneNode()
715 {
716         return m_animated_meshnode;
717 }
718
719 WieldMeshSceneNode* GenericCAO::getWieldMeshSceneNode()
720 {
721         return m_wield_meshnode;
722 }
723
724 scene::IBillboardSceneNode* GenericCAO::getSpriteSceneNode()
725 {
726         return m_spritenode;
727 }
728
729 void GenericCAO::setChildrenVisible(bool toset)
730 {
731         for (std::vector<u16>::size_type i = 0; i < m_children.size(); i++) {
732                 GenericCAO *obj = m_env->getGenericCAO(m_children[i]);
733                 if (obj) {
734                         obj->setVisible(toset);
735                 }
736         }
737 }
738
739 void GenericCAO::setAttachments()
740 {
741         updateAttachments();
742 }
743
744 ClientActiveObject* GenericCAO::getParent()
745 {
746         ClientActiveObject *obj = NULL;
747
748         u16 attached_id = m_env->attachement_parent_ids[getId()];
749
750         if ((attached_id != 0) &&
751                         (attached_id != getId())) {
752                 obj = m_env->getActiveObject(attached_id);
753         }
754         return obj;
755 }
756
757 void GenericCAO::removeFromScene(bool permanent)
758 {
759         // Should be true when removing the object permanently and false when refreshing (eg: updating visuals)
760         if((m_env != NULL) && (permanent))
761         {
762                 for (std::vector<u16>::size_type i = 0; i < m_children.size(); i++) {
763                         u16 ci = m_children[i];
764                         if (m_env->attachement_parent_ids[ci] == getId()) {
765                                 m_env->attachement_parent_ids[ci] = 0;
766                         }
767                 }
768
769                 m_env->attachement_parent_ids[getId()] = 0;
770
771                 LocalPlayer* player = m_env->getLocalPlayer();
772                 if (this == player->parent) {
773                         player->parent = NULL;
774                         player->isAttached = false;
775                 }
776         }
777
778         if (m_meshnode) {
779                 m_meshnode->remove();
780                 m_meshnode->drop();
781                 m_meshnode = NULL;
782         } else if (m_animated_meshnode) {
783                 m_animated_meshnode->remove();
784                 m_animated_meshnode->drop();
785                 m_animated_meshnode = NULL;
786         } else if (m_wield_meshnode) {
787                 m_wield_meshnode->remove();
788                 m_wield_meshnode->drop();
789                 m_wield_meshnode = NULL;
790         } else if (m_spritenode) {
791                 m_spritenode->remove();
792                 m_spritenode->drop();
793                 m_spritenode = NULL;
794         }
795
796         if (m_nametag) {
797                 m_client->getCamera()->removeNametag(m_nametag);
798                 m_nametag = NULL;
799         }
800 }
801
802 void GenericCAO::addToScene(scene::ISceneManager *smgr,
803                 ITextureSource *tsrc, IrrlichtDevice *irr)
804 {
805         m_smgr = smgr;
806         m_irr = irr;
807
808         if (getSceneNode() != NULL) {
809                 return;
810         }
811
812         m_visuals_expired = false;
813
814         if (!m_prop.is_visible) {
815                 return;
816         }
817
818         if (m_prop.visual == "sprite") {
819                 infostream<<"GenericCAO::addToScene(): single_sprite"<<std::endl;
820                 m_spritenode = smgr->addBillboardSceneNode(
821                                 NULL, v2f(1, 1), v3f(0,0,0), -1);
822                 m_spritenode->grab();
823                 m_spritenode->setMaterialTexture(0,
824                                 tsrc->getTextureForMesh("unknown_node.png"));
825                 m_spritenode->setMaterialFlag(video::EMF_LIGHTING, false);
826                 m_spritenode->setMaterialFlag(video::EMF_BILINEAR_FILTER, false);
827                 m_spritenode->setMaterialType(video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF);
828                 m_spritenode->setMaterialFlag(video::EMF_FOG_ENABLE, true);
829                 u8 li = m_last_light;
830                 m_spritenode->setColor(video::SColor(255,li,li,li));
831                 m_spritenode->setSize(m_prop.visual_size*BS);
832                 {
833                         const float txs = 1.0 / 1;
834                         const float tys = 1.0 / 1;
835                         setBillboardTextureMatrix(m_spritenode,
836                                         txs, tys, 0, 0);
837                 }
838         } else if (m_prop.visual == "upright_sprite") {
839                 scene::SMesh *mesh = new scene::SMesh();
840                 double dx = BS * m_prop.visual_size.X / 2;
841                 double dy = BS * m_prop.visual_size.Y / 2;
842                 u8 li = m_last_light;
843                 video::SColor c(255, li, li, li);
844
845                 { // Front
846                         scene::IMeshBuffer *buf = new scene::SMeshBuffer();
847                         video::S3DVertex vertices[4] = {
848                                 video::S3DVertex(-dx, -dy, 0, 0,0,0, c, 1,1),
849                                 video::S3DVertex( dx, -dy, 0, 0,0,0, c, 0,1),
850                                 video::S3DVertex( dx,  dy, 0, 0,0,0, c, 0,0),
851                                 video::S3DVertex(-dx,  dy, 0, 0,0,0, c, 1,0),
852                         };
853                         u16 indices[] = {0,1,2,2,3,0};
854                         buf->append(vertices, 4, indices, 6);
855                         // Set material
856                         buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
857                         buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
858                         buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
859                         buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
860                         // Add to mesh
861                         mesh->addMeshBuffer(buf);
862                         buf->drop();
863                 }
864                 { // Back
865                         scene::IMeshBuffer *buf = new scene::SMeshBuffer();
866                         video::S3DVertex vertices[4] = {
867                                 video::S3DVertex( dx,-dy, 0, 0,0,0, c, 1,1),
868                                 video::S3DVertex(-dx,-dy, 0, 0,0,0, c, 0,1),
869                                 video::S3DVertex(-dx, dy, 0, 0,0,0, c, 0,0),
870                                 video::S3DVertex( dx, dy, 0, 0,0,0, c, 1,0),
871                         };
872                         u16 indices[] = {0,1,2,2,3,0};
873                         buf->append(vertices, 4, indices, 6);
874                         // Set material
875                         buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
876                         buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
877                         buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
878                         buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
879                         // Add to mesh
880                         mesh->addMeshBuffer(buf);
881                         buf->drop();
882                 }
883                 m_meshnode = smgr->addMeshSceneNode(mesh, NULL);
884                 m_meshnode->grab();
885                 mesh->drop();
886                 // Set it to use the materials of the meshbuffers directly.
887                 // This is needed for changing the texture in the future
888                 m_meshnode->setReadOnlyMaterials(true);
889         }
890         else if(m_prop.visual == "cube") {
891                 infostream<<"GenericCAO::addToScene(): cube"<<std::endl;
892                 scene::IMesh *mesh = createCubeMesh(v3f(BS,BS,BS));
893                 m_meshnode = smgr->addMeshSceneNode(mesh, NULL);
894                 m_meshnode->grab();
895                 mesh->drop();
896
897                 m_meshnode->setScale(v3f(m_prop.visual_size.X,
898                                 m_prop.visual_size.Y,
899                                 m_prop.visual_size.X));
900                 u8 li = m_last_light;
901                 setMeshColor(m_meshnode->getMesh(), video::SColor(255,li,li,li));
902
903                 m_meshnode->setMaterialFlag(video::EMF_LIGHTING, false);
904                 m_meshnode->setMaterialFlag(video::EMF_BILINEAR_FILTER, false);
905                 m_meshnode->setMaterialType(video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF);
906                 m_meshnode->setMaterialFlag(video::EMF_FOG_ENABLE, true);
907         }
908         else if(m_prop.visual == "mesh") {
909                 infostream<<"GenericCAO::addToScene(): mesh"<<std::endl;
910                 scene::IAnimatedMesh *mesh = m_client->getMesh(m_prop.mesh);
911                 if(mesh)
912                 {
913                         m_animated_meshnode = smgr->addAnimatedMeshSceneNode(mesh, NULL);
914                         m_animated_meshnode->grab();
915                         mesh->drop(); // The scene node took hold of it
916                         m_animated_meshnode->animateJoints(); // Needed for some animations
917                         m_animated_meshnode->setScale(v3f(m_prop.visual_size.X,
918                                         m_prop.visual_size.Y,
919                                         m_prop.visual_size.X));
920                         u8 li = m_last_light;
921                         setMeshColor(m_animated_meshnode->getMesh(), video::SColor(255,li,li,li));
922
923                         bool backface_culling = m_prop.backface_culling;
924                         if (m_is_player)
925                                 backface_culling = false;
926
927                         m_animated_meshnode->setMaterialFlag(video::EMF_LIGHTING, false);
928                         m_animated_meshnode->setMaterialFlag(video::EMF_BILINEAR_FILTER, false);
929                         m_animated_meshnode->setMaterialType(video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF);
930                         m_animated_meshnode->setMaterialFlag(video::EMF_FOG_ENABLE, true);
931                         m_animated_meshnode->setMaterialFlag(video::EMF_BACK_FACE_CULLING, backface_culling);
932                 }
933                 else
934                         errorstream<<"GenericCAO::addToScene(): Could not load mesh "<<m_prop.mesh<<std::endl;
935         }
936         else if(m_prop.visual == "wielditem") {
937                 ItemStack item;
938                 infostream << "GenericCAO::addToScene(): wielditem" << std::endl;
939                 if (m_prop.wield_item == "") {
940                         // Old format, only textures are specified.
941                         infostream << "textures: " << m_prop.textures.size() << std::endl;
942                         if (m_prop.textures.size() >= 1) {
943                                 infostream << "textures[0]: " << m_prop.textures[0]
944                                         << std::endl;
945                                 IItemDefManager *idef = m_client->idef();
946                                 item = ItemStack(m_prop.textures[0], 1, 0, idef);
947                         }
948                 } else {
949                         infostream << "serialized form: " << m_prop.wield_item << std::endl;
950                         item.deSerialize(m_prop.wield_item, m_client->idef());
951                 }
952                 m_wield_meshnode = new WieldMeshSceneNode(smgr->getRootSceneNode(),
953                         smgr, -1);
954                 m_wield_meshnode->setItem(item, m_client);
955
956                 m_wield_meshnode->setScale(
957                         v3f(m_prop.visual_size.X / 2, m_prop.visual_size.Y / 2,
958                                 m_prop.visual_size.X / 2));
959                 u8 li = m_last_light;
960                 m_wield_meshnode->setColor(video::SColor(255, li, li, li));
961         } else {
962                 infostream<<"GenericCAO::addToScene(): \""<<m_prop.visual
963                                 <<"\" not supported"<<std::endl;
964         }
965
966         /* don't update while punch texture modifier is active */
967         if (m_reset_textures_timer < 0)
968                 updateTextures(m_current_texture_modifier);
969
970         scene::ISceneNode *node = getSceneNode();
971         if (node && m_prop.nametag != "" && !m_is_local_player) {
972                 // Add nametag
973                 m_nametag = m_client->getCamera()->addNametag(node,
974                         m_prop.nametag, m_prop.nametag_color);
975         }
976
977         updateNodePos();
978         updateAnimation();
979         updateBonePosition();
980         updateAttachments();
981 }
982
983 void GenericCAO::updateLight(u8 light_at_pos)
984 {
985         // Don't update light of attached one
986         if (getParent() != NULL) {
987                 return;
988         }
989
990         updateLightNoCheck(light_at_pos);
991
992         // Update light of all children
993         for (std::vector<u16>::size_type i = 0; i < m_children.size(); i++) {
994                 ClientActiveObject *obj = m_env->getActiveObject(m_children[i]);
995                 if (obj) {
996                         obj->updateLightNoCheck(light_at_pos);
997                 }
998         }
999 }
1000
1001 void GenericCAO::updateLightNoCheck(u8 light_at_pos)
1002 {
1003         u8 li = decode_light(light_at_pos);
1004         if (li != m_last_light) {
1005                 m_last_light = li;
1006                 video::SColor color(255,li,li,li);
1007                 if (m_meshnode) {
1008                         setMeshColor(m_meshnode->getMesh(), color);
1009                 } else if (m_animated_meshnode) {
1010                         setMeshColor(m_animated_meshnode->getMesh(), color);
1011                 } else if (m_wield_meshnode) {
1012                         m_wield_meshnode->setColor(color);
1013                 } else if (m_spritenode) {
1014                         m_spritenode->setColor(color);
1015                 }
1016         }
1017 }
1018
1019 v3s16 GenericCAO::getLightPosition()
1020 {
1021         return floatToInt(m_position, BS);
1022 }
1023
1024 void GenericCAO::updateNodePos()
1025 {
1026         if (getParent() != NULL)
1027                 return;
1028
1029         scene::ISceneNode *node = getSceneNode();
1030
1031         if (node) {
1032                 v3s16 camera_offset = m_env->getCameraOffset();
1033                 node->setPosition(pos_translator.vect_show - intToFloat(camera_offset, BS));
1034                 if (node != m_spritenode) { // rotate if not a sprite
1035                         v3f rot = node->getRotation();
1036                         rot.Y = -m_yaw;
1037                         node->setRotation(rot);
1038                 }
1039         }
1040 }
1041
1042 void GenericCAO::step(float dtime, ClientEnvironment *env)
1043 {
1044         // Handel model of local player instantly to prevent lags
1045         if (m_is_local_player) {
1046                 LocalPlayer *player = m_env->getLocalPlayer();
1047                 if (m_is_visible) {
1048                         int old_anim = player->last_animation;
1049                         float old_anim_speed = player->last_animation_speed;
1050                         m_position = player->getPosition() + v3f(0,BS,0);
1051                         m_velocity = v3f(0,0,0);
1052                         m_acceleration = v3f(0,0,0);
1053                         pos_translator.vect_show = m_position;
1054                         m_yaw = player->getYaw();
1055                         const PlayerControl &controls = player->getPlayerControl();
1056
1057                         bool walking = false;
1058                         if (controls.up || controls.down || controls.left || controls.right ||
1059                                         controls.forw_move_joystick_axis != 0.f ||
1060                                         controls.sidew_move_joystick_axis != 0.f)
1061                                 walking = true;
1062
1063                         f32 new_speed = player->local_animation_speed;
1064                         v2s32 new_anim = v2s32(0,0);
1065                         bool allow_update = false;
1066
1067                         // increase speed if using fast or flying fast
1068                         if((g_settings->getBool("fast_move") &&
1069                                         m_client->checkLocalPrivilege("fast")) &&
1070                                         (controls.aux1 ||
1071                                         (!player->touching_ground &&
1072                                         g_settings->getBool("free_move") &&
1073                                         m_client->checkLocalPrivilege("fly"))))
1074                                         new_speed *= 1.5;
1075                         // slowdown speed if sneeking
1076                         if (controls.sneak && walking)
1077                                 new_speed /= 2;
1078
1079                         if (walking && (controls.LMB || controls.RMB)) {
1080                                 new_anim = player->local_animations[3];
1081                                 player->last_animation = WD_ANIM;
1082                         } else if(walking) {
1083                                 new_anim = player->local_animations[1];
1084                                 player->last_animation = WALK_ANIM;
1085                         } else if(controls.LMB || controls.RMB) {
1086                                 new_anim = player->local_animations[2];
1087                                 player->last_animation = DIG_ANIM;
1088                         }
1089
1090                         // Apply animations if input detected and not attached
1091                         // or set idle animation
1092                         if ((new_anim.X + new_anim.Y) > 0 && !player->isAttached) {
1093                                 allow_update = true;
1094                                 m_animation_range = new_anim;
1095                                 m_animation_speed = new_speed;
1096                                 player->last_animation_speed = m_animation_speed;
1097                         } else {
1098                                 player->last_animation = NO_ANIM;
1099
1100                                 if (old_anim != NO_ANIM) {
1101                                         m_animation_range = player->local_animations[0];
1102                                         updateAnimation();
1103                                 }
1104                         }
1105
1106                         // Update local player animations
1107                         if ((player->last_animation != old_anim ||
1108                                 m_animation_speed != old_anim_speed) &&
1109                                 player->last_animation != NO_ANIM && allow_update)
1110                                         updateAnimation();
1111
1112                 }
1113         }
1114
1115         if(m_visuals_expired && m_smgr && m_irr){
1116                 m_visuals_expired = false;
1117
1118                 // Attachments, part 1: All attached objects must be unparented first,
1119                 // or Irrlicht causes a segmentation fault
1120                 for(std::vector<u16>::iterator ci = m_children.begin();
1121                                 ci != m_children.end();)
1122                 {
1123                         if (m_env->attachement_parent_ids[*ci] != getId()) {
1124                                 ci = m_children.erase(ci);
1125                                 continue;
1126                         }
1127                         ClientActiveObject *obj = m_env->getActiveObject(*ci);
1128                         if (obj) {
1129                                 scene::ISceneNode *child_node = obj->getSceneNode();
1130                                 if (child_node)
1131                                         child_node->setParent(m_smgr->getRootSceneNode());
1132                         }
1133                         ++ci;
1134                 }
1135
1136                 removeFromScene(false);
1137                 addToScene(m_smgr, m_client->tsrc(), m_irr);
1138
1139                 // Attachments, part 2: Now that the parent has been refreshed, put its attachments back
1140                 for (std::vector<u16>::size_type i = 0; i < m_children.size(); i++) {
1141                         // Get the object of the child
1142                         ClientActiveObject *obj = m_env->getActiveObject(m_children[i]);
1143                         if (obj)
1144                                 obj->setAttachments();
1145                 }
1146         }
1147
1148         // Make sure m_is_visible is always applied
1149         scene::ISceneNode *node = getSceneNode();
1150         if (node)
1151                 node->setVisible(m_is_visible);
1152
1153         if(getParent() != NULL) // Attachments should be glued to their parent by Irrlicht
1154         {
1155                 // Set these for later
1156                 m_position = getPosition();
1157                 m_velocity = v3f(0,0,0);
1158                 m_acceleration = v3f(0,0,0);
1159                 pos_translator.vect_show = m_position;
1160
1161                 if(m_is_local_player) // Update local player attachment position
1162                 {
1163                         LocalPlayer *player = m_env->getLocalPlayer();
1164                         player->overridePosition = getParent()->getPosition();
1165                         m_env->getLocalPlayer()->parent = getParent();
1166                 }
1167         } else {
1168                 v3f lastpos = pos_translator.vect_show;
1169
1170                 if(m_prop.physical)
1171                 {
1172                         aabb3f box = m_prop.collisionbox;
1173                         box.MinEdge *= BS;
1174                         box.MaxEdge *= BS;
1175                         collisionMoveResult moveresult;
1176                         f32 pos_max_d = BS*0.125; // Distance per iteration
1177                         v3f p_pos = m_position;
1178                         v3f p_velocity = m_velocity;
1179                         moveresult = collisionMoveSimple(env,env->getGameDef(),
1180                                         pos_max_d, box, m_prop.stepheight, dtime,
1181                                         &p_pos, &p_velocity, m_acceleration,
1182                                         this, m_prop.collideWithObjects);
1183                         // Apply results
1184                         m_position = p_pos;
1185                         m_velocity = p_velocity;
1186
1187                         bool is_end_position = moveresult.collides;
1188                         pos_translator.update(m_position, is_end_position, dtime);
1189                         pos_translator.translate(dtime);
1190                         updateNodePos();
1191                 } else {
1192                         m_position += dtime * m_velocity + 0.5 * dtime * dtime * m_acceleration;
1193                         m_velocity += dtime * m_acceleration;
1194                         pos_translator.update(m_position, pos_translator.aim_is_end,
1195                                         pos_translator.anim_time);
1196                         pos_translator.translate(dtime);
1197                         updateNodePos();
1198                 }
1199
1200                 float moved = lastpos.getDistanceFrom(pos_translator.vect_show);
1201                 m_step_distance_counter += moved;
1202                 if(m_step_distance_counter > 1.5*BS)
1203                 {
1204                         m_step_distance_counter = 0;
1205                         if(!m_is_local_player && m_prop.makes_footstep_sound)
1206                         {
1207                                 INodeDefManager *ndef = m_client->ndef();
1208                                 v3s16 p = floatToInt(getPosition() + v3f(0,
1209                                                 (m_prop.collisionbox.MinEdge.Y-0.5)*BS, 0), BS);
1210                                 MapNode n = m_env->getMap().getNodeNoEx(p);
1211                                 SimpleSoundSpec spec = ndef->get(n).sound_footstep;
1212                                 m_client->sound()->playSoundAt(spec, false, getPosition());
1213                         }
1214                 }
1215         }
1216
1217         m_anim_timer += dtime;
1218         if(m_anim_timer >= m_anim_framelength)
1219         {
1220                 m_anim_timer -= m_anim_framelength;
1221                 m_anim_frame++;
1222                 if(m_anim_frame >= m_anim_num_frames)
1223                         m_anim_frame = 0;
1224         }
1225
1226         updateTexturePos();
1227
1228         if(m_reset_textures_timer >= 0)
1229         {
1230                 m_reset_textures_timer -= dtime;
1231                 if(m_reset_textures_timer <= 0) {
1232                         m_reset_textures_timer = -1;
1233                         updateTextures(m_previous_texture_modifier);
1234                 }
1235         }
1236         if(getParent() == NULL && fabs(m_prop.automatic_rotate) > 0.001)
1237         {
1238                 m_yaw += dtime * m_prop.automatic_rotate * 180 / M_PI;
1239                 updateNodePos();
1240         }
1241
1242         if (getParent() == NULL && m_prop.automatic_face_movement_dir &&
1243                         (fabs(m_velocity.Z) > 0.001 || fabs(m_velocity.X) > 0.001))
1244         {
1245                 float optimal_yaw = atan2(m_velocity.Z,m_velocity.X) * 180 / M_PI
1246                                 + m_prop.automatic_face_movement_dir_offset;
1247                 float max_rotation_delta =
1248                                 dtime * m_prop.automatic_face_movement_max_rotation_per_sec;
1249
1250                 if ((m_prop.automatic_face_movement_max_rotation_per_sec > 0) &&
1251                         (fabs(m_yaw - optimal_yaw) > max_rotation_delta)) {
1252
1253                         m_yaw = optimal_yaw < m_yaw ? m_yaw - max_rotation_delta : m_yaw + max_rotation_delta;
1254                 } else {
1255                         m_yaw = optimal_yaw;
1256                 }
1257                 updateNodePos();
1258         }
1259 }
1260
1261 void GenericCAO::updateTexturePos()
1262 {
1263         if(m_spritenode)
1264         {
1265                 scene::ICameraSceneNode* camera =
1266                                 m_spritenode->getSceneManager()->getActiveCamera();
1267                 if(!camera)
1268                         return;
1269                 v3f cam_to_entity = m_spritenode->getAbsolutePosition()
1270                                 - camera->getAbsolutePosition();
1271                 cam_to_entity.normalize();
1272
1273                 int row = m_tx_basepos.Y;
1274                 int col = m_tx_basepos.X;
1275
1276                 if(m_tx_select_horiz_by_yawpitch)
1277                 {
1278                         if(cam_to_entity.Y > 0.75)
1279                                 col += 5;
1280                         else if(cam_to_entity.Y < -0.75)
1281                                 col += 4;
1282                         else{
1283                                 float mob_dir =
1284                                                 atan2(cam_to_entity.Z, cam_to_entity.X) / M_PI * 180.;
1285                                 float dir = mob_dir - m_yaw;
1286                                 dir = wrapDegrees_180(dir);
1287                                 //infostream<<"id="<<m_id<<" dir="<<dir<<std::endl;
1288                                 if(fabs(wrapDegrees_180(dir - 0)) <= 45.1)
1289                                         col += 2;
1290                                 else if(fabs(wrapDegrees_180(dir - 90)) <= 45.1)
1291                                         col += 3;
1292                                 else if(fabs(wrapDegrees_180(dir - 180)) <= 45.1)
1293                                         col += 0;
1294                                 else if(fabs(wrapDegrees_180(dir + 90)) <= 45.1)
1295                                         col += 1;
1296                                 else
1297                                         col += 4;
1298                         }
1299                 }
1300
1301                 // Animation goes downwards
1302                 row += m_anim_frame;
1303
1304                 float txs = m_tx_size.X;
1305                 float tys = m_tx_size.Y;
1306                 setBillboardTextureMatrix(m_spritenode,
1307                                 txs, tys, col, row);
1308         }
1309 }
1310
1311 void GenericCAO::updateTextures(std::string mod)
1312 {
1313         ITextureSource *tsrc = m_client->tsrc();
1314
1315         bool use_trilinear_filter = g_settings->getBool("trilinear_filter");
1316         bool use_bilinear_filter = g_settings->getBool("bilinear_filter");
1317         bool use_anisotropic_filter = g_settings->getBool("anisotropic_filter");
1318
1319         m_previous_texture_modifier = m_current_texture_modifier;
1320         m_current_texture_modifier = mod;
1321
1322         if(m_spritenode)
1323         {
1324                 if(m_prop.visual == "sprite")
1325                 {
1326                         std::string texturestring = "unknown_node.png";
1327                         if(m_prop.textures.size() >= 1)
1328                                 texturestring = m_prop.textures[0];
1329                         texturestring += mod;
1330                         m_spritenode->setMaterialTexture(0,
1331                                         tsrc->getTextureForMesh(texturestring));
1332
1333                         // This allows setting per-material colors. However, until a real lighting
1334                         // system is added, the code below will have no effect. Once MineTest
1335                         // has directional lighting, it should work automatically.
1336                         if(m_prop.colors.size() >= 1)
1337                         {
1338                                 m_spritenode->getMaterial(0).AmbientColor = m_prop.colors[0];
1339                                 m_spritenode->getMaterial(0).DiffuseColor = m_prop.colors[0];
1340                                 m_spritenode->getMaterial(0).SpecularColor = m_prop.colors[0];
1341                         }
1342
1343                         m_spritenode->getMaterial(0).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1344                         m_spritenode->getMaterial(0).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1345                         m_spritenode->getMaterial(0).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1346                 }
1347         }
1348         if(m_animated_meshnode)
1349         {
1350                 if(m_prop.visual == "mesh")
1351                 {
1352                         for (u32 i = 0; i < m_prop.textures.size() &&
1353                                         i < m_animated_meshnode->getMaterialCount(); ++i)
1354                         {
1355                                 std::string texturestring = m_prop.textures[i];
1356                                 if(texturestring == "")
1357                                         continue; // Empty texture string means don't modify that material
1358                                 texturestring += mod;
1359                                 video::ITexture* texture = tsrc->getTextureForMesh(texturestring);
1360                                 if(!texture)
1361                                 {
1362                                         errorstream<<"GenericCAO::updateTextures(): Could not load texture "<<texturestring<<std::endl;
1363                                         continue;
1364                                 }
1365
1366                                 // Set material flags and texture
1367                                 video::SMaterial& material = m_animated_meshnode->getMaterial(i);
1368                                 material.TextureLayer[0].Texture = texture;
1369                                 material.setFlag(video::EMF_LIGHTING, false);
1370                                 material.setFlag(video::EMF_BILINEAR_FILTER, false);
1371
1372                                 m_animated_meshnode->getMaterial(i)
1373                                                 .setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1374                                 m_animated_meshnode->getMaterial(i)
1375                                                 .setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1376                                 m_animated_meshnode->getMaterial(i)
1377                                                 .setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1378                         }
1379                         for (u32 i = 0; i < m_prop.colors.size() &&
1380                         i < m_animated_meshnode->getMaterialCount(); ++i)
1381                         {
1382                                 // This allows setting per-material colors. However, until a real lighting
1383                                 // system is added, the code below will have no effect. Once MineTest
1384                                 // has directional lighting, it should work automatically.
1385                                 m_animated_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i];
1386                                 m_animated_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i];
1387                                 m_animated_meshnode->getMaterial(i).SpecularColor = m_prop.colors[i];
1388                         }
1389                 }
1390         }
1391         if(m_meshnode)
1392         {
1393                 if(m_prop.visual == "cube")
1394                 {
1395                         for (u32 i = 0; i < 6; ++i)
1396                         {
1397                                 std::string texturestring = "unknown_node.png";
1398                                 if(m_prop.textures.size() > i)
1399                                         texturestring = m_prop.textures[i];
1400                                 texturestring += mod;
1401
1402
1403                                 // Set material flags and texture
1404                                 video::SMaterial& material = m_meshnode->getMaterial(i);
1405                                 material.setFlag(video::EMF_LIGHTING, false);
1406                                 material.setFlag(video::EMF_BILINEAR_FILTER, false);
1407                                 material.setTexture(0,
1408                                                 tsrc->getTextureForMesh(texturestring));
1409                                 material.getTextureMatrix(0).makeIdentity();
1410
1411                                 // This allows setting per-material colors. However, until a real lighting
1412                                 // system is added, the code below will have no effect. Once MineTest
1413                                 // has directional lighting, it should work automatically.
1414                                 if(m_prop.colors.size() > i)
1415                                 {
1416                                         m_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i];
1417                                         m_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i];
1418                                         m_meshnode->getMaterial(i).SpecularColor = m_prop.colors[i];
1419                                 }
1420
1421                                 m_meshnode->getMaterial(i).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1422                                 m_meshnode->getMaterial(i).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1423                                 m_meshnode->getMaterial(i).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1424                         }
1425                 }
1426                 else if(m_prop.visual == "upright_sprite")
1427                 {
1428                         scene::IMesh *mesh = m_meshnode->getMesh();
1429                         {
1430                                 std::string tname = "unknown_object.png";
1431                                 if(m_prop.textures.size() >= 1)
1432                                         tname = m_prop.textures[0];
1433                                 tname += mod;
1434                                 scene::IMeshBuffer *buf = mesh->getMeshBuffer(0);
1435                                 buf->getMaterial().setTexture(0,
1436                                                 tsrc->getTextureForMesh(tname));
1437
1438                                 // This allows setting per-material colors. However, until a real lighting
1439                                 // system is added, the code below will have no effect. Once MineTest
1440                                 // has directional lighting, it should work automatically.
1441                                 if(m_prop.colors.size() >= 1)
1442                                 {
1443                                         buf->getMaterial().AmbientColor = m_prop.colors[0];
1444                                         buf->getMaterial().DiffuseColor = m_prop.colors[0];
1445                                         buf->getMaterial().SpecularColor = m_prop.colors[0];
1446                                 }
1447
1448                                 buf->getMaterial().setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1449                                 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1450                                 buf->getMaterial().setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1451                         }
1452                         {
1453                                 std::string tname = "unknown_object.png";
1454                                 if(m_prop.textures.size() >= 2)
1455                                         tname = m_prop.textures[1];
1456                                 else if(m_prop.textures.size() >= 1)
1457                                         tname = m_prop.textures[0];
1458                                 tname += mod;
1459                                 scene::IMeshBuffer *buf = mesh->getMeshBuffer(1);
1460                                 buf->getMaterial().setTexture(0,
1461                                                 tsrc->getTextureForMesh(tname));
1462
1463                                 // This allows setting per-material colors. However, until a real lighting
1464                                 // system is added, the code below will have no effect. Once MineTest
1465                                 // has directional lighting, it should work automatically.
1466                                 if(m_prop.colors.size() >= 2)
1467                                 {
1468                                         buf->getMaterial().AmbientColor = m_prop.colors[1];
1469                                         buf->getMaterial().DiffuseColor = m_prop.colors[1];
1470                                         buf->getMaterial().SpecularColor = m_prop.colors[1];
1471                                 }
1472                                 else if(m_prop.colors.size() >= 1)
1473                                 {
1474                                         buf->getMaterial().AmbientColor = m_prop.colors[0];
1475                                         buf->getMaterial().DiffuseColor = m_prop.colors[0];
1476                                         buf->getMaterial().SpecularColor = m_prop.colors[0];
1477                                 }
1478
1479                                 buf->getMaterial().setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1480                                 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1481                                 buf->getMaterial().setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1482                         }
1483                 }
1484         }
1485 }
1486
1487 void GenericCAO::updateAnimation()
1488 {
1489         if(m_animated_meshnode == NULL)
1490                 return;
1491
1492         if (m_animated_meshnode->getStartFrame() != m_animation_range.X ||
1493                 m_animated_meshnode->getEndFrame() != m_animation_range.Y)
1494                         m_animated_meshnode->setFrameLoop(m_animation_range.X, m_animation_range.Y);
1495         if (m_animated_meshnode->getAnimationSpeed() != m_animation_speed)
1496                 m_animated_meshnode->setAnimationSpeed(m_animation_speed);
1497         m_animated_meshnode->setTransitionTime(m_animation_blend);
1498 // Requires Irrlicht 1.8 or greater
1499 #if (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR > 1
1500         if (m_animated_meshnode->getLoopMode() != m_animation_loop)
1501                 m_animated_meshnode->setLoopMode(m_animation_loop);
1502 #endif
1503 }
1504
1505 void GenericCAO::updateBonePosition()
1506 {
1507         if(m_bone_position.empty() || m_animated_meshnode == NULL)
1508                 return;
1509
1510         m_animated_meshnode->setJointMode(irr::scene::EJUOR_CONTROL); // To write positions to the mesh on render
1511         for(UNORDERED_MAP<std::string, core::vector2d<v3f> >::const_iterator
1512                         ii = m_bone_position.begin(); ii != m_bone_position.end(); ++ii) {
1513                 std::string bone_name = (*ii).first;
1514                 v3f bone_pos = (*ii).second.X;
1515                 v3f bone_rot = (*ii).second.Y;
1516                 irr::scene::IBoneSceneNode* bone = m_animated_meshnode->getJointNode(bone_name.c_str());
1517                 if(bone)
1518                 {
1519                         bone->setPosition(bone_pos);
1520                         bone->setRotation(bone_rot);
1521                 }
1522         }
1523 }
1524
1525 void GenericCAO::updateAttachments()
1526 {
1527
1528         if (getParent() == NULL) { // Detach or don't attach
1529                 scene::ISceneNode *node = getSceneNode();
1530                 if (node) {
1531                         v3f old_position = node->getAbsolutePosition();
1532                         v3f old_rotation = node->getRotation();
1533                         node->setParent(m_smgr->getRootSceneNode());
1534                         node->setPosition(old_position);
1535                         node->setRotation(old_rotation);
1536                         node->updateAbsolutePosition();
1537                 }
1538                 if (m_is_local_player) {
1539                         LocalPlayer *player = m_env->getLocalPlayer();
1540                         player->isAttached = false;
1541                 }
1542         }
1543         else // Attach
1544         {
1545                 scene::ISceneNode *my_node = getSceneNode();
1546
1547                 scene::ISceneNode *parent_node = getParent()->getSceneNode();
1548                 scene::IAnimatedMeshSceneNode *parent_animated_mesh_node =
1549                                 getParent()->getAnimatedMeshSceneNode();
1550                 if (parent_animated_mesh_node && m_attachment_bone != "") {
1551                         parent_node = parent_animated_mesh_node->getJointNode(m_attachment_bone.c_str());
1552                 }
1553
1554                 if (my_node && parent_node) {
1555                         my_node->setParent(parent_node);
1556                         my_node->setPosition(m_attachment_position);
1557                         my_node->setRotation(m_attachment_rotation);
1558                         my_node->updateAbsolutePosition();
1559                 }
1560                 if (m_is_local_player) {
1561                         LocalPlayer *player = m_env->getLocalPlayer();
1562                         player->isAttached = true;
1563                 }
1564         }
1565 }
1566
1567 void GenericCAO::processMessage(const std::string &data)
1568 {
1569         //infostream<<"GenericCAO: Got message"<<std::endl;
1570         std::istringstream is(data, std::ios::binary);
1571         // command
1572         u8 cmd = readU8(is);
1573         if (cmd == GENERIC_CMD_SET_PROPERTIES) {
1574                 m_prop = gob_read_set_properties(is);
1575
1576                 m_selection_box = m_prop.collisionbox;
1577                 m_selection_box.MinEdge *= BS;
1578                 m_selection_box.MaxEdge *= BS;
1579
1580                 m_tx_size.X = 1.0 / m_prop.spritediv.X;
1581                 m_tx_size.Y = 1.0 / m_prop.spritediv.Y;
1582
1583                 if(!m_initial_tx_basepos_set){
1584                         m_initial_tx_basepos_set = true;
1585                         m_tx_basepos = m_prop.initial_sprite_basepos;
1586                 }
1587                 if (m_is_local_player) {
1588                         LocalPlayer *player = m_env->getLocalPlayer();
1589                         player->makes_footstep_sound = m_prop.makes_footstep_sound;
1590                 }
1591
1592                 if ((m_is_player && !m_is_local_player) && m_prop.nametag == "")
1593                         m_prop.nametag = m_name;
1594
1595                 expireVisuals();
1596         } else if (cmd == GENERIC_CMD_UPDATE_POSITION) {
1597                 // Not sent by the server if this object is an attachment.
1598                 // We might however get here if the server notices the object being detached before the client.
1599                 m_position = readV3F1000(is);
1600                 m_velocity = readV3F1000(is);
1601                 m_acceleration = readV3F1000(is);
1602                 if(fabs(m_prop.automatic_rotate) < 0.001)
1603                         m_yaw = readF1000(is);
1604                 else
1605                         readF1000(is);
1606                 bool do_interpolate = readU8(is);
1607                 bool is_end_position = readU8(is);
1608                 float update_interval = readF1000(is);
1609
1610                 // Place us a bit higher if we're physical, to not sink into
1611                 // the ground due to sucky collision detection...
1612                 if(m_prop.physical)
1613                         m_position += v3f(0,0.002,0);
1614
1615                 if(getParent() != NULL) // Just in case
1616                         return;
1617
1618                 if(do_interpolate)
1619                 {
1620                         if(!m_prop.physical)
1621                                 pos_translator.update(m_position, is_end_position, update_interval);
1622                 } else {
1623                         pos_translator.init(m_position);
1624                 }
1625                 updateNodePos();
1626         } else if (cmd == GENERIC_CMD_SET_TEXTURE_MOD) {
1627                 std::string mod = deSerializeString(is);
1628
1629                 // immediatly reset a engine issued texture modifier if a mod sends a different one
1630                 if (m_reset_textures_timer > 0) {
1631                         m_reset_textures_timer = -1;
1632                         updateTextures(m_previous_texture_modifier);
1633                 }
1634                 updateTextures(mod);
1635         } else if (cmd == GENERIC_CMD_SET_SPRITE) {
1636                 v2s16 p = readV2S16(is);
1637                 int num_frames = readU16(is);
1638                 float framelength = readF1000(is);
1639                 bool select_horiz_by_yawpitch = readU8(is);
1640
1641                 m_tx_basepos = p;
1642                 m_anim_num_frames = num_frames;
1643                 m_anim_framelength = framelength;
1644                 m_tx_select_horiz_by_yawpitch = select_horiz_by_yawpitch;
1645
1646                 updateTexturePos();
1647         } else if (cmd == GENERIC_CMD_SET_PHYSICS_OVERRIDE) {
1648                 float override_speed = readF1000(is);
1649                 float override_jump = readF1000(is);
1650                 float override_gravity = readF1000(is);
1651                 // these are sent inverted so we get true when the server sends nothing
1652                 bool sneak = !readU8(is);
1653                 bool sneak_glitch = !readU8(is);
1654                 bool new_move = !readU8(is);
1655
1656
1657                 if(m_is_local_player)
1658                 {
1659                         LocalPlayer *player = m_env->getLocalPlayer();
1660                         player->physics_override_speed = override_speed;
1661                         player->physics_override_jump = override_jump;
1662                         player->physics_override_gravity = override_gravity;
1663                         player->physics_override_sneak = sneak;
1664                         player->physics_override_sneak_glitch = sneak_glitch;
1665                         player->physics_override_new_move = new_move;
1666                 }
1667         } else if (cmd == GENERIC_CMD_SET_ANIMATION) {
1668                 // TODO: change frames send as v2s32 value
1669                 v2f range = readV2F1000(is);
1670                 if (!m_is_local_player) {
1671                         m_animation_range = v2s32((s32)range.X, (s32)range.Y);
1672                         m_animation_speed = readF1000(is);
1673                         m_animation_blend = readF1000(is);
1674                         // these are sent inverted so we get true when the server sends nothing
1675                         m_animation_loop = !readU8(is);
1676                         updateAnimation();
1677                 } else {
1678                         LocalPlayer *player = m_env->getLocalPlayer();
1679                         if(player->last_animation == NO_ANIM)
1680                         {
1681                                 m_animation_range = v2s32((s32)range.X, (s32)range.Y);
1682                                 m_animation_speed = readF1000(is);
1683                                 m_animation_blend = readF1000(is);
1684                                 // these are sent inverted so we get true when the server sends nothing
1685                                 m_animation_loop = !readU8(is);
1686                         }
1687                         // update animation only if local animations present
1688                         // and received animation is unknown (except idle animation)
1689                         bool is_known = false;
1690                         for (int i = 1;i<4;i++)
1691                         {
1692                                 if(m_animation_range.Y == player->local_animations[i].Y)
1693                                         is_known = true;
1694                         }
1695                         if(!is_known ||
1696                                         (player->local_animations[1].Y + player->local_animations[2].Y < 1))
1697                         {
1698                                         updateAnimation();
1699                         }
1700                 }
1701         } else if (cmd == GENERIC_CMD_SET_BONE_POSITION) {
1702                 std::string bone = deSerializeString(is);
1703                 v3f position = readV3F1000(is);
1704                 v3f rotation = readV3F1000(is);
1705                 m_bone_position[bone] = core::vector2d<v3f>(position, rotation);
1706
1707                 updateBonePosition();
1708         } else if (cmd == GENERIC_CMD_ATTACH_TO) {
1709                 u16 parentID = readS16(is);
1710                 u16 oldparent = m_env->attachement_parent_ids[getId()];
1711                 if (oldparent) {
1712                         m_children.erase(std::remove(m_children.begin(), m_children.end(),
1713                                 getId()), m_children.end());
1714                 }
1715                 m_env->attachement_parent_ids[getId()] = parentID;
1716                 GenericCAO *parentobj = m_env->getGenericCAO(parentID);
1717
1718                 if (parentobj) {
1719                         parentobj->m_children.push_back(getId());
1720                 }
1721
1722                 m_attachment_bone = deSerializeString(is);
1723                 m_attachment_position = readV3F1000(is);
1724                 m_attachment_rotation = readV3F1000(is);
1725
1726                 // localplayer itself can't be attached to localplayer
1727                 if (!m_is_local_player) {
1728                         m_attached_to_local = getParent() != NULL && getParent()->isLocalPlayer();
1729                         // Objects attached to the local player should be hidden by default
1730                         m_is_visible = !m_attached_to_local;
1731                 }
1732
1733                 updateAttachments();
1734         } else if (cmd == GENERIC_CMD_PUNCHED) {
1735                 /*s16 damage =*/ readS16(is);
1736                 s16 result_hp = readS16(is);
1737
1738                 // Use this instead of the send damage to not interfere with prediction
1739                 s16 damage = m_hp - result_hp;
1740
1741                 m_hp = result_hp;
1742
1743                 if (damage > 0)
1744                 {
1745                         if (m_hp <= 0)
1746                         {
1747                                 // TODO: Execute defined fast response
1748                                 // As there is no definition, make a smoke puff
1749                                 ClientSimpleObject *simple = createSmokePuff(
1750                                                 m_smgr, m_env, m_position,
1751                                                 m_prop.visual_size * BS);
1752                                 m_env->addSimpleObject(simple);
1753                         } else {
1754                                 // TODO: Execute defined fast response
1755                                 // Flashing shall suffice as there is no definition
1756                                 m_reset_textures_timer = 0.05;
1757                                 if(damage >= 2)
1758                                         m_reset_textures_timer += 0.05 * damage;
1759                                 updateTextures(m_current_texture_modifier + "^[brighten");
1760                         }
1761                 }
1762         } else if (cmd == GENERIC_CMD_UPDATE_ARMOR_GROUPS) {
1763                 m_armor_groups.clear();
1764                 int armor_groups_size = readU16(is);
1765                 for(int i=0; i<armor_groups_size; i++)
1766                 {
1767                         std::string name = deSerializeString(is);
1768                         int rating = readS16(is);
1769                         m_armor_groups[name] = rating;
1770                 }
1771         } else if (cmd == GENERIC_CMD_UPDATE_NAMETAG_ATTRIBUTES) {
1772                 // Deprecated, for backwards compatibility only.
1773                 readU8(is); // version
1774                 m_prop.nametag_color = readARGB8(is);
1775                 if (m_nametag != NULL) {
1776                         m_nametag->nametag_color = m_prop.nametag_color;
1777                 }
1778         } else if (cmd == GENERIC_CMD_SPAWN_INFANT) {
1779                 u16 child_id = readU16(is);
1780                 u8 type = readU8(is);
1781
1782                 if (GenericCAO *childobj = m_env->getGenericCAO(child_id)) {
1783                         childobj->processInitData(deSerializeLongString(is));
1784                 } else {
1785                         m_env->addActiveObject(child_id, type, deSerializeLongString(is));
1786                 }
1787         } else {
1788                 warningstream << FUNCTION_NAME
1789                         << ": unknown command or outdated client \""
1790                         << +cmd << "\"" << std::endl;
1791         }
1792 }
1793
1794 /* \pre punchitem != NULL
1795  */
1796 bool GenericCAO::directReportPunch(v3f dir, const ItemStack *punchitem,
1797                 float time_from_last_punch)
1798 {
1799         assert(punchitem);      // pre-condition
1800         const ToolCapabilities *toolcap =
1801                         &punchitem->getToolCapabilities(m_client->idef());
1802         PunchDamageResult result = getPunchDamage(
1803                         m_armor_groups,
1804                         toolcap,
1805                         punchitem,
1806                         time_from_last_punch);
1807
1808         if(result.did_punch && result.damage != 0)
1809         {
1810                 if(result.damage < m_hp)
1811                 {
1812                         m_hp -= result.damage;
1813                 } else {
1814                         m_hp = 0;
1815                         // TODO: Execute defined fast response
1816                         // As there is no definition, make a smoke puff
1817                         ClientSimpleObject *simple = createSmokePuff(
1818                                         m_smgr, m_env, m_position,
1819                                         m_prop.visual_size * BS);
1820                         m_env->addSimpleObject(simple);
1821                 }
1822                 // TODO: Execute defined fast response
1823                 // Flashing shall suffice as there is no definition
1824                 m_reset_textures_timer = 0.05;
1825                 if(result.damage >= 2)
1826                         m_reset_textures_timer += 0.05 * result.damage;
1827                 updateTextures(m_current_texture_modifier + "^[brighten");
1828         }
1829
1830         return false;
1831 }
1832
1833 std::string GenericCAO::debugInfoText()
1834 {
1835         std::ostringstream os(std::ios::binary);
1836         os<<"GenericCAO hp="<<m_hp<<"\n";
1837         os<<"armor={";
1838         for(ItemGroupList::const_iterator i = m_armor_groups.begin();
1839                         i != m_armor_groups.end(); ++i)
1840         {
1841                 os<<i->first<<"="<<i->second<<", ";
1842         }
1843         os<<"}";
1844         return os.str();
1845 }
1846
1847 // Prototype
1848 GenericCAO proto_GenericCAO(NULL, NULL);