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