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