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