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