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