Define M_PI on MSVC
[oweals/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
43 class Settings;
44 struct ToolCapabilities;
45
46 #define PP(x) "("<<(x).X<<","<<(x).Y<<","<<(x).Z<<")"
47
48 core::map<u16, ClientActiveObject::Factory> ClientActiveObject::m_types;
49
50 /*
51         SmoothTranslator
52 */
53
54 struct SmoothTranslator
55 {
56         v3f vect_old;
57         v3f vect_show;
58         v3f vect_aim;
59         f32 anim_counter;
60         f32 anim_time;
61         f32 anim_time_counter;
62         bool aim_is_end;
63
64         SmoothTranslator():
65                 vect_old(0,0,0),
66                 vect_show(0,0,0),
67                 vect_aim(0,0,0),
68                 anim_counter(0),
69                 anim_time(0),
70                 anim_time_counter(0),
71                 aim_is_end(true)
72         {}
73
74         void init(v3f vect)
75         {
76                 vect_old = vect;
77                 vect_show = vect;
78                 vect_aim = vect;
79                 anim_counter = 0;
80                 anim_time = 0;
81                 anim_time_counter = 0;
82                 aim_is_end = true;
83         }
84
85         void sharpen()
86         {
87                 init(vect_show);
88         }
89
90         void update(v3f vect_new, bool is_end_position=false, float update_interval=-1)
91         {
92                 aim_is_end = is_end_position;
93                 vect_old = vect_show;
94                 vect_aim = vect_new;
95                 if(update_interval > 0){
96                         anim_time = update_interval;
97                 } else {
98                         if(anim_time < 0.001 || anim_time > 1.0)
99                                 anim_time = anim_time_counter;
100                         else
101                                 anim_time = anim_time * 0.9 + anim_time_counter * 0.1;
102                 }
103                 anim_time_counter = 0;
104                 anim_counter = 0;
105         }
106
107         void translate(f32 dtime)
108         {
109                 anim_time_counter = anim_time_counter + dtime;
110                 anim_counter = anim_counter + dtime;
111                 v3f vect_move = vect_aim - vect_old;
112                 f32 moveratio = 1.0;
113                 if(anim_time > 0.001)
114                         moveratio = anim_time_counter / anim_time;
115                 // Move a bit less than should, to avoid oscillation
116                 moveratio = moveratio * 0.8;
117                 float move_end = 1.5;
118                 if(aim_is_end)
119                         move_end = 1.0;
120                 if(moveratio > move_end)
121                         moveratio = move_end;
122                 vect_show = vect_old + vect_move * moveratio;
123         }
124
125         bool is_moving()
126         {
127                 return ((anim_time_counter / anim_time) < 1.4);
128         }
129 };
130
131 /*
132         Other stuff
133 */
134
135 static void setBillboardTextureMatrix(scene::IBillboardSceneNode *bill,
136                 float txs, float tys, int col, int row)
137 {
138         video::SMaterial& material = bill->getMaterial(0);
139         core::matrix4& matrix = material.getTextureMatrix(0);
140         matrix.setTextureTranslate(txs*col, tys*row);
141         matrix.setTextureScale(txs, tys);
142 }
143
144 /*
145         TestCAO
146 */
147
148 class TestCAO : public ClientActiveObject
149 {
150 public:
151         TestCAO(IGameDef *gamedef, ClientEnvironment *env);
152         virtual ~TestCAO();
153         
154         u8 getType() const
155         {
156                 return ACTIVEOBJECT_TYPE_TEST;
157         }
158         
159         static ClientActiveObject* create(IGameDef *gamedef, ClientEnvironment *env);
160
161         void addToScene(scene::ISceneManager *smgr, ITextureSource *tsrc,
162                         IrrlichtDevice *irr);
163         void removeFromScene();
164         void updateLight(u8 light_at_pos);
165         v3s16 getLightPosition();
166         void updateNodePos();
167
168         void step(float dtime, ClientEnvironment *env);
169
170         void processMessage(const std::string &data);
171
172 private:
173         scene::IMeshSceneNode *m_node;
174         v3f m_position;
175 };
176
177 // Prototype
178 TestCAO proto_TestCAO(NULL, NULL);
179
180 TestCAO::TestCAO(IGameDef *gamedef, ClientEnvironment *env):
181         ClientActiveObject(0, gamedef, env),
182         m_node(NULL),
183         m_position(v3f(0,10*BS,0))
184 {
185         ClientActiveObject::registerType(getType(), create);
186 }
187
188 TestCAO::~TestCAO()
189 {
190 }
191
192 ClientActiveObject* TestCAO::create(IGameDef *gamedef, ClientEnvironment *env)
193 {
194         return new TestCAO(gamedef, env);
195 }
196
197 void TestCAO::addToScene(scene::ISceneManager *smgr, ITextureSource *tsrc,
198                         IrrlichtDevice *irr)
199 {
200         if(m_node != NULL)
201                 return;
202         
203         //video::IVideoDriver* driver = smgr->getVideoDriver();
204         
205         scene::SMesh *mesh = new scene::SMesh();
206         scene::IMeshBuffer *buf = new scene::SMeshBuffer();
207         video::SColor c(255,255,255,255);
208         video::S3DVertex vertices[4] =
209         {
210                 video::S3DVertex(-BS/2,-BS/4,0, 0,0,0, c, 0,1),
211                 video::S3DVertex(BS/2,-BS/4,0, 0,0,0, c, 1,1),
212                 video::S3DVertex(BS/2,BS/4,0, 0,0,0, c, 1,0),
213                 video::S3DVertex(-BS/2,BS/4,0, 0,0,0, c, 0,0),
214         };
215         u16 indices[] = {0,1,2,2,3,0};
216         buf->append(vertices, 4, indices, 6);
217         // Set material
218         buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
219         buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false);
220         buf->getMaterial().setTexture(0, tsrc->getTextureRaw("rat.png"));
221         buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
222         buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
223         buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
224         // Add to mesh
225         mesh->addMeshBuffer(buf);
226         buf->drop();
227         m_node = smgr->addMeshSceneNode(mesh, NULL);
228         mesh->drop();
229         updateNodePos();
230 }
231
232 void TestCAO::removeFromScene()
233 {
234         if(m_node == NULL)
235                 return;
236
237         m_node->remove();
238         m_node = NULL;
239 }
240
241 void TestCAO::updateLight(u8 light_at_pos)
242 {
243 }
244
245 v3s16 TestCAO::getLightPosition()
246 {
247         return floatToInt(m_position, BS);
248 }
249
250 void TestCAO::updateNodePos()
251 {
252         if(m_node == NULL)
253                 return;
254
255         m_node->setPosition(m_position);
256         //m_node->setRotation(v3f(0, 45, 0));
257 }
258
259 void TestCAO::step(float dtime, ClientEnvironment *env)
260 {
261         if(m_node)
262         {
263                 v3f rot = m_node->getRotation();
264                 //infostream<<"dtime="<<dtime<<", rot.Y="<<rot.Y<<std::endl;
265                 rot.Y += dtime * 180;
266                 m_node->setRotation(rot);
267         }
268 }
269
270 void TestCAO::processMessage(const std::string &data)
271 {
272         infostream<<"TestCAO: Got data: "<<data<<std::endl;
273         std::istringstream is(data, std::ios::binary);
274         u16 cmd;
275         is>>cmd;
276         if(cmd == 0)
277         {
278                 v3f newpos;
279                 is>>newpos.X;
280                 is>>newpos.Y;
281                 is>>newpos.Z;
282                 m_position = newpos;
283                 updateNodePos();
284         }
285 }
286
287 /*
288         ItemCAO
289 */
290
291 class ItemCAO : public ClientActiveObject
292 {
293 public:
294         ItemCAO(IGameDef *gamedef, ClientEnvironment *env);
295         virtual ~ItemCAO();
296         
297         u8 getType() const
298         {
299                 return ACTIVEOBJECT_TYPE_ITEM;
300         }
301         
302         static ClientActiveObject* create(IGameDef *gamedef, ClientEnvironment *env);
303
304         void addToScene(scene::ISceneManager *smgr, ITextureSource *tsrc,
305                         IrrlichtDevice *irr);
306         void removeFromScene();
307         void updateLight(u8 light_at_pos);
308         v3s16 getLightPosition();
309         void updateNodePos();
310         void updateInfoText();
311         void updateTexture();
312
313         void step(float dtime, ClientEnvironment *env);
314
315         void processMessage(const std::string &data);
316
317         void initialize(const std::string &data);
318         
319         core::aabbox3d<f32>* getSelectionBox()
320                 {return &m_selection_box;}
321         v3f getPosition()
322                 {return m_position;}
323         
324         std::string infoText()
325                 {return m_infotext;}
326
327 private:
328         core::aabbox3d<f32> m_selection_box;
329         scene::IMeshSceneNode *m_node;
330         v3f m_position;
331         std::string m_itemstring;
332         std::string m_infotext;
333 };
334
335 #include "inventory.h"
336
337 // Prototype
338 ItemCAO proto_ItemCAO(NULL, NULL);
339
340 ItemCAO::ItemCAO(IGameDef *gamedef, ClientEnvironment *env):
341         ClientActiveObject(0, gamedef, env),
342         m_selection_box(-BS/3.,0.0,-BS/3., BS/3.,BS*2./3.,BS/3.),
343         m_node(NULL),
344         m_position(v3f(0,10*BS,0))
345 {
346         if(!gamedef && !env)
347         {
348                 ClientActiveObject::registerType(getType(), create);
349         }
350 }
351
352 ItemCAO::~ItemCAO()
353 {
354 }
355
356 ClientActiveObject* ItemCAO::create(IGameDef *gamedef, ClientEnvironment *env)
357 {
358         return new ItemCAO(gamedef, env);
359 }
360
361 void ItemCAO::addToScene(scene::ISceneManager *smgr, ITextureSource *tsrc,
362                         IrrlichtDevice *irr)
363 {
364         if(m_node != NULL)
365                 return;
366         
367         //video::IVideoDriver* driver = smgr->getVideoDriver();
368         
369         scene::SMesh *mesh = new scene::SMesh();
370         scene::IMeshBuffer *buf = new scene::SMeshBuffer();
371         video::SColor c(255,255,255,255);
372         video::S3DVertex vertices[4] =
373         {
374                 /*video::S3DVertex(-BS/2,-BS/4,0, 0,0,0, c, 0,1),
375                 video::S3DVertex(BS/2,-BS/4,0, 0,0,0, c, 1,1),
376                 video::S3DVertex(BS/2,BS/4,0, 0,0,0, c, 1,0),
377                 video::S3DVertex(-BS/2,BS/4,0, 0,0,0, c, 0,0),*/
378                 video::S3DVertex(BS/3.,0,0, 0,0,0, c, 0,1),
379                 video::S3DVertex(-BS/3.,0,0, 0,0,0, c, 1,1),
380                 video::S3DVertex(-BS/3.,0+BS*2./3.,0, 0,0,0, c, 1,0),
381                 video::S3DVertex(BS/3.,0+BS*2./3.,0, 0,0,0, c, 0,0),
382         };
383         u16 indices[] = {0,1,2,2,3,0};
384         buf->append(vertices, 4, indices, 6);
385         // Set material
386         buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
387         buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false);
388         // Initialize with a generated placeholder texture
389         buf->getMaterial().setTexture(0, tsrc->getTextureRaw(""));
390         buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
391         buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
392         buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
393         // Add to mesh
394         mesh->addMeshBuffer(buf);
395         buf->drop();
396         m_node = smgr->addMeshSceneNode(mesh, NULL);
397         mesh->drop();
398         updateNodePos();
399
400         /*
401                 Update image of node
402         */
403
404         updateTexture();
405 }
406
407 void ItemCAO::removeFromScene()
408 {
409         if(m_node == NULL)
410                 return;
411
412         m_node->remove();
413         m_node = NULL;
414 }
415
416 void ItemCAO::updateLight(u8 light_at_pos)
417 {
418         if(m_node == NULL)
419                 return;
420
421         u8 li = decode_light(light_at_pos);
422         video::SColor color(255,li,li,li);
423         setMeshColor(m_node->getMesh(), color);
424 }
425
426 v3s16 ItemCAO::getLightPosition()
427 {
428         return floatToInt(m_position + v3f(0,0.5*BS,0), BS);
429 }
430
431 void ItemCAO::updateNodePos()
432 {
433         if(m_node == NULL)
434                 return;
435
436         m_node->setPosition(m_position);
437 }
438
439 void ItemCAO::updateInfoText()
440 {
441         try{
442                 IItemDefManager *idef = m_gamedef->idef();
443                 ItemStack item;
444                 item.deSerialize(m_itemstring, idef);
445                 if(item.isKnown(idef))
446                         m_infotext = item.getDefinition(idef).description;
447                 else
448                         m_infotext = "Unknown item: '" + m_itemstring + "'";
449                 if(item.count >= 2)
450                         m_infotext += " (" + itos(item.count) + ")";
451         }
452         catch(SerializationError &e)
453         {
454                 m_infotext = "Unknown item: '" + m_itemstring + "'";
455         }
456 }
457
458 void ItemCAO::updateTexture()
459 {
460         if(m_node == NULL)
461                 return;
462
463         // Create an inventory item to see what is its image
464         std::istringstream is(m_itemstring, std::ios_base::binary);
465         video::ITexture *texture = NULL;
466         try{
467                 IItemDefManager *idef = m_gamedef->idef();
468                 ItemStack item;
469                 item.deSerialize(is, idef);
470                 texture = item.getDefinition(idef).inventory_texture;
471         }
472         catch(SerializationError &e)
473         {
474                 infostream<<"WARNING: "<<__FUNCTION_NAME
475                                 <<": error deSerializing itemstring \""
476                                 <<m_itemstring<<std::endl;
477         }
478         
479         // Set meshbuffer texture
480         m_node->getMaterial(0).setTexture(0, texture);
481 }
482
483
484 void ItemCAO::step(float dtime, ClientEnvironment *env)
485 {
486         if(m_node)
487         {
488                 /*v3f rot = m_node->getRotation();
489                 rot.Y += dtime * 120;
490                 m_node->setRotation(rot);*/
491                 LocalPlayer *player = env->getLocalPlayer();
492                 assert(player);
493                 v3f rot = m_node->getRotation();
494                 rot.Y = 180.0 - (player->getYaw());
495                 m_node->setRotation(rot);
496         }
497 }
498
499 void ItemCAO::processMessage(const std::string &data)
500 {
501         //infostream<<"ItemCAO: Got message"<<std::endl;
502         std::istringstream is(data, std::ios::binary);
503         // command
504         u8 cmd = readU8(is);
505         if(cmd == 0)
506         {
507                 // pos
508                 m_position = readV3F1000(is);
509                 updateNodePos();
510         }
511         if(cmd == 1)
512         {
513                 // itemstring
514                 m_itemstring = deSerializeString(is);
515                 updateInfoText();
516                 updateTexture();
517         }
518 }
519
520 void ItemCAO::initialize(const std::string &data)
521 {
522         infostream<<"ItemCAO: Got init data"<<std::endl;
523         
524         {
525                 std::istringstream is(data, std::ios::binary);
526                 // version
527                 u8 version = readU8(is);
528                 // check version
529                 if(version != 0)
530                         return;
531                 // pos
532                 m_position = readV3F1000(is);
533                 // itemstring
534                 m_itemstring = deSerializeString(is);
535         }
536         
537         updateNodePos();
538         updateInfoText();
539 }
540
541 /*
542         GenericCAO
543 */
544
545 #include "genericobject.h"
546
547 class GenericCAO : public ClientActiveObject
548 {
549 private:
550         // Only set at initialization
551         std::string m_name;
552         bool m_is_player;
553         bool m_is_local_player; // determined locally
554         // Property-ish things
555         ObjectProperties m_prop;
556         //
557         scene::ISceneManager *m_smgr;
558         IrrlichtDevice *m_irr;
559         core::aabbox3d<f32> m_selection_box;
560         scene::IMeshSceneNode *m_meshnode;
561         scene::IBillboardSceneNode *m_spritenode;
562         scene::ITextSceneNode* m_textnode;
563         v3f m_position;
564         v3f m_velocity;
565         v3f m_acceleration;
566         float m_yaw;
567         s16 m_hp;
568         SmoothTranslator pos_translator;
569         // Spritesheet/animation stuff
570         v2f m_tx_size;
571         v2s16 m_tx_basepos;
572         bool m_initial_tx_basepos_set;
573         bool m_tx_select_horiz_by_yawpitch;
574         int m_anim_frame;
575         int m_anim_num_frames;
576         float m_anim_framelength;
577         float m_anim_timer;
578         ItemGroupList m_armor_groups;
579         float m_reset_textures_timer;
580         bool m_visuals_expired;
581         float m_step_distance_counter;
582         u8 m_last_light;
583
584 public:
585         GenericCAO(IGameDef *gamedef, ClientEnvironment *env):
586                 ClientActiveObject(0, gamedef, env),
587                 //
588                 m_is_player(false),
589                 m_is_local_player(false),
590                 //
591                 m_smgr(NULL),
592                 m_irr(NULL),
593                 m_selection_box(-BS/3.,-BS/3.,-BS/3., BS/3.,BS/3.,BS/3.),
594                 m_meshnode(NULL),
595                 m_spritenode(NULL),
596                 m_textnode(NULL),
597                 m_position(v3f(0,10*BS,0)),
598                 m_velocity(v3f(0,0,0)),
599                 m_acceleration(v3f(0,0,0)),
600                 m_yaw(0),
601                 m_hp(1),
602                 m_tx_size(1,1),
603                 m_tx_basepos(0,0),
604                 m_initial_tx_basepos_set(false),
605                 m_tx_select_horiz_by_yawpitch(false),
606                 m_anim_frame(0),
607                 m_anim_num_frames(1),
608                 m_anim_framelength(0.2),
609                 m_anim_timer(0),
610                 m_reset_textures_timer(-1),
611                 m_visuals_expired(false),
612                 m_step_distance_counter(0),
613                 m_last_light(255)
614         {
615                 if(gamedef == NULL)
616                         ClientActiveObject::registerType(getType(), create);
617         }
618
619         void initialize(const std::string &data)
620         {
621                 infostream<<"GenericCAO: Got init data"<<std::endl;
622                 std::istringstream is(data, std::ios::binary);
623                 // version
624                 u8 version = readU8(is);
625                 // check version
626                 if(version != 0){
627                         errorstream<<"GenericCAO: Unsupported init data version"
628                                         <<std::endl;
629                         return;
630                 }
631                 m_name = deSerializeString(is);
632                 m_is_player = readU8(is);
633                 m_position = readV3F1000(is);
634                 m_yaw = readF1000(is);
635                 m_hp = readS16(is);
636                 
637                 int num_messages = readU8(is);
638                 for(int i=0; i<num_messages; i++){
639                         std::string message = deSerializeLongString(is);
640                         processMessage(message);
641                 }
642
643                 pos_translator.init(m_position);
644                 updateNodePos();
645                 
646                 if(m_is_player){
647                         Player *player = m_env->getPlayer(m_name.c_str());
648                         if(player && player->isLocal()){
649                                 m_is_local_player = true;
650                         }
651                 }
652         }
653
654         ~GenericCAO()
655         {
656         }
657
658         static ClientActiveObject* create(IGameDef *gamedef, ClientEnvironment *env)
659         {
660                 return new GenericCAO(gamedef, env);
661         }
662
663         u8 getType() const
664         {
665                 return ACTIVEOBJECT_TYPE_GENERIC;
666         }
667         core::aabbox3d<f32>* getSelectionBox()
668         {
669                 if(!m_prop.is_visible || m_is_local_player)
670                         return NULL;
671                 return &m_selection_box;
672         }
673         v3f getPosition()
674         {
675                 return pos_translator.vect_show;
676         }
677
678         void removeFromScene()
679         {
680                 if(m_meshnode){
681                         m_meshnode->remove();
682                         m_meshnode = NULL;
683                 }
684                 if(m_spritenode){
685                         m_spritenode->remove();
686                         m_spritenode = NULL;
687                 }
688         }
689
690         void addToScene(scene::ISceneManager *smgr, ITextureSource *tsrc,
691                         IrrlichtDevice *irr)
692         {
693                 m_smgr = smgr;
694                 m_irr = irr;
695
696                 if(m_meshnode != NULL || m_spritenode != NULL)
697                         return;
698                 
699                 m_visuals_expired = false;
700
701                 if(!m_prop.is_visible || m_is_local_player)
702                         return;
703         
704                 //video::IVideoDriver* driver = smgr->getVideoDriver();
705
706                 if(m_prop.visual == "sprite"){
707                         infostream<<"GenericCAO::addToScene(): single_sprite"<<std::endl;
708                         m_spritenode = smgr->addBillboardSceneNode(
709                                         NULL, v2f(1, 1), v3f(0,0,0), -1);
710                         m_spritenode->setMaterialTexture(0,
711                                         tsrc->getTextureRaw("unknown_block.png"));
712                         m_spritenode->setMaterialFlag(video::EMF_LIGHTING, false);
713                         m_spritenode->setMaterialFlag(video::EMF_BILINEAR_FILTER, false);
714                         m_spritenode->setMaterialType(video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF);
715                         m_spritenode->setMaterialFlag(video::EMF_FOG_ENABLE, true);
716                         u8 li = m_last_light;
717                         m_spritenode->setColor(video::SColor(255,li,li,li));
718                         m_spritenode->setSize(m_prop.visual_size*BS);
719                         {
720                                 const float txs = 1.0 / 1;
721                                 const float tys = 1.0 / 1;
722                                 setBillboardTextureMatrix(m_spritenode,
723                                                 txs, tys, 0, 0);
724                         }
725                 }
726                 else if(m_prop.visual == "upright_sprite")
727                 {
728                         scene::SMesh *mesh = new scene::SMesh();
729                         double dx = BS*m_prop.visual_size.X/2;
730                         double dy = BS*m_prop.visual_size.Y/2;
731                         { // Front
732                         scene::IMeshBuffer *buf = new scene::SMeshBuffer();
733                         u8 li = m_last_light;
734                         video::SColor c(255,li,li,li);
735                         video::S3DVertex vertices[4] =
736                         {
737                                 video::S3DVertex(-dx,-dy,0, 0,0,0, c, 0,1),
738                                 video::S3DVertex(dx,-dy,0, 0,0,0, c, 1,1),
739                                 video::S3DVertex(dx,dy,0, 0,0,0, c, 1,0),
740                                 video::S3DVertex(-dx,dy,0, 0,0,0, c, 0,0),
741                         };
742                         u16 indices[] = {0,1,2,2,3,0};
743                         buf->append(vertices, 4, indices, 6);
744                         // Set material
745                         buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
746                         buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
747                         buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
748                         buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
749                         // Add to mesh
750                         mesh->addMeshBuffer(buf);
751                         buf->drop();
752                         }
753                         { // Back
754                         scene::IMeshBuffer *buf = new scene::SMeshBuffer();
755                         u8 li = m_last_light;
756                         video::SColor c(255,li,li,li);
757                         video::S3DVertex vertices[4] =
758                         {
759                                 video::S3DVertex(dx,-dy,0, 0,0,0, c, 1,1),
760                                 video::S3DVertex(-dx,-dy,0, 0,0,0, c, 0,1),
761                                 video::S3DVertex(-dx,dy,0, 0,0,0, c, 0,0),
762                                 video::S3DVertex(dx,dy,0, 0,0,0, c, 1,0),
763                         };
764                         u16 indices[] = {0,1,2,2,3,0};
765                         buf->append(vertices, 4, indices, 6);
766                         // Set material
767                         buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
768                         buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
769                         buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
770                         buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
771                         // Add to mesh
772                         mesh->addMeshBuffer(buf);
773                         buf->drop();
774                         }
775                         m_meshnode = smgr->addMeshSceneNode(mesh, NULL);
776                         mesh->drop();
777                         // Set it to use the materials of the meshbuffers directly.
778                         // This is needed for changing the texture in the future
779                         m_meshnode->setReadOnlyMaterials(true);
780                 }
781                 else if(m_prop.visual == "cube"){
782                         infostream<<"GenericCAO::addToScene(): cube"<<std::endl;
783                         scene::IMesh *mesh = createCubeMesh(v3f(BS,BS,BS));
784                         m_meshnode = smgr->addMeshSceneNode(mesh, NULL);
785                         mesh->drop();
786                         
787                         m_meshnode->setScale(v3f(m_prop.visual_size.X,
788                                         m_prop.visual_size.Y,
789                                         m_prop.visual_size.X));
790                         u8 li = m_last_light;
791                         setMeshColor(m_meshnode->getMesh(), video::SColor(255,li,li,li));
792                 } else if(m_prop.visual == "wielditem"){
793                         infostream<<"GenericCAO::addToScene(): node"<<std::endl;
794                         infostream<<"textures: "<<m_prop.textures.size()<<std::endl;
795                         if(m_prop.textures.size() >= 1){
796                                 infostream<<"textures[0]: "<<m_prop.textures[0]<<std::endl;
797                                 IItemDefManager *idef = m_gamedef->idef();
798                                 ItemStack item(m_prop.textures[0], 1, 0, "", idef);
799                                 scene::IMesh *mesh = item.getDefinition(idef).wield_mesh;
800                                 m_meshnode = smgr->addMeshSceneNode(mesh, NULL);
801                                 
802                                 m_meshnode->setScale(v3f(m_prop.visual_size.X/2,
803                                                 m_prop.visual_size.Y/2,
804                                                 m_prop.visual_size.X/2));
805                                 u8 li = m_last_light;
806                                 setMeshColor(m_meshnode->getMesh(), video::SColor(255,li,li,li));
807                         }
808                 } else {
809                         infostream<<"GenericCAO::addToScene(): \""<<m_prop.visual
810                                         <<"\" not supported"<<std::endl;
811                 }
812                 updateTextures("");
813                 
814                 scene::ISceneNode *node = NULL;
815                 if(m_spritenode)
816                         node = m_spritenode;
817                 else if(m_meshnode)
818                         node = m_meshnode;
819                 if(node && m_is_player && !m_is_local_player){
820                         // Add a text node for showing the name
821                         gui::IGUIEnvironment* gui = irr->getGUIEnvironment();
822                         std::wstring wname = narrow_to_wide(m_name);
823                         m_textnode = smgr->addTextSceneNode(gui->getBuiltInFont(),
824                                         wname.c_str(), video::SColor(255,255,255,255), node);
825                         m_textnode->setPosition(v3f(0, BS*1.1, 0));
826                 }
827                 
828                 updateNodePos();
829         }
830
831         void expireVisuals()
832         {
833                 m_visuals_expired = true;
834         }
835                 
836         void updateLight(u8 light_at_pos)
837         {
838                 bool is_visible = (m_hp != 0);
839                 u8 li = decode_light(light_at_pos);
840                 m_last_light = li;
841                 video::SColor color(255,li,li,li);
842                 if(m_meshnode){
843                         setMeshColor(m_meshnode->getMesh(), color);
844                         m_meshnode->setVisible(is_visible);
845                 }
846                 if(m_spritenode){
847                         m_spritenode->setColor(color);
848                         m_spritenode->setVisible(is_visible);
849                 }
850         }
851
852         v3s16 getLightPosition()
853         {
854                 return floatToInt(m_position, BS);
855         }
856
857         void updateNodePos()
858         {
859                 if(m_meshnode){
860                         m_meshnode->setPosition(pos_translator.vect_show);
861                         v3f rot = m_meshnode->getRotation();
862                         rot.Y = -m_yaw;
863                         m_meshnode->setRotation(rot);
864                 }
865                 if(m_spritenode){
866                         m_spritenode->setPosition(pos_translator.vect_show);
867                 }
868         }
869
870         void step(float dtime, ClientEnvironment *env)
871         {
872                 v3f lastpos = pos_translator.vect_show;
873
874                 if(m_visuals_expired && m_smgr && m_irr){
875                         m_visuals_expired = false;
876                         removeFromScene();
877                         addToScene(m_smgr, m_gamedef->tsrc(), m_irr);
878                 }
879
880                 if(m_prop.physical){
881                         core::aabbox3d<f32> box = m_prop.collisionbox;
882                         box.MinEdge *= BS;
883                         box.MaxEdge *= BS;
884                         collisionMoveResult moveresult;
885                         f32 pos_max_d = BS*0.125; // Distance per iteration
886                         f32 stepheight = 0;
887                         v3f p_pos = m_position;
888                         v3f p_velocity = m_velocity;
889                         v3f p_acceleration = m_acceleration;
890                         IGameDef *gamedef = env->getGameDef();
891                         moveresult = collisionMoveSimple(&env->getMap(), gamedef,
892                                         pos_max_d, box, stepheight, dtime,
893                                         p_pos, p_velocity, p_acceleration);
894                         // Apply results
895                         m_position = p_pos;
896                         m_velocity = p_velocity;
897                         m_acceleration = p_acceleration;
898                         
899                         bool is_end_position = moveresult.collides;
900                         pos_translator.update(m_position, is_end_position, dtime);
901                         pos_translator.translate(dtime);
902                         updateNodePos();
903                 } else {
904                         m_position += dtime * m_velocity + 0.5 * dtime * dtime * m_acceleration;
905                         m_velocity += dtime * m_acceleration;
906                         pos_translator.update(m_position, pos_translator.aim_is_end, pos_translator.anim_time);
907                         pos_translator.translate(dtime);
908                         updateNodePos();
909                 }
910
911                 float moved = lastpos.getDistanceFrom(pos_translator.vect_show);
912                 m_step_distance_counter += moved;
913                 if(m_step_distance_counter > 1.5*BS){
914                         m_step_distance_counter = 0;
915                         if(!m_is_local_player && m_prop.makes_footstep_sound){
916                                 INodeDefManager *ndef = m_gamedef->ndef();
917                                 v3s16 p = floatToInt(getPosition() + v3f(0,
918                                                 (m_prop.collisionbox.MinEdge.Y-0.5)*BS, 0), BS);
919                                 MapNode n = m_env->getMap().getNodeNoEx(p);
920                                 SimpleSoundSpec spec = ndef->get(n).sound_footstep;
921                                 m_gamedef->sound()->playSoundAt(spec, false, getPosition());
922                         }
923                 }
924
925                 m_anim_timer += dtime;
926                 if(m_anim_timer >= m_anim_framelength){
927                         m_anim_timer -= m_anim_framelength;
928                         m_anim_frame++;
929                         if(m_anim_frame >= m_anim_num_frames)
930                                 m_anim_frame = 0;
931                 }
932
933                 updateTexturePos();
934
935                 if(m_reset_textures_timer >= 0){
936                         m_reset_textures_timer -= dtime;
937                         if(m_reset_textures_timer <= 0){
938                                 m_reset_textures_timer = -1;
939                                 updateTextures("");
940                         }
941                 }
942                 if(fabs(m_prop.automatic_rotate) > 0.001){
943                         m_yaw += dtime * m_prop.automatic_rotate * 180 / M_PI;
944                         updateNodePos();
945                 }
946         }
947
948         void updateTexturePos()
949         {
950                 if(m_spritenode){
951                         scene::ICameraSceneNode* camera =
952                                         m_spritenode->getSceneManager()->getActiveCamera();
953                         if(!camera)
954                                 return;
955                         v3f cam_to_entity = m_spritenode->getAbsolutePosition()
956                                         - camera->getAbsolutePosition();
957                         cam_to_entity.normalize();
958
959                         int row = m_tx_basepos.Y;
960                         int col = m_tx_basepos.X;
961                         
962                         if(m_tx_select_horiz_by_yawpitch)
963                         {
964                                 if(cam_to_entity.Y > 0.75)
965                                         col += 5;
966                                 else if(cam_to_entity.Y < -0.75)
967                                         col += 4;
968                                 else{
969                                         float mob_dir = atan2(cam_to_entity.Z, cam_to_entity.X) / M_PI * 180.;
970                                         float dir = mob_dir - m_yaw;
971                                         dir = wrapDegrees_180(dir);
972                                         //infostream<<"id="<<m_id<<" dir="<<dir<<std::endl;
973                                         if(fabs(wrapDegrees_180(dir - 0)) <= 45.1)
974                                                 col += 2;
975                                         else if(fabs(wrapDegrees_180(dir - 90)) <= 45.1)
976                                                 col += 3;
977                                         else if(fabs(wrapDegrees_180(dir - 180)) <= 45.1)
978                                                 col += 0;
979                                         else if(fabs(wrapDegrees_180(dir + 90)) <= 45.1)
980                                                 col += 1;
981                                         else
982                                                 col += 4;
983                                 }
984                         }
985                         
986                         // Animation goes downwards
987                         row += m_anim_frame;
988
989                         float txs = m_tx_size.X;
990                         float tys = m_tx_size.Y;
991                         setBillboardTextureMatrix(m_spritenode,
992                                         txs, tys, col, row);
993                 }
994         }
995
996         void updateTextures(const std::string &mod)
997         {
998                 ITextureSource *tsrc = m_gamedef->tsrc();
999
1000                 if(m_spritenode)
1001                 {
1002                         if(m_prop.visual == "sprite")
1003                         {
1004                                 std::string texturestring = "unknown_block.png";
1005                                 if(m_prop.textures.size() >= 1)
1006                                         texturestring = m_prop.textures[0];
1007                                 texturestring += mod;
1008                                 m_spritenode->setMaterialTexture(0,
1009                                                 tsrc->getTextureRaw(texturestring));
1010                         }
1011                 }
1012                 if(m_meshnode)
1013                 {
1014                         if(m_prop.visual == "cube")
1015                         {
1016                                 for (u32 i = 0; i < 6; ++i)
1017                                 {
1018                                         std::string texturestring = "unknown_block.png";
1019                                         if(m_prop.textures.size() > i)
1020                                                 texturestring = m_prop.textures[i];
1021                                         texturestring += mod;
1022                                         AtlasPointer ap = tsrc->getTexture(texturestring);
1023
1024                                         // Get the tile texture and atlas transformation
1025                                         video::ITexture* atlas = ap.atlas;
1026                                         v2f pos = ap.pos;
1027                                         v2f size = ap.size;
1028
1029                                         // Set material flags and texture
1030                                         video::SMaterial& material = m_meshnode->getMaterial(i);
1031                                         material.setFlag(video::EMF_LIGHTING, false);
1032                                         material.setFlag(video::EMF_BILINEAR_FILTER, false);
1033                                         material.setTexture(0, atlas);
1034                                         material.getTextureMatrix(0).setTextureTranslate(pos.X, pos.Y);
1035                                         material.getTextureMatrix(0).setTextureScale(size.X, size.Y);
1036                                 }
1037                         }
1038                         else if(m_prop.visual == "upright_sprite")
1039                         {
1040                                 scene::IMesh *mesh = m_meshnode->getMesh();
1041                                 {
1042                                         std::string tname = "unknown_object.png";
1043                                         if(m_prop.textures.size() >= 1)
1044                                                 tname = m_prop.textures[0];
1045                                         tname += mod;
1046                                         scene::IMeshBuffer *buf = mesh->getMeshBuffer(0);
1047                                         buf->getMaterial().setTexture(0,
1048                                                         tsrc->getTextureRaw(tname));
1049                                 }
1050                                 {
1051                                         std::string tname = "unknown_object.png";
1052                                         if(m_prop.textures.size() >= 2)
1053                                                 tname = m_prop.textures[1];
1054                                         else if(m_prop.textures.size() >= 1)
1055                                                 tname = m_prop.textures[0];
1056                                         tname += mod;
1057                                         scene::IMeshBuffer *buf = mesh->getMeshBuffer(1);
1058                                         buf->getMaterial().setTexture(0,
1059                                                         tsrc->getTextureRaw(tname));
1060                                 }
1061                         }
1062                 }
1063         }
1064
1065         void processMessage(const std::string &data)
1066         {
1067                 //infostream<<"GenericCAO: Got message"<<std::endl;
1068                 std::istringstream is(data, std::ios::binary);
1069                 // command
1070                 u8 cmd = readU8(is);
1071                 if(cmd == GENERIC_CMD_SET_PROPERTIES)
1072                 {
1073                         m_prop = gob_read_set_properties(is);
1074
1075                         m_selection_box = m_prop.collisionbox;
1076                         m_selection_box.MinEdge *= BS;
1077                         m_selection_box.MaxEdge *= BS;
1078                                 
1079                         m_tx_size.X = 1.0 / m_prop.spritediv.X;
1080                         m_tx_size.Y = 1.0 / m_prop.spritediv.Y;
1081
1082                         if(!m_initial_tx_basepos_set){
1083                                 m_initial_tx_basepos_set = true;
1084                                 m_tx_basepos = m_prop.initial_sprite_basepos;
1085                         }
1086                         
1087                         expireVisuals();
1088                 }
1089                 else if(cmd == GENERIC_CMD_UPDATE_POSITION)
1090                 {
1091                         m_position = readV3F1000(is);
1092                         m_velocity = readV3F1000(is);
1093                         m_acceleration = readV3F1000(is);
1094                         if(fabs(m_prop.automatic_rotate) < 0.001)
1095                                 m_yaw = readF1000(is);
1096                         bool do_interpolate = readU8(is);
1097                         bool is_end_position = readU8(is);
1098                         float update_interval = readF1000(is);
1099
1100                         // Place us a bit higher if we're physical, to not sink into
1101                         // the ground due to sucky collision detection...
1102                         if(m_prop.physical)
1103                                 m_position += v3f(0,0.002,0);
1104                         
1105                         if(do_interpolate){
1106                                 if(!m_prop.physical)
1107                                         pos_translator.update(m_position, is_end_position, update_interval);
1108                         } else {
1109                                 pos_translator.init(m_position);
1110                         }
1111                         updateNodePos();
1112                 }
1113                 else if(cmd == GENERIC_CMD_SET_TEXTURE_MOD)
1114                 {
1115                         std::string mod = deSerializeString(is);
1116                         updateTextures(mod);
1117                 }
1118                 else if(cmd == GENERIC_CMD_SET_SPRITE)
1119                 {
1120                         v2s16 p = readV2S16(is);
1121                         int num_frames = readU16(is);
1122                         float framelength = readF1000(is);
1123                         bool select_horiz_by_yawpitch = readU8(is);
1124                         
1125                         m_tx_basepos = p;
1126                         m_anim_num_frames = num_frames;
1127                         m_anim_framelength = framelength;
1128                         m_tx_select_horiz_by_yawpitch = select_horiz_by_yawpitch;
1129
1130                         updateTexturePos();
1131                 }
1132                 else if(cmd == GENERIC_CMD_PUNCHED)
1133                 {
1134                         /*s16 damage =*/ readS16(is);
1135                         s16 result_hp = readS16(is);
1136                         
1137                         m_hp = result_hp;
1138                 }
1139                 else if(cmd == GENERIC_CMD_UPDATE_ARMOR_GROUPS)
1140                 {
1141                         m_armor_groups.clear();
1142                         int armor_groups_size = readU16(is);
1143                         for(int i=0; i<armor_groups_size; i++){
1144                                 std::string name = deSerializeString(is);
1145                                 int rating = readS16(is);
1146                                 m_armor_groups[name] = rating;
1147                         }
1148                 }
1149         }
1150         
1151         bool directReportPunch(v3f dir, const ItemStack *punchitem=NULL,
1152                         float time_from_last_punch=1000000)
1153         {
1154                 assert(punchitem);
1155                 const ToolCapabilities *toolcap =
1156                                 &punchitem->getToolCapabilities(m_gamedef->idef());
1157                 PunchDamageResult result = getPunchDamage(
1158                                 m_armor_groups,
1159                                 toolcap,
1160                                 punchitem,
1161                                 time_from_last_punch);
1162
1163                 if(result.did_punch && result.damage != 0)
1164                 {
1165                         if(result.damage < m_hp){
1166                                 m_hp -= result.damage;
1167                         } else {
1168                                 m_hp = 0;
1169                                 // TODO: Execute defined fast response
1170                                 // As there is no definition, make a smoke puff
1171                                 ClientSimpleObject *simple = createSmokePuff(
1172                                                 m_smgr, m_env, m_position,
1173                                                 m_prop.visual_size * BS);
1174                                 m_env->addSimpleObject(simple);
1175                         }
1176                         // TODO: Execute defined fast response
1177                         // Flashing shall suffice as there is no definition
1178                         m_reset_textures_timer = 0.05;
1179                         if(result.damage >= 2)
1180                                 m_reset_textures_timer += 0.05 * result.damage;
1181                         updateTextures("^[brighten");
1182                 }
1183                 
1184                 return false;
1185         }
1186         
1187         std::string debugInfoText()
1188         {
1189                 std::ostringstream os(std::ios::binary);
1190                 os<<"GenericCAO hp="<<m_hp<<"\n";
1191                 os<<"armor={";
1192                 for(ItemGroupList::const_iterator i = m_armor_groups.begin();
1193                                 i != m_armor_groups.end(); i++){
1194                         os<<i->first<<"="<<i->second<<", ";
1195                 }
1196                 os<<"}";
1197                 return os.str();
1198         }
1199 };
1200
1201 // Prototype
1202 GenericCAO proto_GenericCAO(NULL, NULL);
1203
1204