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