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