]> git.lizzy.rs Git - minetest.git/blob - src/content_cao.cpp
Performance Improvement: Use a cache which caches result for getFacePositions.
[minetest.git] / src / content_cao.cpp
1 /*
2 Minetest
3 Copyright (C) 2010-2013 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 <ICameraSceneNode.h>
21 #include <ITextSceneNode.h>
22 #include <IBillboardSceneNode.h>
23 #include <IMeshManipulator.h>
24 #include <IAnimatedMeshSceneNode.h>
25 #include <IBoneSceneNode.h>
26 #include "content_cao.h"
27 #include "util/numeric.h" // For IntervalLimiter
28 #include "util/serialize.h"
29 #include "util/mathconstants.h"
30 #include "tile.h"
31 #include "environment.h"
32 #include "collision.h"
33 #include "settings.h"
34 #include "serialization.h" // For decompressZlib
35 #include "gamedef.h"
36 #include "clientobject.h"
37 #include "content_object.h"
38 #include "mesh.h"
39 #include "itemdef.h"
40 #include "tool.h"
41 #include "content_cso.h"
42 #include "sound.h"
43 #include "nodedef.h"
44 #include "localplayer.h"
45 #include "map.h"
46 #include "main.h" // g_settings
47 #include "camera.h" // CameraModes
48 #include "wieldmesh.h"
49 #include "log.h"
50
51 class Settings;
52 struct ToolCapabilities;
53
54 #define PP(x) "("<<(x).X<<","<<(x).Y<<","<<(x).Z<<")"
55
56 std::map<u16, ClientActiveObject::Factory> ClientActiveObject::m_types;
57
58 SmoothTranslator::SmoothTranslator():
59         vect_old(0,0,0),
60         vect_show(0,0,0),
61         vect_aim(0,0,0),
62         anim_counter(0),
63         anim_time(0),
64         anim_time_counter(0),
65         aim_is_end(true)
66 {}
67
68 void SmoothTranslator::init(v3f vect)
69 {
70         vect_old = vect;
71         vect_show = vect;
72         vect_aim = vect;
73         anim_counter = 0;
74         anim_time = 0;
75         anim_time_counter = 0;
76         aim_is_end = true;
77 }
78
79 void SmoothTranslator::sharpen()
80 {
81         init(vect_show);
82 }
83
84 void SmoothTranslator::update(v3f vect_new, bool is_end_position, float update_interval)
85 {
86         aim_is_end = is_end_position;
87         vect_old = vect_show;
88         vect_aim = vect_new;
89         if(update_interval > 0)
90         {
91                 anim_time = update_interval;
92         } else {
93                 if(anim_time < 0.001 || anim_time > 1.0)
94                         anim_time = anim_time_counter;
95                 else
96                         anim_time = anim_time * 0.9 + anim_time_counter * 0.1;
97         }
98         anim_time_counter = 0;
99         anim_counter = 0;
100 }
101
102 void SmoothTranslator::translate(f32 dtime)
103 {
104         anim_time_counter = anim_time_counter + dtime;
105         anim_counter = anim_counter + dtime;
106         v3f vect_move = vect_aim - vect_old;
107         f32 moveratio = 1.0;
108         if(anim_time > 0.001)
109                 moveratio = anim_time_counter / anim_time;
110         // Move a bit less than should, to avoid oscillation
111         moveratio = moveratio * 0.8;
112         float move_end = 1.5;
113         if(aim_is_end)
114                 move_end = 1.0;
115         if(moveratio > move_end)
116                 moveratio = move_end;
117         vect_show = vect_old + vect_move * moveratio;
118 }
119
120 bool SmoothTranslator::is_moving()
121 {
122         return ((anim_time_counter / anim_time) < 1.4);
123 }
124
125 /*
126         Other stuff
127 */
128
129 static void setBillboardTextureMatrix(scene::IBillboardSceneNode *bill,
130                 float txs, float tys, int col, int row)
131 {
132         video::SMaterial& material = bill->getMaterial(0);
133         core::matrix4& matrix = material.getTextureMatrix(0);
134         matrix.setTextureTranslate(txs*col, tys*row);
135         matrix.setTextureScale(txs, tys);
136 }
137
138 /*
139         TestCAO
140 */
141
142 class TestCAO : public ClientActiveObject
143 {
144 public:
145         TestCAO(IGameDef *gamedef, ClientEnvironment *env);
146         virtual ~TestCAO();
147         
148         u8 getType() const
149         {
150                 return ACTIVEOBJECT_TYPE_TEST;
151         }
152         
153         static ClientActiveObject* create(IGameDef *gamedef, ClientEnvironment *env);
154
155         void addToScene(scene::ISceneManager *smgr, ITextureSource *tsrc,
156                         IrrlichtDevice *irr);
157         void removeFromScene(bool permanent);
158         void updateLight(u8 light_at_pos);
159         v3s16 getLightPosition();
160         void updateNodePos();
161
162         void step(float dtime, ClientEnvironment *env);
163
164         void processMessage(const std::string &data);
165
166         bool getCollisionBox(aabb3f *toset) { return false; }
167 private:
168         scene::IMeshSceneNode *m_node;
169         v3f m_position;
170 };
171
172 // Prototype
173 TestCAO proto_TestCAO(NULL, NULL);
174
175 TestCAO::TestCAO(IGameDef *gamedef, ClientEnvironment *env):
176         ClientActiveObject(0, gamedef, env),
177         m_node(NULL),
178         m_position(v3f(0,10*BS,0))
179 {
180         ClientActiveObject::registerType(getType(), create);
181 }
182
183 TestCAO::~TestCAO()
184 {
185 }
186
187 ClientActiveObject* TestCAO::create(IGameDef *gamedef, ClientEnvironment *env)
188 {
189         return new TestCAO(gamedef, env);
190 }
191
192 void TestCAO::addToScene(scene::ISceneManager *smgr, ITextureSource *tsrc,
193                         IrrlichtDevice *irr)
194 {
195         if(m_node != NULL)
196                 return;
197         
198         //video::IVideoDriver* driver = smgr->getVideoDriver();
199         
200         scene::SMesh *mesh = new scene::SMesh();
201         scene::IMeshBuffer *buf = new scene::SMeshBuffer();
202         video::SColor c(255,255,255,255);
203         video::S3DVertex vertices[4] =
204         {
205                 video::S3DVertex(-BS/2,-BS/4,0, 0,0,0, c, 0,1),
206                 video::S3DVertex(BS/2,-BS/4,0, 0,0,0, c, 1,1),
207                 video::S3DVertex(BS/2,BS/4,0, 0,0,0, c, 1,0),
208                 video::S3DVertex(-BS/2,BS/4,0, 0,0,0, c, 0,0),
209         };
210         u16 indices[] = {0,1,2,2,3,0};
211         buf->append(vertices, 4, indices, 6);
212         // Set material
213         buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
214         buf->getMaterial().setFlag(video::EMF_BACK_FACE_CULLING, false);
215         buf->getMaterial().setTexture(0, tsrc->getTexture("rat.png"));
216         buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
217         buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
218         buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
219         // Add to mesh
220         mesh->addMeshBuffer(buf);
221         buf->drop();
222         m_node = smgr->addMeshSceneNode(mesh, NULL);
223         mesh->drop();
224         updateNodePos();
225 }
226
227 void TestCAO::removeFromScene(bool permanent)
228 {
229         if(m_node == NULL)
230                 return;
231
232         m_node->remove();
233         m_node = NULL;
234 }
235
236 void TestCAO::updateLight(u8 light_at_pos)
237 {
238 }
239
240 v3s16 TestCAO::getLightPosition()
241 {
242         return floatToInt(m_position, BS);
243 }
244
245 void TestCAO::updateNodePos()
246 {
247         if(m_node == NULL)
248                 return;
249
250         m_node->setPosition(m_position);
251         //m_node->setRotation(v3f(0, 45, 0));
252 }
253
254 void TestCAO::step(float dtime, ClientEnvironment *env)
255 {
256         if(m_node)
257         {
258                 v3f rot = m_node->getRotation();
259                 //infostream<<"dtime="<<dtime<<", rot.Y="<<rot.Y<<std::endl;
260                 rot.Y += dtime * 180;
261                 m_node->setRotation(rot);
262         }
263 }
264
265 void TestCAO::processMessage(const std::string &data)
266 {
267         infostream<<"TestCAO: Got data: "<<data<<std::endl;
268         std::istringstream is(data, std::ios::binary);
269         u16 cmd;
270         is>>cmd;
271         if(cmd == 0)
272         {
273                 v3f newpos;
274                 is>>newpos.X;
275                 is>>newpos.Y;
276                 is>>newpos.Z;
277                 m_position = newpos;
278                 updateNodePos();
279         }
280 }
281
282 /*
283         ItemCAO
284 */
285
286 class ItemCAO : public ClientActiveObject
287 {
288 public:
289         ItemCAO(IGameDef *gamedef, ClientEnvironment *env);
290         virtual ~ItemCAO();
291         
292         u8 getType() const
293         {
294                 return ACTIVEOBJECT_TYPE_ITEM;
295         }
296         
297         static ClientActiveObject* create(IGameDef *gamedef, ClientEnvironment *env);
298
299         void addToScene(scene::ISceneManager *smgr, ITextureSource *tsrc,
300                         IrrlichtDevice *irr);
301         void removeFromScene(bool permanent);
302         void updateLight(u8 light_at_pos);
303         v3s16 getLightPosition();
304         void updateNodePos();
305         void updateInfoText();
306         void updateTexture();
307
308         void step(float dtime, ClientEnvironment *env);
309
310         void processMessage(const std::string &data);
311
312         void initialize(const std::string &data);
313         
314         core::aabbox3d<f32>* getSelectionBox()
315                 {return &m_selection_box;}
316         v3f getPosition()
317                 {return m_position;}
318         
319         std::string infoText()
320                 {return m_infotext;}
321
322         bool getCollisionBox(aabb3f *toset) { return false; }
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->getTexture(""));
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(bool permanent)
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 = idef->getInventoryTexture(item.getDefinition(idef).name, m_gamedef);
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 GenericCAO::GenericCAO(IGameDef *gamedef, ClientEnvironment *env):
544                 ClientActiveObject(0, gamedef, env),
545                 //
546                 m_is_player(false),
547                 m_is_local_player(false),
548                 m_id(0),
549                 //
550                 m_smgr(NULL),
551                 m_irr(NULL),
552                 m_selection_box(-BS/3.,-BS/3.,-BS/3., BS/3.,BS/3.,BS/3.),
553                 m_meshnode(NULL),
554                 m_animated_meshnode(NULL),
555                 m_wield_meshnode(NULL),
556                 m_spritenode(NULL),
557                 m_textnode(NULL),
558                 m_position(v3f(0,10*BS,0)),
559                 m_velocity(v3f(0,0,0)),
560                 m_acceleration(v3f(0,0,0)),
561                 m_yaw(0),
562                 m_hp(1),
563                 m_tx_size(1,1),
564                 m_tx_basepos(0,0),
565                 m_initial_tx_basepos_set(false),
566                 m_tx_select_horiz_by_yawpitch(false),
567                 m_animation_range(v2s32(0,0)),
568                 m_animation_speed(15),
569                 m_animation_blend(0),
570                 m_bone_position(std::map<std::string, core::vector2d<v3f> >()),
571                 m_attachment_bone(""),
572                 m_attachment_position(v3f(0,0,0)),
573                 m_attachment_rotation(v3f(0,0,0)),
574                 m_attached_to_local(false),
575                 m_anim_frame(0),
576                 m_anim_num_frames(1),
577                 m_anim_framelength(0.2),
578                 m_anim_timer(0),
579                 m_reset_textures_timer(-1),
580                 m_visuals_expired(false),
581                 m_step_distance_counter(0),
582                 m_last_light(255),
583                 m_is_visible(false)
584 {
585         if(gamedef == NULL)
586                 ClientActiveObject::registerType(getType(), create);
587 }
588
589 bool GenericCAO::getCollisionBox(aabb3f *toset)
590 {
591         if (m_prop.physical)
592         {
593                 //update collision box
594                 toset->MinEdge = m_prop.collisionbox.MinEdge * BS;
595                 toset->MaxEdge = m_prop.collisionbox.MaxEdge * BS;
596
597                 toset->MinEdge += m_position;
598                 toset->MaxEdge += m_position;
599
600                 return true;
601         }
602
603         return false;
604 }
605
606 bool GenericCAO::collideWithObjects()
607 {
608         return m_prop.collideWithObjects;
609 }
610
611 void GenericCAO::initialize(const std::string &data)
612 {
613         infostream<<"GenericCAO: Got init data"<<std::endl;
614         std::istringstream is(data, std::ios::binary);
615         int num_messages = 0;
616         // version
617         u8 version = readU8(is);
618         // check version
619         if(version == 1) // In PROTOCOL_VERSION 14
620         {
621                 m_name = deSerializeString(is);
622                 m_is_player = readU8(is);
623                 m_id = readS16(is);
624                 m_position = readV3F1000(is);
625                 m_yaw = readF1000(is);
626                 m_hp = readS16(is);
627                 num_messages = readU8(is);
628         }
629         else if(version == 0) // In PROTOCOL_VERSION 13
630         {
631                 m_name = deSerializeString(is);
632                 m_is_player = readU8(is);
633                 m_position = readV3F1000(is);
634                 m_yaw = readF1000(is);
635                 m_hp = readS16(is);
636                 num_messages = readU8(is);
637         }
638         else
639         {
640                 errorstream<<"GenericCAO: Unsupported init data version"
641                                 <<std::endl;
642                 return;
643         }
644
645         for(int i=0; i<num_messages; i++)
646         {
647                 std::string message = deSerializeLongString(is);
648                 processMessage(message);
649         }
650
651         pos_translator.init(m_position);
652         updateNodePos();
653
654         if(m_is_player)
655         {
656                 Player *player = m_env->getPlayer(m_name.c_str());
657                 if(player && player->isLocal())
658                 {
659                         m_is_local_player = true;
660                         m_is_visible = false;
661                         LocalPlayer* localplayer = dynamic_cast<LocalPlayer*>(player);
662
663                         assert( localplayer != NULL );
664                         localplayer->setCAO(this);
665                 }
666                 m_env->addPlayerName(m_name.c_str());
667         }
668 }
669
670 GenericCAO::~GenericCAO()
671 {
672         if(m_is_player)
673         {
674                 m_env->removePlayerName(m_name.c_str());
675         }
676         removeFromScene(true);
677 }
678
679 core::aabbox3d<f32>* GenericCAO::getSelectionBox()
680 {
681         if(!m_prop.is_visible || !m_is_visible || m_is_local_player || getParent() != NULL)
682                 return NULL;
683         return &m_selection_box;
684 }
685
686 v3f GenericCAO::getPosition()
687 {
688         if (getParent() != NULL) {
689                 scene::ISceneNode *node = getSceneNode();
690                 if (node)
691                         return node->getAbsolutePosition();
692                 else
693                         return m_position;
694         }
695         return pos_translator.vect_show;
696 }
697
698 scene::ISceneNode* GenericCAO::getSceneNode()
699 {
700         if (m_meshnode)
701                 return m_meshnode;
702         if (m_animated_meshnode)
703                 return m_animated_meshnode;
704         if (m_wield_meshnode)
705                 return m_wield_meshnode;
706         if (m_spritenode)
707                 return m_spritenode;
708         return NULL;
709 }
710
711 scene::IMeshSceneNode* GenericCAO::getMeshSceneNode()
712 {
713         return m_meshnode;
714 }
715
716 scene::IAnimatedMeshSceneNode* GenericCAO::getAnimatedMeshSceneNode()
717 {
718         return m_animated_meshnode;
719 }
720
721 WieldMeshSceneNode* GenericCAO::getWieldMeshSceneNode()
722 {
723         return m_wield_meshnode;
724 }
725
726 scene::IBillboardSceneNode* GenericCAO::getSpriteSceneNode()
727 {
728         return m_spritenode;
729 }
730
731 void GenericCAO::setAttachments()
732 {
733         updateAttachments();
734 }
735
736 ClientActiveObject* GenericCAO::getParent()
737 {
738         ClientActiveObject *obj = NULL;
739
740         u16 attached_id = m_env->m_attachements[getId()];
741
742         if ((attached_id != 0) &&
743                         (attached_id != getId())) {
744                 obj = m_env->getActiveObject(attached_id);
745         }
746         return obj;
747 }
748
749 void GenericCAO::removeFromScene(bool permanent)
750 {
751         // Should be true when removing the object permanently and false when refreshing (eg: updating visuals)
752         if((m_env != NULL) && (permanent)) 
753         {
754                 for(std::vector<u16>::iterator ci = m_children.begin();
755                                                 ci != m_children.end(); ci++)
756                 {
757                         if (m_env->m_attachements[*ci] == getId()) {
758                                 m_env->m_attachements[*ci] = 0;
759                         }
760                 }
761
762                 m_env->m_attachements[getId()] = 0;
763                 
764                 LocalPlayer* player = m_env->getLocalPlayer();
765                 if (this == player->parent) {
766                         player->parent = NULL;
767                         player->isAttached = false;
768                 }
769         }
770
771         if(m_meshnode)
772         {
773                 m_meshnode->remove();
774                 m_meshnode->drop();
775                 m_meshnode = NULL;
776         }
777         if(m_animated_meshnode)
778         {
779                 m_animated_meshnode->remove();
780                 m_animated_meshnode->drop();
781                 m_animated_meshnode = NULL;
782         }
783         if(m_wield_meshnode)
784         {
785                 m_wield_meshnode->remove();
786                 m_wield_meshnode->drop();
787                 m_wield_meshnode = NULL;
788         }
789         if(m_spritenode)
790         {
791                 m_spritenode->remove();
792                 m_spritenode->drop();
793                 m_spritenode = NULL;
794         }
795         if (m_textnode)
796         {
797                 m_textnode->remove();
798                 m_textnode->drop();
799                 m_textnode = NULL;
800         }
801 }
802
803 void GenericCAO::addToScene(scene::ISceneManager *smgr, ITextureSource *tsrc,
804                 IrrlichtDevice *irr)
805 {
806         m_smgr = smgr;
807         m_irr = irr;
808
809         if (getSceneNode() != NULL)
810                 return;
811
812         m_visuals_expired = false;
813
814         if(!m_prop.is_visible)
815                 return;
816
817         //video::IVideoDriver* driver = smgr->getVideoDriver();
818
819         if(m_prop.visual == "sprite")
820         {
821                 infostream<<"GenericCAO::addToScene(): single_sprite"<<std::endl;
822                 m_spritenode = smgr->addBillboardSceneNode(
823                                 NULL, v2f(1, 1), v3f(0,0,0), -1);
824                 m_spritenode->grab();
825                 m_spritenode->setMaterialTexture(0,
826                                 tsrc->getTexture("unknown_node.png"));
827                 m_spritenode->setMaterialFlag(video::EMF_LIGHTING, false);
828                 m_spritenode->setMaterialFlag(video::EMF_BILINEAR_FILTER, false);
829                 m_spritenode->setMaterialType(video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF);
830                 m_spritenode->setMaterialFlag(video::EMF_FOG_ENABLE, true);
831                 u8 li = m_last_light;
832                 m_spritenode->setColor(video::SColor(255,li,li,li));
833                 m_spritenode->setSize(m_prop.visual_size*BS);
834                 {
835                         const float txs = 1.0 / 1;
836                         const float tys = 1.0 / 1;
837                         setBillboardTextureMatrix(m_spritenode,
838                                         txs, tys, 0, 0);
839                 }
840         }
841         else if(m_prop.visual == "upright_sprite") {
842                 scene::SMesh *mesh = new scene::SMesh();
843                 double dx = BS*m_prop.visual_size.X/2;
844                 double dy = BS*m_prop.visual_size.Y/2;
845                 { // Front
846                 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
847                 u8 li = m_last_light;
848                 video::SColor c(255,li,li,li);
849                 video::S3DVertex vertices[4] =
850                 {
851                         video::S3DVertex(-dx,-dy,0, 0,0,0, c, 0,1),
852                         video::S3DVertex(dx,-dy,0, 0,0,0, c, 1,1),
853                         video::S3DVertex(dx,dy,0, 0,0,0, c, 1,0),
854                         video::S3DVertex(-dx,dy,0, 0,0,0, c, 0,0),
855                 };
856                 u16 indices[] = {0,1,2,2,3,0};
857                 buf->append(vertices, 4, indices, 6);
858                 // Set material
859                 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
860                 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
861                 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
862                 buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
863                 // Add to mesh
864                 mesh->addMeshBuffer(buf);
865                 buf->drop();
866                 }
867                 { // Back
868                 scene::IMeshBuffer *buf = new scene::SMeshBuffer();
869                 u8 li = m_last_light;
870                 video::SColor c(255,li,li,li);
871                 video::S3DVertex vertices[4] =
872                 {
873                         video::S3DVertex(dx,-dy,0, 0,0,0, c, 1,1),
874                         video::S3DVertex(-dx,-dy,0, 0,0,0, c, 0,1),
875                         video::S3DVertex(-dx,dy,0, 0,0,0, c, 0,0),
876                         video::S3DVertex(dx,dy,0, 0,0,0, c, 1,0),
877                 };
878                 u16 indices[] = {0,1,2,2,3,0};
879                 buf->append(vertices, 4, indices, 6);
880                 // Set material
881                 buf->getMaterial().setFlag(video::EMF_LIGHTING, false);
882                 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, false);
883                 buf->getMaterial().setFlag(video::EMF_FOG_ENABLE, true);
884                 buf->getMaterial().MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF;
885                 // Add to mesh
886                 mesh->addMeshBuffer(buf);
887                 buf->drop();
888                 }
889                 m_meshnode = smgr->addMeshSceneNode(mesh, NULL);
890                 m_meshnode->grab();
891                 mesh->drop();
892                 // Set it to use the materials of the meshbuffers directly.
893                 // This is needed for changing the texture in the future
894                 m_meshnode->setReadOnlyMaterials(true);
895         }
896         else if(m_prop.visual == "cube") {
897                 infostream<<"GenericCAO::addToScene(): cube"<<std::endl;
898                 scene::IMesh *mesh = createCubeMesh(v3f(BS,BS,BS));
899                 m_meshnode = smgr->addMeshSceneNode(mesh, NULL);
900                 m_meshnode->grab();
901                 mesh->drop();
902                 
903                 m_meshnode->setScale(v3f(m_prop.visual_size.X,
904                                 m_prop.visual_size.Y,
905                                 m_prop.visual_size.X));
906                 u8 li = m_last_light;
907                 setMeshColor(m_meshnode->getMesh(), video::SColor(255,li,li,li));
908
909                 m_meshnode->setMaterialFlag(video::EMF_LIGHTING, false);
910                 m_meshnode->setMaterialFlag(video::EMF_BILINEAR_FILTER, false);
911                 m_meshnode->setMaterialType(video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF);
912                 m_meshnode->setMaterialFlag(video::EMF_FOG_ENABLE, true);
913         }
914         else if(m_prop.visual == "mesh") {
915                 infostream<<"GenericCAO::addToScene(): mesh"<<std::endl;
916                 scene::IAnimatedMesh *mesh = m_gamedef->getMesh(m_prop.mesh);
917                 if(mesh)
918                 {
919                         m_animated_meshnode = smgr->addAnimatedMeshSceneNode(mesh, NULL);
920                         m_animated_meshnode->grab();
921                         mesh->drop(); // The scene node took hold of it
922                         m_animated_meshnode->animateJoints(); // Needed for some animations
923                         m_animated_meshnode->setScale(v3f(m_prop.visual_size.X,
924                                         m_prop.visual_size.Y,
925                                         m_prop.visual_size.X));
926                         u8 li = m_last_light;
927                         setMeshColor(m_animated_meshnode->getMesh(), video::SColor(255,li,li,li));
928
929                         m_animated_meshnode->setMaterialFlag(video::EMF_LIGHTING, false);
930                         m_animated_meshnode->setMaterialFlag(video::EMF_BILINEAR_FILTER, false);
931                         m_animated_meshnode->setMaterialType(video::EMT_TRANSPARENT_ALPHA_CHANNEL_REF);
932                         m_animated_meshnode->setMaterialFlag(video::EMF_FOG_ENABLE, true);
933                 }
934                 else
935                         errorstream<<"GenericCAO::addToScene(): Could not load mesh "<<m_prop.mesh<<std::endl;
936         }
937         else if(m_prop.visual == "wielditem") {
938                 infostream<<"GenericCAO::addToScene(): wielditem"<<std::endl;
939                 infostream<<"textures: "<<m_prop.textures.size()<<std::endl;
940                 if(m_prop.textures.size() >= 1){
941                         infostream<<"textures[0]: "<<m_prop.textures[0]<<std::endl;
942                         IItemDefManager *idef = m_gamedef->idef();
943                         ItemStack item(m_prop.textures[0], 1, 0, "", idef);
944
945                         m_wield_meshnode = new WieldMeshSceneNode(
946                                         smgr->getRootSceneNode(), smgr, -1);
947                         m_wield_meshnode->setItem(item, m_gamedef);
948
949                         m_wield_meshnode->setScale(v3f(m_prop.visual_size.X/2,
950                                         m_prop.visual_size.Y/2,
951                                         m_prop.visual_size.X/2));
952                         u8 li = m_last_light;
953                         m_wield_meshnode->setColor(video::SColor(255,li,li,li));
954                 }
955         } else {
956                 infostream<<"GenericCAO::addToScene(): \""<<m_prop.visual
957                                 <<"\" not supported"<<std::endl;
958         }
959         updateTextures("");
960
961         scene::ISceneNode *node = getSceneNode();
962         if (node && m_is_player && !m_is_local_player) {
963                 // Add a text node for showing the name
964                 gui::IGUIEnvironment* gui = irr->getGUIEnvironment();
965                 std::wstring wname = narrow_to_wide(m_name);
966                 m_textnode = smgr->addTextSceneNode(gui->getBuiltInFont(),
967                                 wname.c_str(), video::SColor(255,255,255,255), node);
968                 m_textnode->grab();
969                 m_textnode->setPosition(v3f(0, BS*1.1, 0));
970         }
971
972         updateNodePos();
973         updateAnimation();
974         updateBonePosition();
975         updateAttachments();
976 }
977
978 void GenericCAO::updateLight(u8 light_at_pos)
979 {
980         u8 li = decode_light(light_at_pos);
981         if(li != m_last_light)
982         {
983                 m_last_light = li;
984                 video::SColor color(255,li,li,li);
985                 if(m_meshnode)
986                         setMeshColor(m_meshnode->getMesh(), color);
987                 if(m_animated_meshnode)
988                         setMeshColor(m_animated_meshnode->getMesh(), color);
989                 if(m_wield_meshnode)
990                         m_wield_meshnode->setColor(color);
991                 if(m_spritenode)
992                         m_spritenode->setColor(color);
993         }
994 }
995
996 v3s16 GenericCAO::getLightPosition()
997 {
998         return floatToInt(m_position, BS);
999 }
1000
1001 void GenericCAO::updateNodePos()
1002 {
1003         if (getParent() != NULL)
1004                 return;
1005
1006         scene::ISceneNode *node = getSceneNode();
1007
1008         if (node) {
1009                 v3s16 camera_offset = m_env->getCameraOffset();
1010                 node->setPosition(pos_translator.vect_show - intToFloat(camera_offset, BS));
1011                 if (node != m_spritenode) { // rotate if not a sprite
1012                         v3f rot = node->getRotation();
1013                         rot.Y = -m_yaw;
1014                         node->setRotation(rot);
1015                 }
1016         }
1017 }
1018         
1019 void GenericCAO::step(float dtime, ClientEnvironment *env)
1020 {
1021         // Handel model of local player instantly to prevent lags
1022         if(m_is_local_player)
1023         {
1024                 LocalPlayer *player = m_env->getLocalPlayer();
1025
1026                 if (m_is_visible)
1027                 {
1028                         int old_anim = player->last_animation;
1029                         float old_anim_speed = player->last_animation_speed;
1030                         m_position = player->getPosition() + v3f(0,BS,0);
1031                         m_velocity = v3f(0,0,0);
1032                         m_acceleration = v3f(0,0,0);
1033                         pos_translator.vect_show = m_position;
1034                         m_yaw = player->getYaw();
1035                         PlayerControl controls = player->getPlayerControl();
1036
1037                         bool walking = false;
1038                         if(controls.up || controls.down || controls.left || controls.right)
1039                                 walking = true;
1040
1041                         f32 new_speed = player->local_animation_speed;
1042                         v2s32 new_anim = v2s32(0,0);
1043                         bool allow_update = false;
1044
1045                         // increase speed if using fast or flying fast
1046                         if((g_settings->getBool("fast_move") &&
1047                                         m_gamedef->checkLocalPrivilege("fast")) &&
1048                                         (controls.aux1 ||
1049                                         (!player->touching_ground &&
1050                                         g_settings->getBool("free_move") &&
1051                                         m_gamedef->checkLocalPrivilege("fly"))))
1052                                         new_speed *= 1.5;
1053                         // slowdown speed if sneeking
1054                         if(controls.sneak && walking)
1055                                 new_speed /= 2;
1056
1057                         if(walking && (controls.LMB || controls.RMB))
1058                         {
1059                                 new_anim = player->local_animations[3];
1060                                 player->last_animation = WD_ANIM;
1061                         } else if(walking) {
1062                                 new_anim = player->local_animations[1];
1063                                 player->last_animation = WALK_ANIM;
1064                         } else if(controls.LMB || controls.RMB) {
1065                                 new_anim = player->local_animations[2];
1066                                 player->last_animation = DIG_ANIM;
1067                         }
1068
1069                         // Apply animations if input detected and not attached
1070                         // or set idle animation
1071                         if ((new_anim.X + new_anim.Y) > 0 && !player->isAttached)
1072                         {
1073                                 allow_update = true;
1074                                 m_animation_range = new_anim;
1075                                 m_animation_speed = new_speed;
1076                                 player->last_animation_speed = m_animation_speed;
1077                         } else {
1078                                 player->last_animation = NO_ANIM;
1079
1080                                 if (old_anim != NO_ANIM)
1081                                 {
1082                                         m_animation_range = player->local_animations[0];
1083                                         updateAnimation();
1084                                 }
1085                         }
1086
1087                         // Update local player animations
1088                         if ((player->last_animation != old_anim ||
1089                                 m_animation_speed != old_anim_speed) &&
1090                                 player->last_animation != NO_ANIM && allow_update)
1091                                         updateAnimation();
1092
1093                 }
1094         }
1095
1096         if(m_visuals_expired && m_smgr && m_irr){
1097                 m_visuals_expired = false;
1098
1099                 // Attachments, part 1: All attached objects must be unparented first,
1100                 // or Irrlicht causes a segmentation fault
1101                 for(std::vector<u16>::iterator ci = m_children.begin();
1102                                 ci != m_children.end();)
1103                 {
1104                         if (m_env->m_attachements[*ci] != getId()) {
1105                                 ci = m_children.erase(ci);
1106                                 continue;
1107                         }
1108                         ClientActiveObject *obj = m_env->getActiveObject(*ci);
1109                         if (obj) {
1110                                 scene::ISceneNode *child_node = obj->getSceneNode();
1111                                 if (child_node)
1112                                         child_node->setParent(m_smgr->getRootSceneNode());
1113                         }
1114                         ++ci;
1115                 }
1116
1117                 removeFromScene(false);
1118                 addToScene(m_smgr, m_gamedef->tsrc(), m_irr);
1119
1120                 // Attachments, part 2: Now that the parent has been refreshed, put its attachments back
1121                 for(std::vector<u16>::iterator ci = m_children.begin();
1122                                                 ci != m_children.end(); ci++)
1123                 {
1124                         // Get the object of the child
1125                         ClientActiveObject *obj = m_env->getActiveObject(*ci);
1126                         if (obj)
1127                                 obj->setAttachments();
1128                 }
1129         }
1130
1131         // Make sure m_is_visible is always applied
1132         scene::ISceneNode *node = getSceneNode();
1133         if (node)
1134                 node->setVisible(m_is_visible);
1135
1136         if(getParent() != NULL) // Attachments should be glued to their parent by Irrlicht
1137         {
1138                 // Set these for later
1139                 m_position = getPosition();
1140                 m_velocity = v3f(0,0,0);
1141                 m_acceleration = v3f(0,0,0);
1142                 pos_translator.vect_show = m_position;
1143
1144                 if(m_is_local_player) // Update local player attachment position
1145                 {
1146                         LocalPlayer *player = m_env->getLocalPlayer();
1147                         player->overridePosition = getParent()->getPosition();
1148                         m_env->getLocalPlayer()->parent = getParent();
1149                 }
1150         } else {
1151                 v3f lastpos = pos_translator.vect_show;
1152
1153                 if(m_prop.physical)
1154                 {
1155                         core::aabbox3d<f32> box = m_prop.collisionbox;
1156                         box.MinEdge *= BS;
1157                         box.MaxEdge *= BS;
1158                         collisionMoveResult moveresult;
1159                         f32 pos_max_d = BS*0.125; // Distance per iteration
1160                         v3f p_pos = m_position;
1161                         v3f p_velocity = m_velocity;
1162                         v3f p_acceleration = m_acceleration;
1163                         moveresult = collisionMoveSimple(env,env->getGameDef(),
1164                                         pos_max_d, box, m_prop.stepheight, dtime,
1165                                         p_pos, p_velocity, p_acceleration,
1166                                         this, m_prop.collideWithObjects);
1167                         // Apply results
1168                         m_position = p_pos;
1169                         m_velocity = p_velocity;
1170                         m_acceleration = p_acceleration;
1171
1172                         bool is_end_position = moveresult.collides;
1173                         pos_translator.update(m_position, is_end_position, dtime);
1174                         pos_translator.translate(dtime);
1175                         updateNodePos();
1176                 } else {
1177                         m_position += dtime * m_velocity + 0.5 * dtime * dtime * m_acceleration;
1178                         m_velocity += dtime * m_acceleration;
1179                         pos_translator.update(m_position, pos_translator.aim_is_end,
1180                                         pos_translator.anim_time);
1181                         pos_translator.translate(dtime);
1182                         updateNodePos();
1183                 }
1184
1185                 float moved = lastpos.getDistanceFrom(pos_translator.vect_show);
1186                 m_step_distance_counter += moved;
1187                 if(m_step_distance_counter > 1.5*BS)
1188                 {
1189                         m_step_distance_counter = 0;
1190                         if(!m_is_local_player && m_prop.makes_footstep_sound)
1191                         {
1192                                 INodeDefManager *ndef = m_gamedef->ndef();
1193                                 v3s16 p = floatToInt(getPosition() + v3f(0,
1194                                                 (m_prop.collisionbox.MinEdge.Y-0.5)*BS, 0), BS);
1195                                 MapNode n = m_env->getMap().getNodeNoEx(p);
1196                                 SimpleSoundSpec spec = ndef->get(n).sound_footstep;
1197                                 m_gamedef->sound()->playSoundAt(spec, false, getPosition());
1198                         }
1199                 }
1200         }
1201
1202         m_anim_timer += dtime;
1203         if(m_anim_timer >= m_anim_framelength)
1204         {
1205                 m_anim_timer -= m_anim_framelength;
1206                 m_anim_frame++;
1207                 if(m_anim_frame >= m_anim_num_frames)
1208                         m_anim_frame = 0;
1209         }
1210
1211         updateTexturePos();
1212
1213         if(m_reset_textures_timer >= 0)
1214         {
1215                 m_reset_textures_timer -= dtime;
1216                 if(m_reset_textures_timer <= 0){
1217                         m_reset_textures_timer = -1;
1218                         updateTextures("");
1219                 }
1220         }
1221         if(getParent() == NULL && fabs(m_prop.automatic_rotate) > 0.001)
1222         {
1223                 m_yaw += dtime * m_prop.automatic_rotate * 180 / M_PI;
1224                 updateNodePos();
1225         }
1226
1227         if (getParent() == NULL && m_prop.automatic_face_movement_dir &&
1228                         (fabs(m_velocity.Z) > 0.001 || fabs(m_velocity.X) > 0.001))
1229         {
1230                 m_yaw = atan2(m_velocity.Z,m_velocity.X) * 180 / M_PI
1231                                 + m_prop.automatic_face_movement_dir_offset;
1232                 updateNodePos();
1233         }
1234 }
1235
1236 void GenericCAO::updateTexturePos()
1237 {
1238         if(m_spritenode)
1239         {
1240                 scene::ICameraSceneNode* camera =
1241                                 m_spritenode->getSceneManager()->getActiveCamera();
1242                 if(!camera)
1243                         return;
1244                 v3f cam_to_entity = m_spritenode->getAbsolutePosition()
1245                                 - camera->getAbsolutePosition();
1246                 cam_to_entity.normalize();
1247
1248                 int row = m_tx_basepos.Y;
1249                 int col = m_tx_basepos.X;
1250
1251                 if(m_tx_select_horiz_by_yawpitch)
1252                 {
1253                         if(cam_to_entity.Y > 0.75)
1254                                 col += 5;
1255                         else if(cam_to_entity.Y < -0.75)
1256                                 col += 4;
1257                         else{
1258                                 float mob_dir =
1259                                                 atan2(cam_to_entity.Z, cam_to_entity.X) / M_PI * 180.;
1260                                 float dir = mob_dir - m_yaw;
1261                                 dir = wrapDegrees_180(dir);
1262                                 //infostream<<"id="<<m_id<<" dir="<<dir<<std::endl;
1263                                 if(fabs(wrapDegrees_180(dir - 0)) <= 45.1)
1264                                         col += 2;
1265                                 else if(fabs(wrapDegrees_180(dir - 90)) <= 45.1)
1266                                         col += 3;
1267                                 else if(fabs(wrapDegrees_180(dir - 180)) <= 45.1)
1268                                         col += 0;
1269                                 else if(fabs(wrapDegrees_180(dir + 90)) <= 45.1)
1270                                         col += 1;
1271                                 else
1272                                         col += 4;
1273                         }
1274                 }
1275
1276                 // Animation goes downwards
1277                 row += m_anim_frame;
1278
1279                 float txs = m_tx_size.X;
1280                 float tys = m_tx_size.Y;
1281                 setBillboardTextureMatrix(m_spritenode,
1282                                 txs, tys, col, row);
1283         }
1284 }
1285
1286 void GenericCAO::updateTextures(const std::string &mod)
1287 {
1288         ITextureSource *tsrc = m_gamedef->tsrc();
1289
1290         bool use_trilinear_filter = g_settings->getBool("trilinear_filter");
1291         bool use_bilinear_filter = g_settings->getBool("bilinear_filter");
1292         bool use_anisotropic_filter = g_settings->getBool("anisotropic_filter");
1293
1294         if(m_spritenode)
1295         {
1296                 if(m_prop.visual == "sprite")
1297                 {
1298                         std::string texturestring = "unknown_node.png";
1299                         if(m_prop.textures.size() >= 1)
1300                                 texturestring = m_prop.textures[0];
1301                         texturestring += mod;
1302                         m_spritenode->setMaterialTexture(0,
1303                                         tsrc->getTexture(texturestring));
1304
1305                         // This allows setting per-material colors. However, until a real lighting
1306                         // system is added, the code below will have no effect. Once MineTest
1307                         // has directional lighting, it should work automatically.
1308                         if(m_prop.colors.size() >= 1)
1309                         {
1310                                 m_spritenode->getMaterial(0).AmbientColor = m_prop.colors[0];
1311                                 m_spritenode->getMaterial(0).DiffuseColor = m_prop.colors[0];
1312                                 m_spritenode->getMaterial(0).SpecularColor = m_prop.colors[0];
1313                         }
1314
1315                         m_spritenode->getMaterial(0).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1316                         m_spritenode->getMaterial(0).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1317                         m_spritenode->getMaterial(0).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1318                 }
1319         }
1320         if(m_animated_meshnode)
1321         {
1322                 if(m_prop.visual == "mesh")
1323                 {
1324                         for (u32 i = 0; i < m_prop.textures.size() &&
1325                                         i < m_animated_meshnode->getMaterialCount(); ++i)
1326                         {
1327                                 std::string texturestring = m_prop.textures[i];
1328                                 if(texturestring == "")
1329                                         continue; // Empty texture string means don't modify that material
1330                                 texturestring += mod;
1331                                 video::ITexture* texture = tsrc->getTexture(texturestring);
1332                                 if(!texture)
1333                                 {
1334                                         errorstream<<"GenericCAO::updateTextures(): Could not load texture "<<texturestring<<std::endl;
1335                                         continue;
1336                                 }
1337
1338                                 // Set material flags and texture
1339                                 video::SMaterial& material = m_animated_meshnode->getMaterial(i);
1340                                 material.TextureLayer[0].Texture = texture;
1341                                 material.setFlag(video::EMF_LIGHTING, false);
1342                                 material.setFlag(video::EMF_BILINEAR_FILTER, false);
1343
1344                                 m_animated_meshnode->getMaterial(i)
1345                                                 .setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1346                                 m_animated_meshnode->getMaterial(i)
1347                                                 .setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1348                                 m_animated_meshnode->getMaterial(i)
1349                                                 .setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1350                         }
1351                         for (u32 i = 0; i < m_prop.colors.size() &&
1352                         i < m_animated_meshnode->getMaterialCount(); ++i)
1353                         {
1354                                 // This allows setting per-material colors. However, until a real lighting
1355                                 // system is added, the code below will have no effect. Once MineTest
1356                                 // has directional lighting, it should work automatically.
1357                                 m_animated_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i];
1358                                 m_animated_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i];
1359                                 m_animated_meshnode->getMaterial(i).SpecularColor = m_prop.colors[i];
1360                         }
1361                 }
1362         }
1363         if(m_meshnode)
1364         {
1365                 if(m_prop.visual == "cube")
1366                 {
1367                         for (u32 i = 0; i < 6; ++i)
1368                         {
1369                                 std::string texturestring = "unknown_node.png";
1370                                 if(m_prop.textures.size() > i)
1371                                         texturestring = m_prop.textures[i];
1372                                 texturestring += mod;
1373
1374
1375                                 // Set material flags and texture
1376                                 video::SMaterial& material = m_meshnode->getMaterial(i);
1377                                 material.setFlag(video::EMF_LIGHTING, false);
1378                                 material.setFlag(video::EMF_BILINEAR_FILTER, false);
1379                                 material.setTexture(0,
1380                                                 tsrc->getTexture(texturestring));
1381                                 material.getTextureMatrix(0).makeIdentity();
1382
1383                                 // This allows setting per-material colors. However, until a real lighting
1384                                 // system is added, the code below will have no effect. Once MineTest
1385                                 // has directional lighting, it should work automatically.
1386                                 if(m_prop.colors.size() > i)
1387                                 {
1388                                         m_meshnode->getMaterial(i).AmbientColor = m_prop.colors[i];
1389                                         m_meshnode->getMaterial(i).DiffuseColor = m_prop.colors[i];
1390                                         m_meshnode->getMaterial(i).SpecularColor = m_prop.colors[i];
1391                                 }
1392
1393                                 m_meshnode->getMaterial(i).setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1394                                 m_meshnode->getMaterial(i).setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1395                                 m_meshnode->getMaterial(i).setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1396                         }
1397                 }
1398                 else if(m_prop.visual == "upright_sprite")
1399                 {
1400                         scene::IMesh *mesh = m_meshnode->getMesh();
1401                         {
1402                                 std::string tname = "unknown_object.png";
1403                                 if(m_prop.textures.size() >= 1)
1404                                         tname = m_prop.textures[0];
1405                                 tname += mod;
1406                                 scene::IMeshBuffer *buf = mesh->getMeshBuffer(0);
1407                                 buf->getMaterial().setTexture(0,
1408                                                 tsrc->getTexture(tname));
1409
1410                                 // This allows setting per-material colors. However, until a real lighting
1411                                 // system is added, the code below will have no effect. Once MineTest
1412                                 // has directional lighting, it should work automatically.
1413                                 if(m_prop.colors.size() >= 1)
1414                                 {
1415                                         buf->getMaterial().AmbientColor = m_prop.colors[0];
1416                                         buf->getMaterial().DiffuseColor = m_prop.colors[0];
1417                                         buf->getMaterial().SpecularColor = m_prop.colors[0];
1418                                 }
1419
1420                                 buf->getMaterial().setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1421                                 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1422                                 buf->getMaterial().setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1423                         }
1424                         {
1425                                 std::string tname = "unknown_object.png";
1426                                 if(m_prop.textures.size() >= 2)
1427                                         tname = m_prop.textures[1];
1428                                 else if(m_prop.textures.size() >= 1)
1429                                         tname = m_prop.textures[0];
1430                                 tname += mod;
1431                                 scene::IMeshBuffer *buf = mesh->getMeshBuffer(1);
1432                                 buf->getMaterial().setTexture(0,
1433                                                 tsrc->getTexture(tname));
1434
1435                                 // This allows setting per-material colors. However, until a real lighting
1436                                 // system is added, the code below will have no effect. Once MineTest
1437                                 // has directional lighting, it should work automatically.
1438                                 if(m_prop.colors.size() >= 2)
1439                                 {
1440                                         buf->getMaterial().AmbientColor = m_prop.colors[1];
1441                                         buf->getMaterial().DiffuseColor = m_prop.colors[1];
1442                                         buf->getMaterial().SpecularColor = m_prop.colors[1];
1443                                 }
1444                                 else if(m_prop.colors.size() >= 1)
1445                                 {
1446                                         buf->getMaterial().AmbientColor = m_prop.colors[0];
1447                                         buf->getMaterial().DiffuseColor = m_prop.colors[0];
1448                                         buf->getMaterial().SpecularColor = m_prop.colors[0];
1449                                 }
1450
1451                                 buf->getMaterial().setFlag(video::EMF_TRILINEAR_FILTER, use_trilinear_filter);
1452                                 buf->getMaterial().setFlag(video::EMF_BILINEAR_FILTER, use_bilinear_filter);
1453                                 buf->getMaterial().setFlag(video::EMF_ANISOTROPIC_FILTER, use_anisotropic_filter);
1454                         }
1455                 }
1456         }
1457 }
1458
1459 void GenericCAO::updateAnimation()
1460 {
1461         if(m_animated_meshnode == NULL)
1462                 return;
1463         m_animated_meshnode->setFrameLoop(m_animation_range.X, m_animation_range.Y);
1464         m_animated_meshnode->setAnimationSpeed(m_animation_speed);
1465         m_animated_meshnode->setTransitionTime(m_animation_blend);
1466 }
1467
1468 void GenericCAO::updateBonePosition()
1469 {
1470         if(m_bone_position.empty() || m_animated_meshnode == NULL)
1471                 return;
1472
1473         m_animated_meshnode->setJointMode(irr::scene::EJUOR_CONTROL); // To write positions to the mesh on render
1474         for(std::map<std::string,
1475                         core::vector2d<v3f> >::const_iterator ii = m_bone_position.begin();
1476                         ii != m_bone_position.end(); ++ii)
1477         {
1478                 std::string bone_name = (*ii).first;
1479                 v3f bone_pos = (*ii).second.X;
1480                 v3f bone_rot = (*ii).second.Y;
1481                 irr::scene::IBoneSceneNode* bone = m_animated_meshnode->getJointNode(bone_name.c_str());
1482                 if(bone)
1483                 {
1484                         bone->setPosition(bone_pos);
1485                         bone->setRotation(bone_rot);
1486                 }
1487         }
1488 }
1489         
1490 void GenericCAO::updateAttachments()
1491 {
1492
1493         // localplayer itself can't be attached to localplayer
1494         if (!m_is_local_player)
1495         {
1496                 m_attached_to_local = getParent() != NULL && getParent()->isLocalPlayer();
1497                 // Objects attached to the local player should always be hidden
1498                 m_is_visible = !m_attached_to_local;
1499         }
1500
1501         if(getParent() == NULL || m_attached_to_local) // Detach or don't attach
1502         {
1503                 scene::ISceneNode *node = getSceneNode();
1504                 if (node) {
1505                         v3f old_position = node->getAbsolutePosition();
1506                         v3f old_rotation = node->getRotation();
1507                         node->setParent(m_smgr->getRootSceneNode());
1508                         node->setPosition(old_position);
1509                         node->setRotation(old_rotation);
1510                         node->updateAbsolutePosition();
1511                 }
1512                 if (m_is_local_player) {
1513                         LocalPlayer *player = m_env->getLocalPlayer();
1514                         player->isAttached = false;
1515                 }
1516         }
1517         else // Attach
1518         {
1519                 scene::ISceneNode *my_node = getSceneNode();
1520
1521                 scene::ISceneNode *parent_node = getParent()->getSceneNode();
1522                 scene::IAnimatedMeshSceneNode *parent_animated_mesh_node =
1523                                 getParent()->getAnimatedMeshSceneNode();
1524                 if (parent_animated_mesh_node && m_attachment_bone != "") {
1525                         parent_node = parent_animated_mesh_node->getJointNode(m_attachment_bone.c_str());
1526                 }
1527
1528                 if (my_node && parent_node) {
1529                         my_node->setParent(parent_node);
1530                         my_node->setPosition(m_attachment_position);
1531                         my_node->setRotation(m_attachment_rotation);
1532                         my_node->updateAbsolutePosition();
1533                 }
1534                 if (m_is_local_player) {
1535                         LocalPlayer *player = m_env->getLocalPlayer();
1536                         player->isAttached = true;
1537                 }
1538         }
1539 }
1540
1541 void GenericCAO::processMessage(const std::string &data)
1542 {
1543         //infostream<<"GenericCAO: Got message"<<std::endl;
1544         std::istringstream is(data, std::ios::binary);
1545         // command
1546         u8 cmd = readU8(is);
1547         if(cmd == GENERIC_CMD_SET_PROPERTIES)
1548         {
1549                 m_prop = gob_read_set_properties(is);
1550
1551                 m_selection_box = m_prop.collisionbox;
1552                 m_selection_box.MinEdge *= BS;
1553                 m_selection_box.MaxEdge *= BS;
1554
1555                 m_tx_size.X = 1.0 / m_prop.spritediv.X;
1556                 m_tx_size.Y = 1.0 / m_prop.spritediv.Y;
1557
1558                 if(!m_initial_tx_basepos_set){
1559                         m_initial_tx_basepos_set = true;
1560                         m_tx_basepos = m_prop.initial_sprite_basepos;
1561                 }
1562
1563                 expireVisuals();
1564         }
1565         else if(cmd == GENERIC_CMD_UPDATE_POSITION)
1566         {
1567                 // Not sent by the server if this object is an attachment.
1568                 // We might however get here if the server notices the object being detached before the client.
1569                 m_position = readV3F1000(is);
1570                 m_velocity = readV3F1000(is);
1571                 m_acceleration = readV3F1000(is);
1572                 if(fabs(m_prop.automatic_rotate) < 0.001)
1573                         m_yaw = readF1000(is);
1574                 else
1575                         readF1000(is);
1576                 bool do_interpolate = readU8(is);
1577                 bool is_end_position = readU8(is);
1578                 float update_interval = readF1000(is);
1579
1580                 // Place us a bit higher if we're physical, to not sink into
1581                 // the ground due to sucky collision detection...
1582                 if(m_prop.physical)
1583                         m_position += v3f(0,0.002,0);
1584
1585                 if(getParent() != NULL) // Just in case
1586                         return;
1587
1588                 if(do_interpolate)
1589                 {
1590                         if(!m_prop.physical)
1591                                 pos_translator.update(m_position, is_end_position, update_interval);
1592                 } else {
1593                         pos_translator.init(m_position);
1594                 }
1595                 updateNodePos();
1596         }
1597         else if(cmd == GENERIC_CMD_SET_TEXTURE_MOD) {
1598                 std::string mod = deSerializeString(is);
1599                 updateTextures(mod);
1600         }
1601         else if(cmd == GENERIC_CMD_SET_SPRITE) {
1602                 v2s16 p = readV2S16(is);
1603                 int num_frames = readU16(is);
1604                 float framelength = readF1000(is);
1605                 bool select_horiz_by_yawpitch = readU8(is);
1606
1607                 m_tx_basepos = p;
1608                 m_anim_num_frames = num_frames;
1609                 m_anim_framelength = framelength;
1610                 m_tx_select_horiz_by_yawpitch = select_horiz_by_yawpitch;
1611
1612                 updateTexturePos();
1613         }
1614         else if(cmd == GENERIC_CMD_SET_PHYSICS_OVERRIDE) {
1615                 float override_speed = readF1000(is);
1616                 float override_jump = readF1000(is);
1617                 float override_gravity = readF1000(is);
1618                 // these are sent inverted so we get true when the server sends nothing
1619                 bool sneak = !readU8(is);
1620                 bool sneak_glitch = !readU8(is);
1621
1622
1623                 if(m_is_local_player)
1624                 {
1625                         LocalPlayer *player = m_env->getLocalPlayer();
1626                         player->physics_override_speed = override_speed;
1627                         player->physics_override_jump = override_jump;
1628                         player->physics_override_gravity = override_gravity;
1629                         player->physics_override_sneak = sneak;
1630                         player->physics_override_sneak_glitch = sneak_glitch;
1631                 }
1632         }
1633         else if(cmd == GENERIC_CMD_SET_ANIMATION) {
1634                 // TODO: change frames send as v2s32 value
1635                 v2f range = readV2F1000(is);
1636                 if (!m_is_local_player) {
1637                         m_animation_range = v2s32((s32)range.X, (s32)range.Y);
1638                         m_animation_speed = readF1000(is);
1639                         m_animation_blend = readF1000(is);
1640                         updateAnimation();
1641                 } else {
1642                         LocalPlayer *player = m_env->getLocalPlayer();
1643                         if(player->last_animation == NO_ANIM)
1644                         {
1645                                 m_animation_range = v2s32((s32)range.X, (s32)range.Y);
1646                                 m_animation_speed = readF1000(is);
1647                                 m_animation_blend = readF1000(is);
1648                         }
1649                         // update animation only if local animations present
1650                         // and received animation is unknown (except idle animation)
1651                         bool is_known = false;
1652                         for (int i = 1;i<4;i++)
1653                         {
1654                                 if(m_animation_range.Y == player->local_animations[i].Y)
1655                                         is_known = true;
1656                         }
1657                         if(!is_known ||
1658                                         (player->local_animations[1].Y + player->local_animations[2].Y < 1))
1659                         {
1660                                         updateAnimation();
1661                         }
1662                 }
1663         }
1664         else if(cmd == GENERIC_CMD_SET_BONE_POSITION) {
1665                 std::string bone = deSerializeString(is);
1666                 v3f position = readV3F1000(is);
1667                 v3f rotation = readV3F1000(is);
1668                 m_bone_position[bone] = core::vector2d<v3f>(position, rotation);
1669
1670                 updateBonePosition();
1671         }
1672         else if(cmd == GENERIC_CMD_SET_ATTACHMENT) {
1673                 m_env->m_attachements[getId()] = readS16(is);
1674                 m_children.push_back(m_env->m_attachements[getId()]);
1675                 m_attachment_bone = deSerializeString(is);
1676                 m_attachment_position = readV3F1000(is);
1677                 m_attachment_rotation = readV3F1000(is);
1678
1679                 updateAttachments();
1680         }
1681         else if(cmd == GENERIC_CMD_PUNCHED) {
1682                 /*s16 damage =*/ readS16(is);
1683                 s16 result_hp = readS16(is);
1684
1685                 // Use this instead of the send damage to not interfere with prediction
1686                 s16 damage = m_hp - result_hp;
1687
1688                 m_hp = result_hp;
1689
1690                 if (damage > 0)
1691                 {
1692                         if (m_hp <= 0)
1693                         {
1694                                 // TODO: Execute defined fast response
1695                                 // As there is no definition, make a smoke puff
1696                                 ClientSimpleObject *simple = createSmokePuff(
1697                                                 m_smgr, m_env, m_position,
1698                                                 m_prop.visual_size * BS);
1699                                 m_env->addSimpleObject(simple);
1700                         } else {
1701                                 // TODO: Execute defined fast response
1702                                 // Flashing shall suffice as there is no definition
1703                                 m_reset_textures_timer = 0.05;
1704                                 if(damage >= 2)
1705                                         m_reset_textures_timer += 0.05 * damage;
1706                                 updateTextures("^[brighten");
1707                         }
1708                 }
1709         }
1710         else if(cmd == GENERIC_CMD_UPDATE_ARMOR_GROUPS) {
1711                 m_armor_groups.clear();
1712                 int armor_groups_size = readU16(is);
1713                 for(int i=0; i<armor_groups_size; i++)
1714                 {
1715                         std::string name = deSerializeString(is);
1716                         int rating = readS16(is);
1717                         m_armor_groups[name] = rating;
1718                 }
1719         }
1720 }
1721         
1722 bool GenericCAO::directReportPunch(v3f dir, const ItemStack *punchitem,
1723                 float time_from_last_punch)
1724 {
1725         assert(punchitem);
1726         const ToolCapabilities *toolcap =
1727                         &punchitem->getToolCapabilities(m_gamedef->idef());
1728         PunchDamageResult result = getPunchDamage(
1729                         m_armor_groups,
1730                         toolcap,
1731                         punchitem,
1732                         time_from_last_punch);
1733
1734         if(result.did_punch && result.damage != 0)
1735         {
1736                 if(result.damage < m_hp)
1737                 {
1738                         m_hp -= result.damage;
1739                 } else {
1740                         m_hp = 0;
1741                         // TODO: Execute defined fast response
1742                         // As there is no definition, make a smoke puff
1743                         ClientSimpleObject *simple = createSmokePuff(
1744                                         m_smgr, m_env, m_position,
1745                                         m_prop.visual_size * BS);
1746                         m_env->addSimpleObject(simple);
1747                 }
1748                 // TODO: Execute defined fast response
1749                 // Flashing shall suffice as there is no definition
1750                 m_reset_textures_timer = 0.05;
1751                 if(result.damage >= 2)
1752                         m_reset_textures_timer += 0.05 * result.damage;
1753                 updateTextures("^[brighten");
1754         }
1755
1756         return false;
1757 }
1758
1759 std::string GenericCAO::debugInfoText()
1760 {
1761         std::ostringstream os(std::ios::binary);
1762         os<<"GenericCAO hp="<<m_hp<<"\n";
1763         os<<"armor={";
1764         for(ItemGroupList::const_iterator i = m_armor_groups.begin();
1765                         i != m_armor_groups.end(); i++)
1766         {
1767                 os<<i->first<<"="<<i->second<<", ";
1768         }
1769         os<<"}";
1770         return os.str();
1771 }
1772
1773 // Prototype
1774 GenericCAO proto_GenericCAO(NULL, NULL);