]> git.lizzy.rs Git - minetest.git/blob - src/content_cao.cpp
Update ContentFeatures serialization format now as PROTOCOL_VERSION was changed
[minetest.git] / src / content_cao.cpp
1 /*
2 Minetest-c55
3 Copyright (C) 2010-2011 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 core::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 = item.getDefinition(idef).inventory_texture;
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                 // version
651                 u8 version = readU8(is);
652                 // check version
653                 if(version != 0){
654                         errorstream<<"GenericCAO: Unsupported init data version"
655                                         <<std::endl;
656                         return;
657                 }
658                 m_name = deSerializeString(is);
659                 m_is_player = readU8(is);
660                 m_id = readS16(is);
661                 m_position = readV3F1000(is);
662                 m_yaw = readF1000(is);
663                 m_hp = readS16(is);
664                 
665                 int num_messages = readU8(is);
666                 for(int i=0; i<num_messages; i++){
667                         std::string message = deSerializeLongString(is);
668                         processMessage(message);
669                 }
670
671                 pos_translator.init(m_position);
672                 updateNodePos();
673                 
674                 if(m_is_player){
675                         Player *player = m_env->getPlayer(m_name.c_str());
676                         if(player && player->isLocal()){
677                                 m_is_local_player = true;
678                         }
679                 }
680         }
681
682         ~GenericCAO()
683         {
684         }
685
686         static ClientActiveObject* create(IGameDef *gamedef, ClientEnvironment *env)
687         {
688                 return new GenericCAO(gamedef, env);
689         }
690
691         u8 getType() const
692         {
693                 return ACTIVEOBJECT_TYPE_GENERIC;
694         }
695         core::aabbox3d<f32>* getSelectionBox()
696         {
697                 if(!m_prop.is_visible || !m_is_visible || m_is_local_player || getParent() != NULL)
698                         return NULL;
699                 return &m_selection_box;
700         }
701         v3f getPosition()
702         {
703                 if(getParent() != NULL){
704                         if(m_meshnode)
705                                 return m_meshnode->getAbsolutePosition();
706                         if(m_animated_meshnode)
707                                 return m_animated_meshnode->getAbsolutePosition();
708                         if(m_spritenode)
709                                 return m_spritenode->getAbsolutePosition();
710                         return m_position;
711                 }
712                 return pos_translator.vect_show;
713         }
714
715         scene::IMeshSceneNode *getMeshSceneNode()
716         {
717                 if(m_meshnode)
718                         return m_meshnode;
719                 return NULL;
720         }
721
722         scene::IAnimatedMeshSceneNode *getAnimatedMeshSceneNode()
723         {
724                 if(m_animated_meshnode)
725                         return m_animated_meshnode;
726                 return NULL;
727         }
728
729         scene::IBillboardSceneNode *getSpriteSceneNode()
730         {
731                 if(m_spritenode)
732                         return m_spritenode;
733                 return NULL;
734         }
735
736         bool isPlayer()
737         {
738                 return m_is_player;
739         }
740
741         bool isLocalPlayer()
742         {
743                 return m_is_local_player;
744         }
745
746         void setAttachments()
747         {
748                 updateAttachments();
749         }
750
751         ClientActiveObject *getParent()
752         {
753                 ClientActiveObject *obj = NULL;
754                 for(std::vector<core::vector2d<int> >::const_iterator cii = m_env->attachment_list.begin(); cii != m_env->attachment_list.end(); cii++)
755                 {
756                         if(cii->X == getId()){ // This ID is our child
757                                 if(cii->Y > 0){ // A parent ID exists for our child
758                                         if(cii->X != cii->Y){ // The parent and child ID are not the same
759                                                 obj = m_env->getActiveObject(cii->Y);
760                                         }
761                                 }
762                                 break;
763                         }
764                 }
765                 if(obj)
766                         return obj;
767                 return NULL;
768         }
769
770         void removeFromScene(bool permanent)
771         {
772                 if(permanent) // Should be true when removing the object permanently and false when refreshing (eg: updating visuals)
773                 {
774                         // Detach this object's children
775                         for(std::vector<core::vector2d<int> >::iterator ii = m_env->attachment_list.begin(); ii != m_env->attachment_list.end(); ii++)
776                         {
777                                 if(ii->Y == getId()) // Is a child of our object
778                                 {
779                                         ii->Y = 0;
780                                         ClientActiveObject *obj = m_env->getActiveObject(ii->X); // Get the object of the child
781                                         if(obj)
782                                                 obj->setAttachments();
783                                 }
784                         }
785                         // Delete this object from the attachments list
786                         for(std::vector<core::vector2d<int> >::iterator ii = m_env->attachment_list.begin(); ii != m_env->attachment_list.end(); ii++)
787                         {
788                                 if(ii->X == getId()) // Is our object
789                                 {
790                                         m_env->attachment_list.erase(ii);
791                                         break;
792                                 }
793                         }
794                 }
795
796                 if(m_meshnode){
797                         m_meshnode->remove();
798                         m_meshnode = NULL;
799                 }
800                 if(m_animated_meshnode){
801                         m_animated_meshnode->remove();
802                         m_animated_meshnode = NULL;
803                 }
804                 if(m_spritenode){
805                         m_spritenode->remove();
806                         m_spritenode = NULL;
807                 }
808         }
809
810         void addToScene(scene::ISceneManager *smgr, ITextureSource *tsrc,
811                         IrrlichtDevice *irr)
812         {
813                 m_smgr = smgr;
814                 m_irr = irr;
815
816                 if(m_meshnode != NULL || m_animated_meshnode != NULL || m_spritenode != NULL)
817                         return;
818                 
819                 m_visuals_expired = false;
820
821                 if(!m_prop.is_visible || m_is_local_player)
822                         return;
823         
824                 //video::IVideoDriver* driver = smgr->getVideoDriver();
825
826                 if(m_prop.visual == "sprite"){
827                         infostream<<"GenericCAO::addToScene(): single_sprite"<<std::endl;
828                         m_spritenode = smgr->addBillboardSceneNode(
829                                         NULL, v2f(1, 1), v3f(0,0,0), -1);
830                         m_spritenode->setMaterialTexture(0,
831                                         tsrc->getTextureRaw("unknown_block.png"));
832                         m_spritenode->setMaterialFlag(video::EMF_LIGHTING, false);
833                         m_spritenode->setMaterialFlag(video::EMF_BILINEAR_FILTER, false);
834                         m_spritenode->setMaterialType(video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF);
835                         m_spritenode->setMaterialFlag(video::EMF_FOG_ENABLE, true);
836                         u8 li = m_last_light;
837                         m_spritenode->setColor(video::SColor(255,li,li,li));
838                         m_spritenode->setSize(m_prop.visual_size*BS);
839                         {
840                                 const float txs = 1.0 / 1;
841                                 const float tys = 1.0 / 1;
842                                 setBillboardTextureMatrix(m_spritenode,
843                                                 txs, tys, 0, 0);
844                         }
845                 }
846                 else if(m_prop.visual == "upright_sprite")
847                 {
848                         scene::SMesh *mesh = new scene::SMesh();
849                         double dx = BS*m_prop.visual_size.X/2;
850                         double dy = BS*m_prop.visual_size.Y/2;
851                         { // Front
852                         scene::IMeshBuffer *buf = new scene::SMeshBuffer();
853                         u8 li = m_last_light;
854                         video::SColor c(255,li,li,li);
855                         video::S3DVertex vertices[4] =
856                         {
857                                 video::S3DVertex(-dx,-dy,0, 0,0,0, c, 0,1),
858                                 video::S3DVertex(dx,-dy,0, 0,0,0, c, 1,1),
859                                 video::S3DVertex(dx,dy,0, 0,0,0, c, 1,0),
860                                 video::S3DVertex(-dx,dy,0, 0,0,0, c, 0,0),
861                         };
862                         u16 indices[] = {0,1,2,2,3,0};
863                         buf->append(vertices, 4, indices, 6);
864                         // Set material
865                         buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
866                         buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
867                         buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
868                         buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
869                         // Add to mesh
870                         mesh->addMeshBuffer(buf);
871                         buf->drop();
872                         }
873                         { // Back
874                         scene::IMeshBuffer *buf = new scene::SMeshBuffer();
875                         u8 li = m_last_light;
876                         video::SColor c(255,li,li,li);
877                         video::S3DVertex vertices[4] =
878                         {
879                                 video::S3DVertex(dx,-dy,0, 0,0,0, c, 1,1),
880                                 video::S3DVertex(-dx,-dy,0, 0,0,0, c, 0,1),
881                                 video::S3DVertex(-dx,dy,0, 0,0,0, c, 0,0),
882                                 video::S3DVertex(dx,dy,0, 0,0,0, c, 1,0),
883                         };
884                         u16 indices[] = {0,1,2,2,3,0};
885                         buf->append(vertices, 4, indices, 6);
886                         // Set material
887                         buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
888                         buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
889                         buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
890                         buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
891                         // Add to mesh
892                         mesh->addMeshBuffer(buf);
893                         buf->drop();
894                         }
895                         m_meshnode = smgr->addMeshSceneNode(mesh, NULL);
896                         mesh->drop();
897                         // Set it to use the materials of the meshbuffers directly.
898                         // This is needed for changing the texture in the future
899                         m_meshnode->setReadOnlyMaterials(true);
900                 }
901                 else if(m_prop.visual == "cube"){
902                         infostream<<"GenericCAO::addToScene(): cube"<<std::endl;
903                         scene::IMesh *mesh = createCubeMesh(v3f(BS,BS,BS));
904                         m_meshnode = smgr->addMeshSceneNode(mesh, NULL);
905                         mesh->drop();
906                         
907                         m_meshnode->setScale(v3f(m_prop.visual_size.X,
908                                         m_prop.visual_size.Y,
909                                         m_prop.visual_size.X));
910                         u8 li = m_last_light;
911                         setMeshColor(m_meshnode->getMesh(), video::SColor(255,li,li,li));
912                 }
913                 else if(m_prop.visual == "mesh"){
914                         infostream<<"GenericCAO::addToScene(): mesh"<<std::endl;
915                         scene::IAnimatedMesh *mesh = smgr->getMesh(m_prop.mesh.c_str());
916                         if(mesh)
917                         {
918                                 m_animated_meshnode = smgr->addAnimatedMeshSceneNode(mesh, NULL);
919                                 m_animated_meshnode->animateJoints(); // Needed for some animations
920                                 m_animated_meshnode->setScale(v3f(m_prop.visual_size.X,
921                                                 m_prop.visual_size.Y,
922                                                 m_prop.visual_size.X));
923                                 u8 li = m_last_light;
924                                 setMeshColor(m_animated_meshnode->getMesh(), video::SColor(255,li,li,li));
925                         }
926                         else
927                                 errorstream<<"GenericCAO::addToScene(): Could not load mesh "<<m_prop.mesh<<std::endl;
928                 }
929                 else if(m_prop.visual == "wielditem"){
930                         infostream<<"GenericCAO::addToScene(): node"<<std::endl;
931                         infostream<<"textures: "<<m_prop.textures.size()<<std::endl;
932                         if(m_prop.textures.size() >= 1){
933                                 infostream<<"textures[0]: "<<m_prop.textures[0]<<std::endl;
934                                 IItemDefManager *idef = m_gamedef->idef();
935                                 ItemStack item(m_prop.textures[0], 1, 0, "", idef);
936                                 scene::IMesh *item_mesh = item.getDefinition(idef).wield_mesh;
937                                 
938                                 // Copy mesh to be able to set unique vertex colors
939                                 scene::IMeshManipulator *manip =
940                                                 irr->getVideoDriver()->getMeshManipulator();
941                                 scene::IMesh *mesh = manip->createMeshUniquePrimitives(item_mesh);
942
943                                 m_meshnode = smgr->addMeshSceneNode(mesh, NULL);
944                                 mesh->drop();
945                                 
946                                 m_meshnode->setScale(v3f(m_prop.visual_size.X/2,
947                                                 m_prop.visual_size.Y/2,
948                                                 m_prop.visual_size.X/2));
949                                 u8 li = m_last_light;
950                                 setMeshColor(m_meshnode->getMesh(), video::SColor(255,li,li,li));
951                         }
952                 } else {
953                         infostream<<"GenericCAO::addToScene(): \""<<m_prop.visual
954                                         <<"\" not supported"<<std::endl;
955                 }
956                 updateTextures("");
957                 
958                 scene::ISceneNode *node = NULL;
959                 if(m_spritenode)
960                         node = m_spritenode;
961                 else if(m_animated_meshnode)
962                         node = m_animated_meshnode;
963                 else if(m_meshnode)
964                         node = m_meshnode;
965                 if(node && m_is_player && !m_is_local_player){
966                         // Add a text node for showing the name
967                         gui::IGUIEnvironment* gui = irr->getGUIEnvironment();
968                         std::wstring wname = narrow_to_wide(m_name);
969                         m_textnode = smgr->addTextSceneNode(gui->getBuiltInFont(),
970                                         wname.c_str(), video::SColor(255,255,255,255), node);
971                         m_textnode->setPosition(v3f(0, BS*1.1, 0));
972                 }
973
974                 updateNodePos();
975                 updateAnimation();
976                 updateBonePosition();
977                 updateAttachments();
978         }
979
980         void expireVisuals()
981         {
982                 m_visuals_expired = true;
983         }
984                 
985         void updateLight(u8 light_at_pos)
986         {
987                 u8 li = decode_light(light_at_pos);
988                 if(li != m_last_light){
989                         m_last_light = li;
990                         video::SColor color(255,li,li,li);
991                         if(m_meshnode)
992                                 setMeshColor(m_meshnode->getMesh(), color);
993                         if(m_animated_meshnode)
994                                 setMeshColor(m_animated_meshnode->getMesh(), color);
995                         if(m_spritenode)
996                                 m_spritenode->setColor(color);
997                 }
998         }
999
1000         v3s16 getLightPosition()
1001         {
1002                 return floatToInt(m_position, BS);
1003         }
1004
1005         void updateNodePos()
1006         {
1007                 if(getParent() != NULL)
1008                         return;
1009
1010                 if(m_meshnode){
1011                         m_meshnode->setPosition(pos_translator.vect_show);
1012                         v3f rot = m_meshnode->getRotation();
1013                         rot.Y = -m_yaw;
1014                         m_meshnode->setRotation(rot);
1015                 }
1016                 if(m_animated_meshnode){
1017                         m_animated_meshnode->setPosition(pos_translator.vect_show);
1018                         v3f rot = m_animated_meshnode->getRotation();
1019                         rot.Y = -m_yaw;
1020                         m_animated_meshnode->setRotation(rot);
1021                 }
1022                 if(m_spritenode){
1023                         m_spritenode->setPosition(pos_translator.vect_show);
1024                 }
1025         }
1026
1027         void step(float dtime, ClientEnvironment *env)
1028         {
1029                 if(m_visuals_expired && m_smgr && m_irr){
1030                         m_visuals_expired = false;
1031
1032                         // Attachments, part 1: All attached objects must be unparented first, or Irrlicht causes a segmentation fault
1033                         for(std::vector<core::vector2d<int> >::iterator ii = m_env->attachment_list.begin(); ii != m_env->attachment_list.end(); ii++)
1034                         {
1035                                 if(ii->Y == getId()) // This is a child of our parent
1036                                 {
1037                                         ClientActiveObject *obj = m_env->getActiveObject(ii->X); // Get the object of the child
1038                                         if(obj)
1039                                         {
1040                                                 scene::IMeshSceneNode *m_child_meshnode = obj->getMeshSceneNode();
1041                                                 scene::IAnimatedMeshSceneNode *m_child_animated_meshnode = obj->getAnimatedMeshSceneNode();
1042                                                 scene::IBillboardSceneNode *m_child_spritenode = obj->getSpriteSceneNode();
1043                                                 if(m_child_meshnode)
1044                                                         m_child_meshnode->setParent(m_smgr->getRootSceneNode());
1045                                                 if(m_child_animated_meshnode)
1046                                                         m_child_animated_meshnode->setParent(m_smgr->getRootSceneNode());
1047                                                 if(m_child_spritenode)
1048                                                         m_child_spritenode->setParent(m_smgr->getRootSceneNode());
1049                                         }
1050                                 }
1051                         }
1052
1053                         removeFromScene(false);
1054                         addToScene(m_smgr, m_gamedef->tsrc(), m_irr);
1055
1056                         // Attachments, part 2: Now that the parent has been refreshed, put its attachments back
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                                                 obj->setAttachments();
1064                                 }
1065                         }
1066                 }
1067
1068                 // Make sure m_is_visible is always applied
1069                 if(m_meshnode)
1070                         m_meshnode->setVisible(m_is_visible);
1071                 if(m_animated_meshnode)
1072                         m_animated_meshnode->setVisible(m_is_visible);
1073                 if(m_spritenode)
1074                         m_spritenode->setVisible(m_is_visible);
1075                 if(m_textnode)
1076                         m_textnode->setVisible(m_is_visible);
1077
1078                 if(getParent() != NULL) // Attachments should be glued to their parent by Irrlicht
1079                 {
1080                         // Set these for later
1081                         m_position = getPosition();
1082                         m_velocity = v3f(0,0,0);
1083                         m_acceleration = v3f(0,0,0);
1084                         pos_translator.vect_show = m_position;
1085
1086                         if(m_is_local_player) // Update local player attachment position
1087                         {
1088                                 LocalPlayer *player = m_env->getLocalPlayer();
1089                                 player->overridePosition = getParent()->getPosition();
1090                         }
1091                 }
1092                 else
1093                 {
1094                         v3f lastpos = pos_translator.vect_show;
1095
1096                         if(m_prop.physical){
1097                                 core::aabbox3d<f32> box = m_prop.collisionbox;
1098                                 box.MinEdge *= BS;
1099                                 box.MaxEdge *= BS;
1100                                 collisionMoveResult moveresult;
1101                                 f32 pos_max_d = BS*0.125; // Distance per iteration
1102                                 f32 stepheight = 0;
1103                                 v3f p_pos = m_position;
1104                                 v3f p_velocity = m_velocity;
1105                                 v3f p_acceleration = m_acceleration;
1106                                 IGameDef *gamedef = env->getGameDef();
1107                                 moveresult = collisionMoveSimple(&env->getMap(), gamedef,
1108                                                 pos_max_d, box, stepheight, dtime,
1109                                                 p_pos, p_velocity, p_acceleration);
1110                                 // Apply results
1111                                 m_position = p_pos;
1112                                 m_velocity = p_velocity;
1113                                 m_acceleration = p_acceleration;
1114                                 
1115                                 bool is_end_position = moveresult.collides;
1116                                 pos_translator.update(m_position, is_end_position, dtime);
1117                                 pos_translator.translate(dtime);
1118                                 updateNodePos();
1119                         } else {
1120                                 m_position += dtime * m_velocity + 0.5 * dtime * dtime * m_acceleration;
1121                                 m_velocity += dtime * m_acceleration;
1122                                 pos_translator.update(m_position, pos_translator.aim_is_end, pos_translator.anim_time);
1123                                 pos_translator.translate(dtime);
1124                                 updateNodePos();
1125                         }
1126
1127                         float moved = lastpos.getDistanceFrom(pos_translator.vect_show);
1128                         m_step_distance_counter += moved;
1129                         if(m_step_distance_counter > 1.5*BS){
1130                                 m_step_distance_counter = 0;
1131                                 if(!m_is_local_player && m_prop.makes_footstep_sound){
1132                                         INodeDefManager *ndef = m_gamedef->ndef();
1133                                         v3s16 p = floatToInt(getPosition() + v3f(0,
1134                                                         (m_prop.collisionbox.MinEdge.Y-0.5)*BS, 0), BS);
1135                                         MapNode n = m_env->getMap().getNodeNoEx(p);
1136                                         SimpleSoundSpec spec = ndef->get(n).sound_footstep;
1137                                         m_gamedef->sound()->playSoundAt(spec, false, getPosition());
1138                                 }
1139                         }
1140                 }
1141
1142                 m_anim_timer += dtime;
1143                 if(m_anim_timer >= m_anim_framelength){
1144                         m_anim_timer -= m_anim_framelength;
1145                         m_anim_frame++;
1146                         if(m_anim_frame >= m_anim_num_frames)
1147                                 m_anim_frame = 0;
1148                 }
1149
1150                 updateTexturePos();
1151
1152                 if(m_reset_textures_timer >= 0){
1153                         m_reset_textures_timer -= dtime;
1154                         if(m_reset_textures_timer <= 0){
1155                                 m_reset_textures_timer = -1;
1156                                 updateTextures("");
1157                         }
1158                 }
1159                 if(getParent() == NULL && fabs(m_prop.automatic_rotate) > 0.001){
1160                         m_yaw += dtime * m_prop.automatic_rotate * 180 / M_PI;
1161                         updateNodePos();
1162                 }
1163         }
1164
1165         void updateTexturePos()
1166         {
1167                 if(m_spritenode){
1168                         scene::ICameraSceneNode* camera =
1169                                         m_spritenode->getSceneManager()->getActiveCamera();
1170                         if(!camera)
1171                                 return;
1172                         v3f cam_to_entity = m_spritenode->getAbsolutePosition()
1173                                         - camera->getAbsolutePosition();
1174                         cam_to_entity.normalize();
1175
1176                         int row = m_tx_basepos.Y;
1177                         int col = m_tx_basepos.X;
1178                         
1179                         if(m_tx_select_horiz_by_yawpitch)
1180                         {
1181                                 if(cam_to_entity.Y > 0.75)
1182                                         col += 5;
1183                                 else if(cam_to_entity.Y < -0.75)
1184                                         col += 4;
1185                                 else{
1186                                         float mob_dir = atan2(cam_to_entity.Z, cam_to_entity.X) / M_PI * 180.;
1187                                         float dir = mob_dir - m_yaw;
1188                                         dir = wrapDegrees_180(dir);
1189                                         //infostream<<"id="<<m_id<<" dir="<<dir<<std::endl;
1190                                         if(fabs(wrapDegrees_180(dir - 0)) <= 45.1)
1191                                                 col += 2;
1192                                         else if(fabs(wrapDegrees_180(dir - 90)) <= 45.1)
1193                                                 col += 3;
1194                                         else if(fabs(wrapDegrees_180(dir - 180)) <= 45.1)
1195                                                 col += 0;
1196                                         else if(fabs(wrapDegrees_180(dir + 90)) <= 45.1)
1197                                                 col += 1;
1198                                         else
1199                                                 col += 4;
1200                                 }
1201                         }
1202                         
1203                         // Animation goes downwards
1204                         row += m_anim_frame;
1205
1206                         float txs = m_tx_size.X;
1207                         float tys = m_tx_size.Y;
1208                         setBillboardTextureMatrix(m_spritenode,
1209                                         txs, tys, col, row);
1210                 }
1211         }
1212
1213         void updateTextures(const std::string &mod)
1214         {
1215                 ITextureSource *tsrc = m_gamedef->tsrc();
1216
1217                 bool use_trilinear_filter = g_settings->getBool("trilinear_filter");
1218                 bool use_bilinear_filter = g_settings->getBool("bilinear_filter");
1219                 bool use_anisotropic_filter = g_settings->getBool("anisotropic_filter");
1220
1221                 if(m_spritenode)
1222                 {
1223                         if(m_prop.visual == "sprite")
1224                         {
1225                                 std::string texturestring = "unknown_block.png";
1226                                 if(m_prop.textures.size() >= 1)
1227                                         texturestring = m_prop.textures[0];
1228                                 texturestring += mod;
1229                                 m_spritenode->setMaterialTexture(0,
1230                                                 tsrc->getTextureRaw(texturestring));
1231
1232                                 // This allows setting per-material colors. However, until a real lighting
1233                                 // system is added, the code below will have no effect. Once MineTest
1234                                 // has directional lighting, it should work automatically.
1235                                 if(m_prop.colors.size() >= 1)
1236                                 {
1237                                         m_spritenode->getMaterial(0).AmbientColor = m_prop.colors[0];
1238                                         m_spritenode->getMaterial(0).DiffuseColor = m_prop.colors[0];
1239                                         m_spritenode->getMaterial(0).SpecularColor = m_prop.colors[0];
1240                                 }
1241
1242                                 m_spritenode->getMaterial(0).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1243                                 m_spritenode->getMaterial(0).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1244                                 m_spritenode->getMaterial(0).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1245                         }
1246                 }
1247                 if(m_animated_meshnode)
1248                 {
1249                         if(m_prop.visual == "mesh")
1250                         {
1251                                 for (u32 i = 0; i < m_prop.textures.size() && i < m_animated_meshnode->getMaterialCount(); ++i)
1252                                 {
1253                                         std::string texturestring = m_prop.textures[i];
1254                                         if(texturestring == "")
1255                                                 continue; // Empty texture string means don't modify that material
1256                                         texturestring += mod;
1257                                         video::ITexture* texture = tsrc->getTextureRaw(texturestring);
1258                                         if(!texture)
1259                                         {
1260                                                 errorstream<<"GenericCAO::updateTextures(): Could not load texture "<<texturestring<<std::endl;
1261                                                 continue;
1262                                         }
1263
1264                                         // Set material flags and texture
1265                                         m_animated_meshnode->setMaterialTexture(i, texture);
1266                                         video::SMaterial& material = m_animated_meshnode->getMaterial(i);
1267                                         material.setFlag(video::EMF_LIGHTING, false);
1268                                         material.setFlag(video::EMF_BILINEAR_FILTER, false);
1269
1270                                         m_animated_meshnode->getMaterial(i).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1271                                         m_animated_meshnode->getMaterial(i).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1272                                         m_animated_meshnode->getMaterial(i).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1273                                 }
1274                                 for (u32 i = 0; i < m_prop.colors.size() && i < m_animated_meshnode->getMaterialCount(); ++i)
1275                                 {
1276                                         // This allows setting per-material colors. However, until a real lighting
1277                                         // system is added, the code below will have no effect. Once MineTest
1278                                         // has directional lighting, it should work automatically.
1279                                         m_animated_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i];
1280                                         m_animated_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i];
1281                                         m_animated_meshnode->getMaterial(i).SpecularColor = m_prop.colors[i];
1282                                 }
1283                         }
1284                 }
1285                 if(m_meshnode)
1286                 {
1287                         if(m_prop.visual == "cube")
1288                         {
1289                                 for (u32 i = 0; i < 6; ++i)
1290                                 {
1291                                         std::string texturestring = "unknown_block.png";
1292                                         if(m_prop.textures.size() > i)
1293                                                 texturestring = m_prop.textures[i];
1294                                         texturestring += mod;
1295                                         AtlasPointer ap = tsrc->getTexture(texturestring);
1296
1297                                         // Get the tile texture and atlas transformation
1298                                         video::ITexture* atlas = ap.atlas;
1299                                         v2f pos = ap.pos;
1300                                         v2f size = ap.size;
1301
1302                                         // Set material flags and texture
1303                                         video::SMaterial& material = m_meshnode->getMaterial(i);
1304                                         material.setFlag(video::EMF_LIGHTING, false);
1305                                         material.setFlag(video::EMF_BILINEAR_FILTER, false);
1306                                         material.setTexture(0, atlas);
1307                                         material.getTextureMatrix(0).setTextureTranslate(pos.X, pos.Y);
1308                                         material.getTextureMatrix(0).setTextureScale(size.X, size.Y);
1309
1310                                         // This allows setting per-material colors. However, until a real lighting
1311                                         // system is added, the code below will have no effect. Once MineTest
1312                                         // has directional lighting, it should work automatically.
1313                                         if(m_prop.colors.size() > i)
1314                                         {
1315                                                 m_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i];
1316                                                 m_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i];
1317                                                 m_meshnode->getMaterial(i).SpecularColor = m_prop.colors[i];
1318                                         }
1319
1320                                         m_meshnode->getMaterial(i).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1321                                         m_meshnode->getMaterial(i).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1322                                         m_meshnode->getMaterial(i).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1323                                 }
1324                         }
1325                         else if(m_prop.visual == "upright_sprite")
1326                         {
1327                                 scene::IMesh *mesh = m_meshnode->getMesh();
1328                                 {
1329                                         std::string tname = "unknown_object.png";
1330                                         if(m_prop.textures.size() >= 1)
1331                                                 tname = m_prop.textures[0];
1332                                         tname += mod;
1333                                         scene::IMeshBuffer *buf = mesh->getMeshBuffer(0);
1334                                         buf->getMaterial().setTexture(0,
1335                                                         tsrc->getTextureRaw(tname));
1336                                         
1337                                         // This allows setting per-material colors. However, until a real lighting
1338                                         // system is added, the code below will have no effect. Once MineTest
1339                                         // has directional lighting, it should work automatically.
1340                                         if(m_prop.colors.size() >= 1)
1341                                         {
1342                                                 buf->getMaterial().AmbientColor = m_prop.colors[0];
1343                                                 buf->getMaterial().DiffuseColor = m_prop.colors[0];
1344                                                 buf->getMaterial().SpecularColor = m_prop.colors[0];
1345                                         }
1346
1347                                         buf->getMaterial().setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1348                                         buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1349                                         buf->getMaterial().setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1350                                 }
1351                                 {
1352                                         std::string tname = "unknown_object.png";
1353                                         if(m_prop.textures.size() >= 2)
1354                                                 tname = m_prop.textures[1];
1355                                         else if(m_prop.textures.size() >= 1)
1356                                                 tname = m_prop.textures[0];
1357                                         tname += mod;
1358                                         scene::IMeshBuffer *buf = mesh->getMeshBuffer(1);
1359                                         buf->getMaterial().setTexture(0,
1360                                                         tsrc->getTextureRaw(tname));
1361
1362                                         // This allows setting per-material colors. However, until a real lighting
1363                                         // system is added, the code below will have no effect. Once MineTest
1364                                         // has directional lighting, it should work automatically.
1365                                         if(m_prop.colors.size() >= 2)
1366                                         {
1367                                                 buf->getMaterial().AmbientColor = m_prop.colors[1];
1368                                                 buf->getMaterial().DiffuseColor = m_prop.colors[1];
1369                                                 buf->getMaterial().SpecularColor = m_prop.colors[1];
1370                                         }
1371                                         else if(m_prop.colors.size() >= 1)
1372                                         {
1373                                                 buf->getMaterial().AmbientColor = m_prop.colors[0];
1374                                                 buf->getMaterial().DiffuseColor = m_prop.colors[0];
1375                                                 buf->getMaterial().SpecularColor = m_prop.colors[0];
1376                                         }
1377
1378                                         buf->getMaterial().setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1379                                         buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1380                                         buf->getMaterial().setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1381                                 }
1382                         }
1383                 }
1384         }
1385
1386         void updateAnimation()
1387         {
1388                 if(m_animated_meshnode == NULL)
1389                         return;
1390
1391                 m_animated_meshnode->setFrameLoop((int)m_animation_range.X, (int)m_animation_range.Y);
1392                 m_animated_meshnode->setAnimationSpeed(m_animation_speed);
1393                 m_animated_meshnode->setTransitionTime(m_animation_blend);
1394         }
1395
1396         void updateBonePosition()
1397         {
1398                 if(!m_bone_position.size() || m_animated_meshnode == NULL)
1399                         return;
1400
1401                 m_animated_meshnode->setJointMode(irr::scene::EJUOR_CONTROL); // To write positions to the mesh on render
1402                 for(std::map<std::string, core::vector2d<v3f> >::const_iterator ii = m_bone_position.begin(); ii != m_bone_position.end(); ++ii){
1403                         std::string bone_name = (*ii).first;
1404                         v3f bone_pos = (*ii).second.X;
1405                         v3f bone_rot = (*ii).second.Y;
1406                         irr::scene::IBoneSceneNode* bone = m_animated_meshnode->getJointNode(bone_name.c_str());
1407                         if(bone)
1408                         {
1409                                 bone->setPosition(bone_pos);
1410                                 bone->setRotation(bone_rot);
1411                         }
1412                 }
1413         }
1414         
1415         void updateAttachments()
1416         {
1417                 m_attached_to_local = getParent() != NULL && getParent()->isLocalPlayer();
1418                 m_is_visible = !m_attached_to_local; // Objects attached to the local player should always be hidden
1419
1420                 if(getParent() == NULL || m_attached_to_local) // Detach or don't attach
1421                 {
1422                         if(m_meshnode)
1423                         {
1424                                 v3f old_position = m_meshnode->getAbsolutePosition();
1425                                 v3f old_rotation = m_meshnode->getRotation();
1426                                 m_meshnode->setParent(m_smgr->getRootSceneNode());
1427                                 m_meshnode->setPosition(old_position);
1428                                 m_meshnode->setRotation(old_rotation);
1429                                 m_meshnode->updateAbsolutePosition();
1430                         }
1431                         if(m_animated_meshnode)
1432                         {
1433                                 v3f old_position = m_animated_meshnode->getAbsolutePosition();
1434                                 v3f old_rotation = m_animated_meshnode->getRotation();
1435                                 m_animated_meshnode->setParent(m_smgr->getRootSceneNode());
1436                                 m_animated_meshnode->setPosition(old_position);
1437                                 m_animated_meshnode->setRotation(old_rotation);
1438                                 m_animated_meshnode->updateAbsolutePosition();
1439                         }
1440                         if(m_spritenode)
1441                         {
1442                                 v3f old_position = m_spritenode->getAbsolutePosition();
1443                                 v3f old_rotation = m_spritenode->getRotation();
1444                                 m_spritenode->setParent(m_smgr->getRootSceneNode());
1445                                 m_spritenode->setPosition(old_position);
1446                                 m_spritenode->setRotation(old_rotation);
1447                                 m_spritenode->updateAbsolutePosition();
1448                         }
1449                         if(m_is_local_player)
1450                         {
1451                                 LocalPlayer *player = m_env->getLocalPlayer();
1452                                 player->isAttached = false;
1453                         }
1454                 }
1455                 else // Attach
1456                 {
1457                         scene::IMeshSceneNode *parent_mesh = NULL;
1458                         if(getParent()->getMeshSceneNode())
1459                                 parent_mesh = getParent()->getMeshSceneNode();
1460                         scene::IAnimatedMeshSceneNode *parent_animated_mesh = NULL;
1461                         if(getParent()->getAnimatedMeshSceneNode())
1462                                 parent_animated_mesh = getParent()->getAnimatedMeshSceneNode();
1463                         scene::IBillboardSceneNode *parent_sprite = NULL;
1464                         if(getParent()->getSpriteSceneNode())
1465                                 parent_sprite = getParent()->getSpriteSceneNode();
1466
1467                         scene::IBoneSceneNode *parent_bone = NULL;
1468                         if(parent_animated_mesh && m_attachment_bone != "")
1469                                 parent_bone = parent_animated_mesh->getJointNode(m_attachment_bone.c_str());
1470
1471                         // The spaghetti code below makes sure attaching works if either the parent or child is a spritenode, meshnode, or animatedmeshnode
1472                         // TODO: Perhaps use polymorphism here to save code duplication
1473                         if(m_meshnode){
1474                                 if(parent_bone){
1475                                         m_meshnode->setParent(parent_bone);
1476                                         m_meshnode->setPosition(m_attachment_position);
1477                                         m_meshnode->setRotation(m_attachment_rotation);
1478                                         m_meshnode->updateAbsolutePosition();
1479                                 }
1480                                 else
1481                                 {
1482                                         if(parent_mesh){
1483                                                 m_meshnode->setParent(parent_mesh);
1484                                                 m_meshnode->setPosition(m_attachment_position);
1485                                                 m_meshnode->setRotation(m_attachment_rotation);
1486                                                 m_meshnode->updateAbsolutePosition();
1487                                         }
1488                                         else if(parent_animated_mesh){
1489                                                 m_meshnode->setParent(parent_animated_mesh);
1490                                                 m_meshnode->setPosition(m_attachment_position);
1491                                                 m_meshnode->setRotation(m_attachment_rotation);
1492                                                 m_meshnode->updateAbsolutePosition();
1493                                         }
1494                                         else if(parent_sprite){
1495                                                 m_meshnode->setParent(parent_sprite);
1496                                                 m_meshnode->setPosition(m_attachment_position);
1497                                                 m_meshnode->setRotation(m_attachment_rotation);
1498                                                 m_meshnode->updateAbsolutePosition();
1499                                         }
1500                                 }
1501                         }
1502                         if(m_animated_meshnode){
1503                                 if(parent_bone){
1504                                         m_animated_meshnode->setParent(parent_bone);
1505                                         m_animated_meshnode->setPosition(m_attachment_position);
1506                                         m_animated_meshnode->setRotation(m_attachment_rotation);
1507                                         m_animated_meshnode->updateAbsolutePosition();
1508                                 }
1509                                 else
1510                                 {
1511                                         if(parent_mesh){
1512                                                 m_animated_meshnode->setParent(parent_mesh);
1513                                                 m_animated_meshnode->setPosition(m_attachment_position);
1514                                                 m_animated_meshnode->setRotation(m_attachment_rotation);
1515                                                 m_animated_meshnode->updateAbsolutePosition();
1516                                         }
1517                                         else if(parent_animated_mesh){
1518                                                 m_animated_meshnode->setParent(parent_animated_mesh);
1519                                                 m_animated_meshnode->setPosition(m_attachment_position);
1520                                                 m_animated_meshnode->setRotation(m_attachment_rotation);
1521                                                 m_animated_meshnode->updateAbsolutePosition();
1522                                         }
1523                                         else if(parent_sprite){
1524                                                 m_animated_meshnode->setParent(parent_sprite);
1525                                                 m_animated_meshnode->setPosition(m_attachment_position);
1526                                                 m_animated_meshnode->setRotation(m_attachment_rotation);
1527                                                 m_animated_meshnode->updateAbsolutePosition();
1528                                         }
1529                                 }
1530                         }
1531                         if(m_spritenode){
1532                                 if(parent_bone){
1533                                         m_spritenode->setParent(parent_bone);
1534                                         m_spritenode->setPosition(m_attachment_position);
1535                                         m_spritenode->setRotation(m_attachment_rotation);
1536                                         m_spritenode->updateAbsolutePosition();
1537                                 }
1538                                 else
1539                                 {
1540                                         if(parent_mesh){
1541                                                 m_spritenode->setParent(parent_mesh);
1542                                                 m_spritenode->setPosition(m_attachment_position);
1543                                                 m_spritenode->setRotation(m_attachment_rotation);
1544                                                 m_spritenode->updateAbsolutePosition();
1545                                         }
1546                                         else if(parent_animated_mesh){
1547                                                 m_spritenode->setParent(parent_animated_mesh);
1548                                                 m_spritenode->setPosition(m_attachment_position);
1549                                                 m_spritenode->setRotation(m_attachment_rotation);
1550                                                 m_spritenode->updateAbsolutePosition();
1551                                         }
1552                                         else if(parent_sprite){
1553                                                 m_spritenode->setParent(parent_sprite);
1554                                                 m_spritenode->setPosition(m_attachment_position);
1555                                                 m_spritenode->setRotation(m_attachment_rotation);
1556                                                 m_spritenode->updateAbsolutePosition();
1557                                         }
1558                                 }
1559                         }
1560                         if(m_is_local_player)
1561                         {
1562                                 LocalPlayer *player = m_env->getLocalPlayer();
1563                                 player->isAttached = true;
1564                         }
1565                 }
1566         }
1567
1568         void processMessage(const std::string &data)
1569         {
1570                 //infostream<<"GenericCAO: Got message"<<std::endl;
1571                 std::istringstream is(data, std::ios::binary);
1572                 // command
1573                 u8 cmd = readU8(is);
1574                 if(cmd == GENERIC_CMD_SET_PROPERTIES)
1575                 {
1576                         m_prop = gob_read_set_properties(is);
1577
1578                         m_selection_box = m_prop.collisionbox;
1579                         m_selection_box.MinEdge *= BS;
1580                         m_selection_box.MaxEdge *= BS;
1581                                 
1582                         m_tx_size.X = 1.0 / m_prop.spritediv.X;
1583                         m_tx_size.Y = 1.0 / m_prop.spritediv.Y;
1584
1585                         if(!m_initial_tx_basepos_set){
1586                                 m_initial_tx_basepos_set = true;
1587                                 m_tx_basepos = m_prop.initial_sprite_basepos;
1588                         }
1589                         
1590                         expireVisuals();
1591                 }
1592                 else if(cmd == GENERIC_CMD_UPDATE_POSITION)
1593                 {
1594                         // Not sent by the server if this object is an attachment.
1595                         // We might however get here if the server notices the object being detached before the client.
1596                         m_position = readV3F1000(is);
1597                         m_velocity = readV3F1000(is);
1598                         m_acceleration = readV3F1000(is);
1599                         if(fabs(m_prop.automatic_rotate) < 0.001)
1600                                 m_yaw = readF1000(is);
1601                         bool do_interpolate = readU8(is);
1602                         bool is_end_position = readU8(is);
1603                         float update_interval = readF1000(is);
1604
1605                         // Place us a bit higher if we're physical, to not sink into
1606                         // the ground due to sucky collision detection...
1607                         if(m_prop.physical)
1608                                 m_position += v3f(0,0.002,0);
1609
1610                         if(getParent() != NULL) // Just in case
1611                                 return;
1612
1613                         if(do_interpolate){
1614                                 if(!m_prop.physical)
1615                                         pos_translator.update(m_position, is_end_position, update_interval);
1616                         } else {
1617                                 pos_translator.init(m_position);
1618                         }
1619                         updateNodePos();
1620                 }
1621                 else if(cmd == GENERIC_CMD_SET_TEXTURE_MOD)
1622                 {
1623                         std::string mod = deSerializeString(is);
1624                         updateTextures(mod);
1625                 }
1626                 else if(cmd == GENERIC_CMD_SET_SPRITE)
1627                 {
1628                         v2s16 p = readV2S16(is);
1629                         int num_frames = readU16(is);
1630                         float framelength = readF1000(is);
1631                         bool select_horiz_by_yawpitch = readU8(is);
1632                         
1633                         m_tx_basepos = p;
1634                         m_anim_num_frames = num_frames;
1635                         m_anim_framelength = framelength;
1636                         m_tx_select_horiz_by_yawpitch = select_horiz_by_yawpitch;
1637
1638                         updateTexturePos();
1639                 }
1640                 else if(cmd == GENERIC_CMD_SET_ANIMATION)
1641                 {
1642                         m_animation_range = readV2F1000(is);
1643                         m_animation_speed = readF1000(is);
1644                         m_animation_blend = readF1000(is);
1645
1646                         updateAnimation();
1647                 }
1648                 else if(cmd == GENERIC_CMD_SET_BONE_POSITION)
1649                 {
1650                         std::string bone = deSerializeString(is);
1651                         v3f position = readV3F1000(is);
1652                         v3f rotation = readV3F1000(is);
1653                         m_bone_position[bone] = core::vector2d<v3f>(position, rotation);
1654
1655                         updateBonePosition();
1656                 }
1657                 else if(cmd == GENERIC_CMD_SET_ATTACHMENT)
1658                 {
1659                         // If an entry already exists for this object, delete it first to avoid duplicates
1660                         for(std::vector<core::vector2d<int> >::iterator ii = m_env->attachment_list.begin(); ii != m_env->attachment_list.end(); ii++)
1661                         {
1662                                 if(ii->X == getId()) // This is the ID of our object
1663                                 {
1664                                         m_env->attachment_list.erase(ii);
1665                                         break;
1666                                 }
1667                         }
1668                         m_env->attachment_list.push_back(core::vector2d<int>(getId(), readS16(is)));
1669                         m_attachment_bone = deSerializeString(is);
1670                         m_attachment_position = readV3F1000(is);
1671                         m_attachment_rotation = readV3F1000(is);
1672
1673                         updateAttachments();
1674                 }
1675                 else if(cmd == GENERIC_CMD_PUNCHED)
1676                 {
1677                         /*s16 damage =*/ readS16(is);
1678                         s16 result_hp = readS16(is);
1679                         
1680                         m_hp = result_hp;
1681                 }
1682                 else if(cmd == GENERIC_CMD_UPDATE_ARMOR_GROUPS)
1683                 {
1684                         m_armor_groups.clear();
1685                         int armor_groups_size = readU16(is);
1686                         for(int i=0; i<armor_groups_size; i++){
1687                                 std::string name = deSerializeString(is);
1688                                 int rating = readS16(is);
1689                                 m_armor_groups[name] = rating;
1690                         }
1691                 }
1692         }
1693         
1694         bool directReportPunch(v3f dir, const ItemStack *punchitem=NULL,
1695                         float time_from_last_punch=1000000)
1696         {
1697                 assert(punchitem);
1698                 const ToolCapabilities *toolcap =
1699                                 &punchitem->getToolCapabilities(m_gamedef->idef());
1700                 PunchDamageResult result = getPunchDamage(
1701                                 m_armor_groups,
1702                                 toolcap,
1703                                 punchitem,
1704                                 time_from_last_punch);
1705
1706                 if(result.did_punch && result.damage != 0)
1707                 {
1708                         if(result.damage < m_hp){
1709                                 m_hp -= result.damage;
1710                         } else {
1711                                 m_hp = 0;
1712                                 // TODO: Execute defined fast response
1713                                 // As there is no definition, make a smoke puff
1714                                 ClientSimpleObject *simple = createSmokePuff(
1715                                                 m_smgr, m_env, m_position,
1716                                                 m_prop.visual_size * BS);
1717                                 m_env->addSimpleObject(simple);
1718                         }
1719                         // TODO: Execute defined fast response
1720                         // Flashing shall suffice as there is no definition
1721                         m_reset_textures_timer = 0.05;
1722                         if(result.damage >= 2)
1723                                 m_reset_textures_timer += 0.05 * result.damage;
1724                         updateTextures("^[brighten");
1725                 }
1726                 
1727                 return false;
1728         }
1729         
1730         std::string debugInfoText()
1731         {
1732                 std::ostringstream os(std::ios::binary);
1733                 os<<"GenericCAO hp="<<m_hp<<"\n";
1734                 os<<"armor={";
1735                 for(ItemGroupList::const_iterator i = m_armor_groups.begin();
1736                                 i != m_armor_groups.end(); i++){
1737                         os<<i->first<<"="<<i->second<<", ";
1738                 }
1739                 os<<"}";
1740                 return os.str();
1741         }
1742 };
1743
1744 // Prototype
1745 GenericCAO proto_GenericCAO(NULL, NULL);
1746
1747