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