Delete unknown LuaEntities when punched
[oweals/minetest.git] / src / content_sao.cpp
1 /*
2 Minetest-c55
3 Copyright (C) 2010-2011 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "content_sao.h"
21 #include "collision.h"
22 #include "environment.h"
23 #include "settings.h"
24 #include "main.h" // For g_profiler
25 #include "profiler.h"
26 #include "serialization.h" // For compressZlib
27 #include "materials.h" // For MaterialProperties
28 #include "tooldef.h" // ToolDiggingProperties
29
30 core::map<u16, ServerActiveObject::Factory> ServerActiveObject::m_types;
31
32 /* Some helper functions */
33
34 // Y is copied, X and Z change is limited
35 void accelerate_xz(v3f &speed, v3f target_speed, f32 max_increase)
36 {
37         v3f d_wanted = target_speed - speed;
38         d_wanted.Y = 0;
39         f32 dl_wanted = d_wanted.getLength();
40         f32 dl = dl_wanted;
41         if(dl > max_increase)
42                 dl = max_increase;
43         
44         v3f d = d_wanted.normalize() * dl;
45
46         speed.X += d.X;
47         speed.Z += d.Z;
48         speed.Y = target_speed.Y;
49 }
50
51 /*
52         TestSAO
53 */
54
55 // Prototype
56 TestSAO proto_TestSAO(NULL, v3f(0,0,0));
57
58 TestSAO::TestSAO(ServerEnvironment *env, v3f pos):
59         ServerActiveObject(env, pos),
60         m_timer1(0),
61         m_age(0)
62 {
63         ServerActiveObject::registerType(getType(), create);
64 }
65
66 ServerActiveObject* TestSAO::create(ServerEnvironment *env, v3f pos,
67                 const std::string &data)
68 {
69         return new TestSAO(env, pos);
70 }
71
72 void TestSAO::step(float dtime, bool send_recommended)
73 {
74         m_age += dtime;
75         if(m_age > 10)
76         {
77                 m_removed = true;
78                 return;
79         }
80
81         m_base_position.Y += dtime * BS * 2;
82         if(m_base_position.Y > 8*BS)
83                 m_base_position.Y = 2*BS;
84
85         if(send_recommended == false)
86                 return;
87
88         m_timer1 -= dtime;
89         if(m_timer1 < 0.0)
90         {
91                 m_timer1 += 0.125;
92
93                 std::string data;
94
95                 data += itos(0); // 0 = position
96                 data += " ";
97                 data += itos(m_base_position.X);
98                 data += " ";
99                 data += itos(m_base_position.Y);
100                 data += " ";
101                 data += itos(m_base_position.Z);
102
103                 ActiveObjectMessage aom(getId(), false, data);
104                 m_messages_out.push_back(aom);
105         }
106 }
107
108
109 /*
110         ItemSAO
111 */
112
113 // Prototype
114 ItemSAO proto_ItemSAO(NULL, v3f(0,0,0), "");
115
116 ItemSAO::ItemSAO(ServerEnvironment *env, v3f pos,
117                 const std::string inventorystring):
118         ServerActiveObject(env, pos),
119         m_inventorystring(inventorystring),
120         m_speed_f(0,0,0),
121         m_last_sent_position(0,0,0)
122 {
123         ServerActiveObject::registerType(getType(), create);
124 }
125
126 ServerActiveObject* ItemSAO::create(ServerEnvironment *env, v3f pos,
127                 const std::string &data)
128 {
129         std::istringstream is(data, std::ios::binary);
130         char buf[1];
131         // read version
132         is.read(buf, 1);
133         u8 version = buf[0];
134         // check if version is supported
135         if(version != 0)
136                 return NULL;
137         std::string inventorystring = deSerializeString(is);
138         infostream<<"ItemSAO::create(): Creating item \""
139                         <<inventorystring<<"\""<<std::endl;
140         return new ItemSAO(env, pos, inventorystring);
141 }
142
143 void ItemSAO::step(float dtime, bool send_recommended)
144 {
145         ScopeProfiler sp2(g_profiler, "ItemSAO::step avg", SPT_AVG);
146
147         assert(m_env);
148
149         const float interval = 0.2;
150         if(m_move_interval.step(dtime, interval)==false)
151                 return;
152         dtime = interval;
153         
154         core::aabbox3d<f32> box(-BS/3.,0.0,-BS/3., BS/3.,BS*2./3.,BS/3.);
155         collisionMoveResult moveresult;
156         // Apply gravity
157         m_speed_f += v3f(0, -dtime*9.81*BS, 0);
158         // Maximum movement without glitches
159         f32 pos_max_d = BS*0.25;
160         // Limit speed
161         if(m_speed_f.getLength()*dtime > pos_max_d)
162                 m_speed_f *= pos_max_d / (m_speed_f.getLength()*dtime);
163         v3f pos_f = getBasePosition();
164         v3f pos_f_old = pos_f;
165         IGameDef *gamedef = m_env->getGameDef();
166         moveresult = collisionMoveSimple(&m_env->getMap(), gamedef,
167                         pos_max_d, box, dtime, pos_f, m_speed_f);
168         
169         if(send_recommended == false)
170                 return;
171
172         if(pos_f.getDistanceFrom(m_last_sent_position) > 0.05*BS)
173         {
174                 setBasePosition(pos_f);
175                 m_last_sent_position = pos_f;
176
177                 std::ostringstream os(std::ios::binary);
178                 char buf[6];
179                 // command (0 = update position)
180                 buf[0] = 0;
181                 os.write(buf, 1);
182                 // pos
183                 writeS32((u8*)buf, m_base_position.X*1000);
184                 os.write(buf, 4);
185                 writeS32((u8*)buf, m_base_position.Y*1000);
186                 os.write(buf, 4);
187                 writeS32((u8*)buf, m_base_position.Z*1000);
188                 os.write(buf, 4);
189                 // create message and add to list
190                 ActiveObjectMessage aom(getId(), false, os.str());
191                 m_messages_out.push_back(aom);
192         }
193 }
194
195 std::string ItemSAO::getClientInitializationData()
196 {
197         std::ostringstream os(std::ios::binary);
198         char buf[6];
199         // version
200         buf[0] = 0;
201         os.write(buf, 1);
202         // pos
203         writeS32((u8*)buf, m_base_position.X*1000);
204         os.write(buf, 4);
205         writeS32((u8*)buf, m_base_position.Y*1000);
206         os.write(buf, 4);
207         writeS32((u8*)buf, m_base_position.Z*1000);
208         os.write(buf, 4);
209         // inventorystring
210         os<<serializeString(m_inventorystring);
211         return os.str();
212 }
213
214 std::string ItemSAO::getStaticData()
215 {
216         infostream<<__FUNCTION_NAME<<std::endl;
217         std::ostringstream os(std::ios::binary);
218         char buf[1];
219         // version
220         buf[0] = 0;
221         os.write(buf, 1);
222         // inventorystring
223         os<<serializeString(m_inventorystring);
224         return os.str();
225 }
226
227 InventoryItem * ItemSAO::createInventoryItem()
228 {
229         try{
230                 std::istringstream is(m_inventorystring, std::ios_base::binary);
231                 IGameDef *gamedef = m_env->getGameDef();
232                 InventoryItem *item = InventoryItem::deSerialize(is, gamedef);
233                 infostream<<__FUNCTION_NAME<<": m_inventorystring=\""
234                                 <<m_inventorystring<<"\" -> item="<<item
235                                 <<std::endl;
236                 return item;
237         }
238         catch(SerializationError &e)
239         {
240                 infostream<<__FUNCTION_NAME<<": serialization error: "
241                                 <<"m_inventorystring=\""<<m_inventorystring<<"\""<<std::endl;
242                 return NULL;
243         }
244 }
245
246 void ItemSAO::punch(ServerActiveObject *puncher, float time_from_last_punch)
247 {
248         InventoryItem *item = createInventoryItem();
249         bool fits = puncher->addToInventory(item);
250         if(fits)
251                 m_removed = true;
252         else
253                 delete item;
254 }
255
256 /*
257         RatSAO
258 */
259
260 // Prototype
261 RatSAO proto_RatSAO(NULL, v3f(0,0,0));
262
263 RatSAO::RatSAO(ServerEnvironment *env, v3f pos):
264         ServerActiveObject(env, pos),
265         m_is_active(false),
266         m_speed_f(0,0,0)
267 {
268         ServerActiveObject::registerType(getType(), create);
269
270         m_oldpos = v3f(0,0,0);
271         m_last_sent_position = v3f(0,0,0);
272         m_yaw = myrand_range(0,PI*2);
273         m_counter1 = 0;
274         m_counter2 = 0;
275         m_age = 0;
276         m_touching_ground = false;
277 }
278
279 ServerActiveObject* RatSAO::create(ServerEnvironment *env, v3f pos,
280                 const std::string &data)
281 {
282         std::istringstream is(data, std::ios::binary);
283         char buf[1];
284         // read version
285         is.read(buf, 1);
286         u8 version = buf[0];
287         // check if version is supported
288         if(version != 0)
289                 return NULL;
290         return new RatSAO(env, pos);
291 }
292
293 void RatSAO::step(float dtime, bool send_recommended)
294 {
295         ScopeProfiler sp2(g_profiler, "RatSAO::step avg", SPT_AVG);
296
297         assert(m_env);
298
299         if(m_is_active == false)
300         {
301                 if(m_inactive_interval.step(dtime, 0.5)==false)
302                         return;
303         }
304
305         /*
306                 The AI
307         */
308
309         /*m_age += dtime;
310         if(m_age > 60)
311         {
312                 // Die
313                 m_removed = true;
314                 return;
315         }*/
316
317         // Apply gravity
318         m_speed_f.Y -= dtime*9.81*BS;
319
320         /*
321                 Move around if some player is close
322         */
323         bool player_is_close = false;
324         // Check connected players
325         core::list<Player*> players = m_env->getPlayers(true);
326         core::list<Player*>::Iterator i;
327         for(i = players.begin();
328                         i != players.end(); i++)
329         {
330                 Player *player = *i;
331                 v3f playerpos = player->getPosition();
332                 if(m_base_position.getDistanceFrom(playerpos) < BS*10.0)
333                 {
334                         player_is_close = true;
335                         break;
336                 }
337         }
338
339         m_is_active = player_is_close;
340         
341         if(player_is_close == false)
342         {
343                 m_speed_f.X = 0;
344                 m_speed_f.Z = 0;
345         }
346         else
347         {
348                 // Move around
349                 v3f dir(cos(m_yaw/180*PI),0,sin(m_yaw/180*PI));
350                 f32 speed = 2*BS;
351                 m_speed_f.X = speed * dir.X;
352                 m_speed_f.Z = speed * dir.Z;
353
354                 if(m_touching_ground && (m_oldpos - m_base_position).getLength()
355                                 < dtime*speed/2)
356                 {
357                         m_counter1 -= dtime;
358                         if(m_counter1 < 0.0)
359                         {
360                                 m_counter1 += 1.0;
361                                 m_speed_f.Y = 5.0*BS;
362                         }
363                 }
364
365                 {
366                         m_counter2 -= dtime;
367                         if(m_counter2 < 0.0)
368                         {
369                                 m_counter2 += (float)(myrand()%100)/100*3.0;
370                                 m_yaw += ((float)(myrand()%200)-100)/100*180;
371                                 m_yaw = wrapDegrees(m_yaw);
372                         }
373                 }
374         }
375         
376         m_oldpos = m_base_position;
377
378         /*
379                 Move it, with collision detection
380         */
381
382         core::aabbox3d<f32> box(-BS/3.,0.0,-BS/3., BS/3.,BS*2./3.,BS/3.);
383         collisionMoveResult moveresult;
384         // Maximum movement without glitches
385         f32 pos_max_d = BS*0.25;
386         // Limit speed
387         if(m_speed_f.getLength()*dtime > pos_max_d)
388                 m_speed_f *= pos_max_d / (m_speed_f.getLength()*dtime);
389         v3f pos_f = getBasePosition();
390         v3f pos_f_old = pos_f;
391         IGameDef *gamedef = m_env->getGameDef();
392         moveresult = collisionMoveSimple(&m_env->getMap(), gamedef,
393                         pos_max_d, box, dtime, pos_f, m_speed_f);
394         m_touching_ground = moveresult.touching_ground;
395         
396         setBasePosition(pos_f);
397
398         if(send_recommended == false)
399                 return;
400
401         if(pos_f.getDistanceFrom(m_last_sent_position) > 0.05*BS)
402         {
403                 m_last_sent_position = pos_f;
404
405                 std::ostringstream os(std::ios::binary);
406                 // command (0 = update position)
407                 writeU8(os, 0);
408                 // pos
409                 writeV3F1000(os, m_base_position);
410                 // yaw
411                 writeF1000(os, m_yaw);
412                 // create message and add to list
413                 ActiveObjectMessage aom(getId(), false, os.str());
414                 m_messages_out.push_back(aom);
415         }
416 }
417
418 std::string RatSAO::getClientInitializationData()
419 {
420         std::ostringstream os(std::ios::binary);
421         // version
422         writeU8(os, 0);
423         // pos
424         writeV3F1000(os, m_base_position);
425         return os.str();
426 }
427
428 std::string RatSAO::getStaticData()
429 {
430         //infostream<<__FUNCTION_NAME<<std::endl;
431         std::ostringstream os(std::ios::binary);
432         // version
433         writeU8(os, 0);
434         return os.str();
435 }
436
437 void RatSAO::punch(ServerActiveObject *puncher, float time_from_last_punch)
438 {
439         std::istringstream is("CraftItem rat 1", std::ios_base::binary);
440         IGameDef *gamedef = m_env->getGameDef();
441         InventoryItem *item = InventoryItem::deSerialize(is, gamedef);
442         bool fits = puncher->addToInventory(item);
443         if(fits)
444                 m_removed = true;
445         else
446                 delete item;
447 }
448
449 /*
450         Oerkki1SAO
451 */
452
453 // Prototype
454 Oerkki1SAO proto_Oerkki1SAO(NULL, v3f(0,0,0));
455
456 Oerkki1SAO::Oerkki1SAO(ServerEnvironment *env, v3f pos):
457         ServerActiveObject(env, pos),
458         m_is_active(false),
459         m_speed_f(0,0,0)
460 {
461         ServerActiveObject::registerType(getType(), create);
462
463         m_oldpos = v3f(0,0,0);
464         m_last_sent_position = v3f(0,0,0);
465         m_yaw = 0;
466         m_counter1 = 0;
467         m_counter2 = 0;
468         m_age = 0;
469         m_touching_ground = false;
470         m_hp = 20;
471         m_after_jump_timer = 0;
472 }
473
474 ServerActiveObject* Oerkki1SAO::create(ServerEnvironment *env, v3f pos,
475                 const std::string &data)
476 {
477         std::istringstream is(data, std::ios::binary);
478         // read version
479         u8 version = readU8(is);
480         // read hp
481         u8 hp = readU8(is);
482         // check if version is supported
483         if(version != 0)
484                 return NULL;
485         Oerkki1SAO *o = new Oerkki1SAO(env, pos);
486         o->m_hp = hp;
487         return o;
488 }
489
490 void Oerkki1SAO::step(float dtime, bool send_recommended)
491 {
492         ScopeProfiler sp2(g_profiler, "Oerkki1SAO::step avg", SPT_AVG);
493
494         assert(m_env);
495
496         if(m_is_active == false)
497         {
498                 if(m_inactive_interval.step(dtime, 0.5)==false)
499                         return;
500         }
501
502         /*
503                 The AI
504         */
505
506         m_age += dtime;
507         if(m_age > 120)
508         {
509                 // Die
510                 m_removed = true;
511                 return;
512         }
513
514         m_after_jump_timer -= dtime;
515
516         v3f old_speed = m_speed_f;
517
518         // Apply gravity
519         m_speed_f.Y -= dtime*9.81*BS;
520
521         /*
522                 Move around if some player is close
523         */
524         bool player_is_close = false;
525         bool player_is_too_close = false;
526         v3f near_player_pos;
527         // Check connected players
528         core::list<Player*> players = m_env->getPlayers(true);
529         core::list<Player*>::Iterator i;
530         for(i = players.begin();
531                         i != players.end(); i++)
532         {
533                 Player *player = *i;
534                 v3f playerpos = player->getPosition();
535                 f32 dist = m_base_position.getDistanceFrom(playerpos);
536                 if(dist < BS*0.6)
537                 {
538                         m_removed = true;
539                         return;
540                         player_is_too_close = true;
541                         near_player_pos = playerpos;
542                 }
543                 else if(dist < BS*15.0 && !player_is_too_close)
544                 {
545                         player_is_close = true;
546                         near_player_pos = playerpos;
547                 }
548         }
549
550         m_is_active = player_is_close;
551
552         v3f target_speed = m_speed_f;
553
554         if(!player_is_close)
555         {
556                 target_speed = v3f(0,0,0);
557         }
558         else
559         {
560                 // Move around
561
562                 v3f ndir = near_player_pos - m_base_position;
563                 ndir.Y = 0;
564                 ndir.normalize();
565
566                 f32 nyaw = 180./PI*atan2(ndir.Z,ndir.X);
567                 if(nyaw < m_yaw - 180)
568                         nyaw += 360;
569                 else if(nyaw > m_yaw + 180)
570                         nyaw -= 360;
571                 m_yaw = 0.95*m_yaw + 0.05*nyaw;
572                 m_yaw = wrapDegrees(m_yaw);
573                 
574                 f32 speed = 2*BS;
575
576                 if((m_touching_ground || m_after_jump_timer > 0.0)
577                                 && !player_is_too_close)
578                 {
579                         v3f dir(cos(m_yaw/180*PI),0,sin(m_yaw/180*PI));
580                         target_speed.X = speed * dir.X;
581                         target_speed.Z = speed * dir.Z;
582                 }
583
584                 if(m_touching_ground && (m_oldpos - m_base_position).getLength()
585                                 < dtime*speed/2)
586                 {
587                         m_counter1 -= dtime;
588                         if(m_counter1 < 0.0)
589                         {
590                                 m_counter1 += 0.2;
591                                 // Jump
592                                 target_speed.Y = 5.0*BS;
593                                 m_after_jump_timer = 1.0;
594                         }
595                 }
596
597                 {
598                         m_counter2 -= dtime;
599                         if(m_counter2 < 0.0)
600                         {
601                                 m_counter2 += (float)(myrand()%100)/100*3.0;
602                                 //m_yaw += ((float)(myrand()%200)-100)/100*180;
603                                 m_yaw += ((float)(myrand()%200)-100)/100*90;
604                                 m_yaw = wrapDegrees(m_yaw);
605                         }
606                 }
607         }
608         
609         if((m_speed_f - target_speed).getLength() > BS*4 || player_is_too_close)
610                 accelerate_xz(m_speed_f, target_speed, dtime*BS*8);
611         else
612                 accelerate_xz(m_speed_f, target_speed, dtime*BS*4);
613         
614         m_oldpos = m_base_position;
615
616         /*
617                 Move it, with collision detection
618         */
619
620         core::aabbox3d<f32> box(-BS/3.,0.0,-BS/3., BS/3.,BS*5./3.,BS/3.);
621         collisionMoveResult moveresult;
622         // Maximum movement without glitches
623         f32 pos_max_d = BS*0.25;
624         /*// Limit speed
625         if(m_speed_f.getLength()*dtime > pos_max_d)
626                 m_speed_f *= pos_max_d / (m_speed_f.getLength()*dtime);*/
627         v3f pos_f = getBasePosition();
628         v3f pos_f_old = pos_f;
629         IGameDef *gamedef = m_env->getGameDef();
630         moveresult = collisionMovePrecise(&m_env->getMap(), gamedef,
631                         pos_max_d, box, dtime, pos_f, m_speed_f);
632         m_touching_ground = moveresult.touching_ground;
633         
634         // Do collision damage
635         float tolerance = BS*30;
636         float factor = BS*0.5;
637         v3f speed_diff = old_speed - m_speed_f;
638         // Increase effect in X and Z
639         speed_diff.X *= 2;
640         speed_diff.Z *= 2;
641         float vel = speed_diff.getLength();
642         if(vel > tolerance)
643         {
644                 f32 damage_f = (vel - tolerance)/BS*factor;
645                 u16 damage = (u16)(damage_f+0.5);
646                 doDamage(damage);
647         }
648
649         setBasePosition(pos_f);
650
651         if(send_recommended == false && m_speed_f.getLength() < 3.0*BS)
652                 return;
653
654         if(pos_f.getDistanceFrom(m_last_sent_position) > 0.05*BS)
655         {
656                 m_last_sent_position = pos_f;
657
658                 std::ostringstream os(std::ios::binary);
659                 // command (0 = update position)
660                 writeU8(os, 0);
661                 // pos
662                 writeV3F1000(os, m_base_position);
663                 // yaw
664                 writeF1000(os, m_yaw);
665                 // create message and add to list
666                 ActiveObjectMessage aom(getId(), false, os.str());
667                 m_messages_out.push_back(aom);
668         }
669 }
670
671 std::string Oerkki1SAO::getClientInitializationData()
672 {
673         std::ostringstream os(std::ios::binary);
674         // version
675         writeU8(os, 0);
676         // pos
677         writeV3F1000(os, m_base_position);
678         return os.str();
679 }
680
681 std::string Oerkki1SAO::getStaticData()
682 {
683         //infostream<<__FUNCTION_NAME<<std::endl;
684         std::ostringstream os(std::ios::binary);
685         // version
686         writeU8(os, 0);
687         // hp
688         writeU8(os, m_hp);
689         return os.str();
690 }
691
692 void Oerkki1SAO::punch(ServerActiveObject *puncher, float time_from_last_punch)
693 {
694         if(!puncher)
695                 return;
696         
697         v3f dir = (getBasePosition() - puncher->getBasePosition()).normalize();
698         m_speed_f += dir*12*BS;
699
700         // "Material" properties of an oerkki
701         MaterialProperties mp;
702         mp.diggability = DIGGABLE_NORMAL;
703         mp.crackiness = -1.0;
704         mp.cuttability = 1.0;
705
706         ToolDiggingProperties tp;
707         puncher->getWieldDiggingProperties(&tp);
708
709         HittingProperties hitprop = getHittingProperties(&mp, &tp,
710                         time_from_last_punch);
711
712         doDamage(hitprop.hp);
713         puncher->damageWieldedItem(hitprop.wear);
714 }
715
716 void Oerkki1SAO::doDamage(u16 d)
717 {
718         infostream<<"oerkki damage: "<<d<<std::endl;
719         
720         if(d < m_hp)
721         {
722                 m_hp -= d;
723         }
724         else
725         {
726                 // Die
727                 m_hp = 0;
728                 m_removed = true;
729         }
730
731         {
732                 std::ostringstream os(std::ios::binary);
733                 // command (1 = damage)
734                 writeU8(os, 1);
735                 // amount
736                 writeU8(os, d);
737                 // create message and add to list
738                 ActiveObjectMessage aom(getId(), false, os.str());
739                 m_messages_out.push_back(aom);
740         }
741 }
742
743 /*
744         FireflySAO
745 */
746
747 // Prototype
748 FireflySAO proto_FireflySAO(NULL, v3f(0,0,0));
749
750 FireflySAO::FireflySAO(ServerEnvironment *env, v3f pos):
751         ServerActiveObject(env, pos),
752         m_is_active(false),
753         m_speed_f(0,0,0)
754 {
755         ServerActiveObject::registerType(getType(), create);
756
757         m_oldpos = v3f(0,0,0);
758         m_last_sent_position = v3f(0,0,0);
759         m_yaw = 0;
760         m_counter1 = 0;
761         m_counter2 = 0;
762         m_age = 0;
763         m_touching_ground = false;
764 }
765
766 ServerActiveObject* FireflySAO::create(ServerEnvironment *env, v3f pos,
767                 const std::string &data)
768 {
769         std::istringstream is(data, std::ios::binary);
770         char buf[1];
771         // read version
772         is.read(buf, 1);
773         u8 version = buf[0];
774         // check if version is supported
775         if(version != 0)
776                 return NULL;
777         return new FireflySAO(env, pos);
778 }
779
780 void FireflySAO::step(float dtime, bool send_recommended)
781 {
782         ScopeProfiler sp2(g_profiler, "FireflySAO::step avg", SPT_AVG);
783
784         assert(m_env);
785
786         if(m_is_active == false)
787         {
788                 if(m_inactive_interval.step(dtime, 0.5)==false)
789                         return;
790         }
791
792         /*
793                 The AI
794         */
795
796         // Apply (less) gravity
797         m_speed_f.Y -= dtime*3*BS;
798
799         /*
800                 Move around if some player is close
801         */
802         bool player_is_close = false;
803         // Check connected players
804         core::list<Player*> players = m_env->getPlayers(true);
805         core::list<Player*>::Iterator i;
806         for(i = players.begin();
807                         i != players.end(); i++)
808         {
809                 Player *player = *i;
810                 v3f playerpos = player->getPosition();
811                 if(m_base_position.getDistanceFrom(playerpos) < BS*10.0)
812                 {
813                         player_is_close = true;
814                         break;
815                 }
816         }
817
818         m_is_active = player_is_close;
819         
820         if(player_is_close == false)
821         {
822                 m_speed_f.X = 0;
823                 m_speed_f.Z = 0;
824         }
825         else
826         {
827                 // Move around
828                 v3f dir(cos(m_yaw/180*PI),0,sin(m_yaw/180*PI));
829                 f32 speed = BS/2;
830                 m_speed_f.X = speed * dir.X;
831                 m_speed_f.Z = speed * dir.Z;
832
833                 if(m_touching_ground && (m_oldpos - m_base_position).getLength()
834                                 < dtime*speed/2)
835                 {
836                         m_counter1 -= dtime;
837                         if(m_counter1 < 0.0)
838                         {
839                                 m_counter1 += 1.0;
840                                 m_speed_f.Y = 5.0*BS;
841                         }
842                 }
843
844                 {
845                         m_counter2 -= dtime;
846                         if(m_counter2 < 0.0)
847                         {
848                                 m_counter2 += (float)(myrand()%100)/100*3.0;
849                                 m_yaw += ((float)(myrand()%200)-100)/100*180;
850                                 m_yaw = wrapDegrees(m_yaw);
851                         }
852                 }
853         }
854         
855         m_oldpos = m_base_position;
856
857         /*
858                 Move it, with collision detection
859         */
860
861         core::aabbox3d<f32> box(-BS/3.,-BS*2/3.0,-BS/3., BS/3.,BS*4./3.,BS/3.);
862         collisionMoveResult moveresult;
863         // Maximum movement without glitches
864         f32 pos_max_d = BS*0.25;
865         // Limit speed
866         if(m_speed_f.getLength()*dtime > pos_max_d)
867                 m_speed_f *= pos_max_d / (m_speed_f.getLength()*dtime);
868         v3f pos_f = getBasePosition();
869         v3f pos_f_old = pos_f;
870         IGameDef *gamedef = m_env->getGameDef();
871         moveresult = collisionMoveSimple(&m_env->getMap(), gamedef,
872                         pos_max_d, box, dtime, pos_f, m_speed_f);
873         m_touching_ground = moveresult.touching_ground;
874         
875         setBasePosition(pos_f);
876
877         if(send_recommended == false)
878                 return;
879
880         if(pos_f.getDistanceFrom(m_last_sent_position) > 0.05*BS)
881         {
882                 m_last_sent_position = pos_f;
883
884                 std::ostringstream os(std::ios::binary);
885                 // command (0 = update position)
886                 writeU8(os, 0);
887                 // pos
888                 writeV3F1000(os, m_base_position);
889                 // yaw
890                 writeF1000(os, m_yaw);
891                 // create message and add to list
892                 ActiveObjectMessage aom(getId(), false, os.str());
893                 m_messages_out.push_back(aom);
894         }
895 }
896
897 std::string FireflySAO::getClientInitializationData()
898 {
899         std::ostringstream os(std::ios::binary);
900         // version
901         writeU8(os, 0);
902         // pos
903         writeV3F1000(os, m_base_position);
904         return os.str();
905 }
906
907 std::string FireflySAO::getStaticData()
908 {
909         //infostream<<__FUNCTION_NAME<<std::endl;
910         std::ostringstream os(std::ios::binary);
911         // version
912         writeU8(os, 0);
913         return os.str();
914 }
915
916 /*
917         MobV2SAO
918 */
919
920 // Prototype
921 MobV2SAO proto_MobV2SAO(NULL, v3f(0,0,0), NULL);
922
923 MobV2SAO::MobV2SAO(ServerEnvironment *env, v3f pos,
924                 Settings *init_properties):
925         ServerActiveObject(env, pos),
926         m_move_type("ground_nodes"),
927         m_speed(0,0,0),
928         m_last_sent_position(0,0,0),
929         m_oldpos(0,0,0),
930         m_yaw(0),
931         m_counter1(0),
932         m_counter2(0),
933         m_age(0),
934         m_touching_ground(false),
935         m_hp(10),
936         m_walk_around(false),
937         m_walk_around_timer(0),
938         m_next_pos_exists(false),
939         m_shoot_reload_timer(0),
940         m_shooting(false),
941         m_shooting_timer(0),
942         m_falling(false),
943         m_disturb_timer(100000),
944         m_random_disturb_timer(0),
945         m_shoot_y(0)
946 {
947         ServerActiveObject::registerType(getType(), create);
948         
949         m_properties = new Settings();
950         if(init_properties)
951                 m_properties->update(*init_properties);
952         
953         m_properties->setV3F("pos", pos);
954         
955         setPropertyDefaults();
956         readProperties();
957 }
958         
959 MobV2SAO::~MobV2SAO()
960 {
961         delete m_properties;
962 }
963
964 ServerActiveObject* MobV2SAO::create(ServerEnvironment *env, v3f pos,
965                 const std::string &data)
966 {
967         std::istringstream is(data, std::ios::binary);
968         Settings properties;
969         properties.parseConfigLines(is, "MobArgsEnd");
970         MobV2SAO *o = new MobV2SAO(env, pos, &properties);
971         return o;
972 }
973
974 std::string MobV2SAO::getStaticData()
975 {
976         updateProperties();
977
978         std::ostringstream os(std::ios::binary);
979         m_properties->writeLines(os);
980         return os.str();
981 }
982
983 std::string MobV2SAO::getClientInitializationData()
984 {
985         //infostream<<__FUNCTION_NAME<<std::endl;
986
987         updateProperties();
988
989         std::ostringstream os(std::ios::binary);
990
991         // version
992         writeU8(os, 0);
993         
994         Settings client_properties;
995         
996         /*client_properties.set("version", "0");
997         client_properties.updateValue(*m_properties, "pos");
998         client_properties.updateValue(*m_properties, "yaw");
999         client_properties.updateValue(*m_properties, "hp");*/
1000
1001         // Just send everything for simplicity
1002         client_properties.update(*m_properties);
1003
1004         std::ostringstream os2(std::ios::binary);
1005         client_properties.writeLines(os2);
1006         compressZlib(os2.str(), os);
1007
1008         return os.str();
1009 }
1010
1011 bool checkFreePosition(Map *map, v3s16 p0, v3s16 size)
1012 {
1013         for(int dx=0; dx<size.X; dx++)
1014         for(int dy=0; dy<size.Y; dy++)
1015         for(int dz=0; dz<size.Z; dz++){
1016                 v3s16 dp(dx, dy, dz);
1017                 v3s16 p = p0 + dp;
1018                 MapNode n = map->getNodeNoEx(p);
1019                 if(n.getContent() != CONTENT_AIR)
1020                         return false;
1021         }
1022         return true;
1023 }
1024
1025 bool checkWalkablePosition(Map *map, v3s16 p0)
1026 {
1027         v3s16 p = p0 + v3s16(0,-1,0);
1028         MapNode n = map->getNodeNoEx(p);
1029         if(n.getContent() != CONTENT_AIR)
1030                 return true;
1031         return false;
1032 }
1033
1034 bool checkFreeAndWalkablePosition(Map *map, v3s16 p0, v3s16 size)
1035 {
1036         if(!checkFreePosition(map, p0, size))
1037                 return false;
1038         if(!checkWalkablePosition(map, p0))
1039                 return false;
1040         return true;
1041 }
1042
1043 static void get_random_u32_array(u32 a[], u32 len)
1044 {
1045         u32 i, n;
1046         for(i=0; i<len; i++)
1047                 a[i] = i;
1048         n = len;
1049         while(n > 1){
1050                 u32 k = myrand() % n;
1051                 n--;
1052                 u32 temp = a[n];
1053                 a[n] = a[k];
1054                 a[k] = temp;
1055         }
1056 }
1057
1058 #define PP(x) "("<<(x).X<<","<<(x).Y<<","<<(x).Z<<")"
1059
1060 static void explodeSquare(Map *map, v3s16 p0, v3s16 size)
1061 {
1062         core::map<v3s16, MapBlock*> modified_blocks;
1063
1064         for(int dx=0; dx<size.X; dx++)
1065         for(int dy=0; dy<size.Y; dy++)
1066         for(int dz=0; dz<size.Z; dz++){
1067                 v3s16 dp(dx - size.X/2, dy - size.Y/2, dz - size.Z/2);
1068                 v3s16 p = p0 + dp;
1069                 MapNode n = map->getNodeNoEx(p);
1070                 if(n.getContent() == CONTENT_IGNORE)
1071                         continue;
1072                 //map->removeNodeWithEvent(p);
1073                 map->removeNodeAndUpdate(p, modified_blocks);
1074         }
1075
1076         // Send a MEET_OTHER event
1077         MapEditEvent event;
1078         event.type = MEET_OTHER;
1079         for(core::map<v3s16, MapBlock*>::Iterator
1080                   i = modified_blocks.getIterator();
1081                   i.atEnd() == false; i++)
1082         {
1083                 v3s16 p = i.getNode()->getKey();
1084                 event.modified_blocks.insert(p, true);
1085         }
1086         map->dispatchEvent(&event);
1087 }
1088
1089 void MobV2SAO::step(float dtime, bool send_recommended)
1090 {
1091         ScopeProfiler sp2(g_profiler, "MobV2SAO::step avg", SPT_AVG);
1092
1093         assert(m_env);
1094         Map *map = &m_env->getMap();
1095
1096         m_age += dtime;
1097
1098         if(m_die_age >= 0.0 && m_age >= m_die_age){
1099                 m_removed = true;
1100                 return;
1101         }
1102
1103         m_random_disturb_timer += dtime;
1104         if(m_random_disturb_timer >= 5.0)
1105         {
1106                 m_random_disturb_timer = 0;
1107                 // Check connected players
1108                 core::list<Player*> players = m_env->getPlayers(true);
1109                 core::list<Player*>::Iterator i;
1110                 for(i = players.begin();
1111                                 i != players.end(); i++)
1112                 {
1113                         Player *player = *i;
1114                         v3f playerpos = player->getPosition();
1115                         f32 dist = m_base_position.getDistanceFrom(playerpos);
1116                         if(dist < BS*16)
1117                         {
1118                                 if(myrand_range(0,3) == 0){
1119                                         actionstream<<"Mob id="<<m_id<<" at "
1120                                                         <<PP(m_base_position/BS)
1121                                                         <<" got randomly disturbed by "
1122                                                         <<player->getName()<<std::endl;
1123                                         m_disturbing_player = player->getName();
1124                                         m_disturb_timer = 0;
1125                                         break;
1126                                 }
1127                         }
1128                 }
1129         }
1130
1131         Player *disturbing_player =
1132                         m_env->getPlayer(m_disturbing_player.c_str());
1133         v3f disturbing_player_off = v3f(0,1,0);
1134         v3f disturbing_player_norm = v3f(0,1,0);
1135         float disturbing_player_distance = 1000000;
1136         float disturbing_player_dir = 0;
1137         if(disturbing_player){
1138                 disturbing_player_off =
1139                                 disturbing_player->getPosition() - m_base_position;
1140                 disturbing_player_distance = disturbing_player_off.getLength();
1141                 disturbing_player_norm = disturbing_player_off;
1142                 disturbing_player_norm.normalize();
1143                 disturbing_player_dir = 180./PI*atan2(disturbing_player_norm.Z,
1144                                 disturbing_player_norm.X);
1145         }
1146
1147         m_disturb_timer += dtime;
1148         
1149         if(!m_falling)
1150         {
1151                 m_shooting_timer -= dtime;
1152                 if(m_shooting_timer <= 0.0 && m_shooting){
1153                         m_shooting = false;
1154                         
1155                         std::string shoot_type = m_properties->get("shoot_type");
1156                         v3f shoot_pos(0,0,0);
1157                         shoot_pos.Y += m_properties->getFloat("shoot_y") * BS;
1158                         if(shoot_type == "fireball"){
1159                                 v3f dir(cos(m_yaw/180*PI),0,sin(m_yaw/180*PI));
1160                                 dir.Y = m_shoot_y;
1161                                 dir.normalize();
1162                                 v3f speed = dir * BS * 10.0;
1163                                 v3f pos = m_base_position + shoot_pos;
1164                                 infostream<<__FUNCTION_NAME<<": Mob id="<<m_id
1165                                                 <<" shooting fireball from "<<PP(pos)
1166                                                 <<" at speed "<<PP(speed)<<std::endl;
1167                                 Settings properties;
1168                                 properties.set("looks", "fireball");
1169                                 properties.setV3F("speed", speed);
1170                                 properties.setFloat("die_age", 5.0);
1171                                 properties.set("move_type", "constant_speed");
1172                                 properties.setFloat("hp", 1000);
1173                                 properties.set("lock_full_brightness", "true");
1174                                 properties.set("player_hit_damage", "9");
1175                                 properties.set("player_hit_distance", "2");
1176                                 properties.set("player_hit_interval", "1");
1177                                 ServerActiveObject *obj = new MobV2SAO(m_env,
1178                                                 pos, &properties);
1179                                 //m_env->addActiveObjectAsStatic(obj);
1180                                 m_env->addActiveObject(obj);
1181                         } else {
1182                                 infostream<<__FUNCTION_NAME<<": Mob id="<<m_id
1183                                                 <<": Unknown shoot_type="<<shoot_type
1184                                                 <<std::endl;
1185                         }
1186                 }
1187
1188                 m_shoot_reload_timer += dtime;
1189
1190                 float reload_time = 15.0;
1191                 if(m_disturb_timer <= 15.0)
1192                         reload_time = 3.0;
1193
1194                 bool shoot_without_player = false;
1195                 if(m_properties->getBool("mindless_rage"))
1196                         shoot_without_player = true;
1197
1198                 if(!m_shooting && m_shoot_reload_timer >= reload_time &&
1199                                 !m_next_pos_exists &&
1200                                 (m_disturb_timer <= 60.0 || shoot_without_player))
1201                 {
1202                         m_shoot_y = 0;
1203                         if(m_disturb_timer < 60.0 && disturbing_player &&
1204                                         disturbing_player_distance < 16*BS &&
1205                                         fabs(disturbing_player_norm.Y) < 0.8){
1206                                 m_yaw = disturbing_player_dir;
1207                                 sendPosition();
1208                                 m_shoot_y += disturbing_player_norm.Y;
1209                         } else {
1210                                 m_shoot_y = 0.01 * myrand_range(-30,10);
1211                         }
1212                         m_shoot_reload_timer = 0.0;
1213                         m_shooting = true;
1214                         m_shooting_timer = 1.5;
1215                         {
1216                                 std::ostringstream os(std::ios::binary);
1217                                 // command (2 = shooting)
1218                                 writeU8(os, 2);
1219                                 // time
1220                                 writeF1000(os, m_shooting_timer + 0.1);
1221                                 // bright?
1222                                 writeU8(os, true);
1223                                 // create message and add to list
1224                                 ActiveObjectMessage aom(getId(), false, os.str());
1225                                 m_messages_out.push_back(aom);
1226                         }
1227                 }
1228         }
1229         
1230         if(m_move_type == "ground_nodes")
1231         {
1232                 if(!m_shooting){
1233                         m_walk_around_timer -= dtime;
1234                         if(m_walk_around_timer <= 0.0){
1235                                 m_walk_around = !m_walk_around;
1236                                 if(m_walk_around)
1237                                         m_walk_around_timer = 0.1*myrand_range(10,50);
1238                                 else
1239                                         m_walk_around_timer = 0.1*myrand_range(30,70);
1240                         }
1241                 }
1242
1243                 /* Move */
1244                 if(m_next_pos_exists){
1245                         v3f pos_f = m_base_position;
1246                         v3f next_pos_f = intToFloat(m_next_pos_i, BS);
1247
1248                         v3f v = next_pos_f - pos_f;
1249                         m_yaw = atan2(v.Z, v.X) / PI * 180;
1250                         
1251                         v3f diff = next_pos_f - pos_f;
1252                         v3f dir = diff;
1253                         dir.normalize();
1254                         float speed = BS * 0.5;
1255                         if(m_falling)
1256                                 speed = BS * 3.0;
1257                         dir *= dtime * speed;
1258                         bool arrived = false;
1259                         if(dir.getLength() > diff.getLength()){
1260                                 dir = diff;
1261                                 arrived = true;
1262                         }
1263                         pos_f += dir;
1264                         m_base_position = pos_f;
1265
1266                         if((pos_f - next_pos_f).getLength() < 0.1 || arrived){
1267                                 m_next_pos_exists = false;
1268                         }
1269                 }
1270
1271                 v3s16 pos_i = floatToInt(m_base_position, BS);
1272                 v3s16 size_blocks = v3s16(m_size.X+0.5,m_size.Y+0.5,m_size.X+0.5);
1273                 v3s16 pos_size_off(0,0,0);
1274                 if(m_size.X >= 2.5){
1275                         pos_size_off.X = -1;
1276                         pos_size_off.Y = -1;
1277                 }
1278                 
1279                 if(!m_next_pos_exists){
1280                         /* Check whether to drop down */
1281                         if(checkFreePosition(map,
1282                                         pos_i + pos_size_off + v3s16(0,-1,0), size_blocks)){
1283                                 m_next_pos_i = pos_i + v3s16(0,-1,0);
1284                                 m_next_pos_exists = true;
1285                                 m_falling = true;
1286                         } else {
1287                                 m_falling = false;
1288                         }
1289                 }
1290
1291                 if(m_walk_around)
1292                 {
1293                         if(!m_next_pos_exists){
1294                                 /* Find some position where to go next */
1295                                 v3s16 dps[3*3*3];
1296                                 int num_dps = 0;
1297                                 for(int dx=-1; dx<=1; dx++)
1298                                 for(int dy=-1; dy<=1; dy++)
1299                                 for(int dz=-1; dz<=1; dz++){
1300                                         if(dx == 0 && dy == 0)
1301                                                 continue;
1302                                         if(dx != 0 && dz != 0 && dy != 0)
1303                                                 continue;
1304                                         dps[num_dps++] = v3s16(dx,dy,dz);
1305                                 }
1306                                 u32 order[3*3*3];
1307                                 get_random_u32_array(order, num_dps);
1308                                 for(int i=0; i<num_dps; i++){
1309                                         v3s16 p = dps[order[i]] + pos_i;
1310                                         bool is_free = checkFreeAndWalkablePosition(map,
1311                                                         p + pos_size_off, size_blocks);
1312                                         if(!is_free)
1313                                                 continue;
1314                                         m_next_pos_i = p;
1315                                         m_next_pos_exists = true;
1316                                         break;
1317                                 }
1318                         }
1319                 }
1320         }
1321         else if(m_move_type == "constant_speed")
1322         {
1323                 m_base_position += m_speed * dtime;
1324                 
1325                 v3s16 pos_i = floatToInt(m_base_position, BS);
1326                 v3s16 size_blocks = v3s16(m_size.X+0.5,m_size.Y+0.5,m_size.X+0.5);
1327                 v3s16 pos_size_off(0,0,0);
1328                 if(m_size.X >= 2.5){
1329                         pos_size_off.X = -1;
1330                         pos_size_off.Y = -1;
1331                 }
1332                 bool free = checkFreePosition(map, pos_i + pos_size_off, size_blocks);
1333                 if(!free){
1334                         explodeSquare(map, pos_i, v3s16(3,3,3));
1335                         m_removed = true;
1336                         return;
1337                 }
1338         }
1339         else
1340         {
1341                 errorstream<<"MobV2SAO::step(): id="<<m_id<<" unknown move_type=\""
1342                                 <<m_move_type<<"\""<<std::endl;
1343         }
1344
1345         if(send_recommended == false)
1346                 return;
1347
1348         if(m_base_position.getDistanceFrom(m_last_sent_position) > 0.05*BS)
1349         {
1350                 sendPosition();
1351         }
1352 }
1353
1354 void MobV2SAO::punch(ServerActiveObject *puncher, float time_from_last_punch)
1355 {
1356         if(!puncher)
1357                 return;
1358         
1359         v3f dir = (getBasePosition() - puncher->getBasePosition()).normalize();
1360
1361         // A quick hack; SAO description is player name for player
1362         std::string playername = puncher->getDescription();
1363
1364         Map *map = &m_env->getMap();
1365         
1366         actionstream<<playername<<" punches mob id="<<m_id
1367                         <<" at "<<PP(m_base_position/BS)<<std::endl;
1368
1369         m_disturb_timer = 0;
1370         m_disturbing_player = playername;
1371         m_next_pos_exists = false; // Cancel moving immediately
1372         
1373         m_yaw = wrapDegrees_180(180./PI*atan2(dir.Z, dir.X) + 180.);
1374         v3f new_base_position = m_base_position + dir * BS;
1375         {
1376                 v3s16 pos_i = floatToInt(new_base_position, BS);
1377                 v3s16 size_blocks = v3s16(m_size.X+0.5,m_size.Y+0.5,m_size.X+0.5);
1378                 v3s16 pos_size_off(0,0,0);
1379                 if(m_size.X >= 2.5){
1380                         pos_size_off.X = -1;
1381                         pos_size_off.Y = -1;
1382                 }
1383                 bool free = checkFreePosition(map, pos_i + pos_size_off, size_blocks);
1384                 if(free)
1385                         m_base_position = new_base_position;
1386         }
1387         sendPosition();
1388         
1389
1390         // "Material" properties of the MobV2
1391         MaterialProperties mp;
1392         mp.diggability = DIGGABLE_NORMAL;
1393         mp.crackiness = -1.0;
1394         mp.cuttability = 1.0;
1395
1396         ToolDiggingProperties tp;
1397         puncher->getWieldDiggingProperties(&tp);
1398
1399         HittingProperties hitprop = getHittingProperties(&mp, &tp,
1400                         time_from_last_punch);
1401
1402         doDamage(hitprop.hp);
1403         puncher->damageWieldedItem(hitprop.wear);
1404 }
1405
1406 bool MobV2SAO::isPeaceful()
1407 {
1408         return m_properties->getBool("is_peaceful");
1409 }
1410
1411 void MobV2SAO::sendPosition()
1412 {
1413         m_last_sent_position = m_base_position;
1414
1415         std::ostringstream os(std::ios::binary);
1416         // command (0 = update position)
1417         writeU8(os, 0);
1418         // pos
1419         writeV3F1000(os, m_base_position);
1420         // yaw
1421         writeF1000(os, m_yaw);
1422         // create message and add to list
1423         ActiveObjectMessage aom(getId(), false, os.str());
1424         m_messages_out.push_back(aom);
1425 }
1426
1427 void MobV2SAO::setPropertyDefaults()
1428 {
1429         m_properties->setDefault("is_peaceful", "false");
1430         m_properties->setDefault("move_type", "ground_nodes");
1431         m_properties->setDefault("speed", "(0,0,0)");
1432         m_properties->setDefault("age", "0");
1433         m_properties->setDefault("yaw", "0");
1434         m_properties->setDefault("pos", "(0,0,0)");
1435         m_properties->setDefault("hp", "0");
1436         m_properties->setDefault("die_age", "-1");
1437         m_properties->setDefault("size", "(1,2)");
1438         m_properties->setDefault("shoot_type", "fireball");
1439         m_properties->setDefault("shoot_y", "0");
1440         m_properties->setDefault("mindless_rage", "false");
1441 }
1442 void MobV2SAO::readProperties()
1443 {
1444         m_move_type = m_properties->get("move_type");
1445         m_speed = m_properties->getV3F("speed");
1446         m_age = m_properties->getFloat("age");
1447         m_yaw = m_properties->getFloat("yaw");
1448         m_base_position = m_properties->getV3F("pos");
1449         m_hp = m_properties->getS32("hp");
1450         m_die_age = m_properties->getFloat("die_age");
1451         m_size = m_properties->getV2F("size");
1452 }
1453 void MobV2SAO::updateProperties()
1454 {
1455         m_properties->set("move_type", m_move_type);
1456         m_properties->setV3F("speed", m_speed);
1457         m_properties->setFloat("age", m_age);
1458         m_properties->setFloat("yaw", m_yaw);
1459         m_properties->setV3F("pos", m_base_position);
1460         m_properties->setS32("hp", m_hp);
1461         m_properties->setFloat("die_age", m_die_age);
1462         m_properties->setV2F("size", m_size);
1463
1464         m_properties->setS32("version", 0);
1465 }
1466
1467 void MobV2SAO::doDamage(u16 d)
1468 {
1469         infostream<<"MobV2 hp="<<m_hp<<" damage="<<d<<std::endl;
1470         
1471         if(d < m_hp)
1472         {
1473                 m_hp -= d;
1474         }
1475         else
1476         {
1477                 actionstream<<"A "<<(isPeaceful()?"peaceful":"non-peaceful")
1478                                 <<" mob id="<<m_id<<" dies at "<<PP(m_base_position)<<std::endl;
1479                 // Die
1480                 m_hp = 0;
1481                 m_removed = true;
1482         }
1483
1484         {
1485                 std::ostringstream os(std::ios::binary);
1486                 // command (1 = damage)
1487                 writeU8(os, 1);
1488                 // amount
1489                 writeU16(os, d);
1490                 // create message and add to list
1491                 ActiveObjectMessage aom(getId(), false, os.str());
1492                 m_messages_out.push_back(aom);
1493         }
1494 }
1495
1496
1497 /*
1498         LuaEntitySAO
1499 */
1500
1501 #include "scriptapi.h"
1502 #include "luaentity_common.h"
1503
1504 // Prototype
1505 LuaEntitySAO proto_LuaEntitySAO(NULL, v3f(0,0,0), "_prototype", "");
1506
1507 LuaEntitySAO::LuaEntitySAO(ServerEnvironment *env, v3f pos,
1508                 const std::string &name, const std::string &state):
1509         ServerActiveObject(env, pos),
1510         m_init_name(name),
1511         m_init_state(state),
1512         m_registered(false),
1513         m_prop(new LuaEntityProperties),
1514         m_velocity(0,0,0),
1515         m_acceleration(0,0,0),
1516         m_yaw(0),
1517         m_last_sent_yaw(0),
1518         m_last_sent_position(0,0,0),
1519         m_last_sent_velocity(0,0,0),
1520         m_last_sent_position_timer(0),
1521         m_last_sent_move_precision(0)
1522 {
1523         // Only register type if no environment supplied
1524         if(env == NULL){
1525                 ServerActiveObject::registerType(getType(), create);
1526                 return;
1527         }
1528 }
1529
1530 LuaEntitySAO::~LuaEntitySAO()
1531 {
1532         if(m_registered){
1533                 lua_State *L = m_env->getLua();
1534                 scriptapi_luaentity_rm(L, m_id);
1535         }
1536         delete m_prop;
1537 }
1538
1539 void LuaEntitySAO::addedToEnvironment()
1540 {
1541         ServerActiveObject::addedToEnvironment();
1542         
1543         // Create entity from name and state
1544         lua_State *L = m_env->getLua();
1545         m_registered = scriptapi_luaentity_add(L, m_id, m_init_name.c_str(),
1546                         m_init_state.c_str());
1547         
1548         if(m_registered){
1549                 // Get properties
1550                 scriptapi_luaentity_get_properties(L, m_id, m_prop);
1551         }
1552 }
1553
1554 ServerActiveObject* LuaEntitySAO::create(ServerEnvironment *env, v3f pos,
1555                 const std::string &data)
1556 {
1557         std::istringstream is(data, std::ios::binary);
1558         // read version
1559         u8 version = readU8(is);
1560         // check if version is supported
1561         if(version != 0)
1562                 return NULL;
1563         // read name
1564         std::string name = deSerializeString(is);
1565         // read state
1566         std::string state = deSerializeLongString(is);
1567         // create object
1568         infostream<<"LuaEntitySAO::create(name=\""<<name<<"\" state=\""
1569                         <<state<<"\")"<<std::endl;
1570         return new LuaEntitySAO(env, pos, name, state);
1571 }
1572
1573 void LuaEntitySAO::step(float dtime, bool send_recommended)
1574 {
1575         m_last_sent_position_timer += dtime;
1576         
1577         if(m_prop->physical){
1578                 core::aabbox3d<f32> box = m_prop->collisionbox;
1579                 box.MinEdge *= BS;
1580                 box.MaxEdge *= BS;
1581                 collisionMoveResult moveresult;
1582                 f32 pos_max_d = BS*0.25; // Distance per iteration
1583                 v3f p_pos = getBasePosition();
1584                 v3f p_velocity = m_velocity;
1585                 IGameDef *gamedef = m_env->getGameDef();
1586                 moveresult = collisionMovePrecise(&m_env->getMap(), gamedef,
1587                                 pos_max_d, box, dtime, p_pos, p_velocity);
1588                 // Apply results
1589                 setBasePosition(p_pos);
1590                 m_velocity = p_velocity;
1591
1592                 m_velocity += dtime * m_acceleration;
1593         } else {
1594                 m_base_position += dtime * m_velocity + 0.5 * dtime
1595                                 * dtime * m_acceleration;
1596                 m_velocity += dtime * m_acceleration;
1597         }
1598
1599         if(m_registered){
1600                 lua_State *L = m_env->getLua();
1601                 scriptapi_luaentity_step(L, m_id, dtime);
1602         }
1603
1604         if(send_recommended == false)
1605                 return;
1606         
1607         // TODO: force send when acceleration changes enough?
1608         float minchange = 0.2*BS;
1609         if(m_last_sent_position_timer > 1.0){
1610                 minchange = 0.01*BS;
1611         } else if(m_last_sent_position_timer > 0.2){
1612                 minchange = 0.05*BS;
1613         }
1614         float move_d = m_base_position.getDistanceFrom(m_last_sent_position);
1615         move_d += m_last_sent_move_precision;
1616         float vel_d = m_velocity.getDistanceFrom(m_last_sent_velocity);
1617         if(move_d > minchange || vel_d > minchange ||
1618                         fabs(m_yaw - m_last_sent_yaw) > 1.0){
1619                 sendPosition(true, false);
1620         }
1621 }
1622
1623 std::string LuaEntitySAO::getClientInitializationData()
1624 {
1625         std::ostringstream os(std::ios::binary);
1626         // version
1627         writeU8(os, 0);
1628         // pos
1629         writeV3F1000(os, m_base_position);
1630         // yaw
1631         writeF1000(os, m_yaw);
1632         // properties
1633         std::ostringstream prop_os(std::ios::binary);
1634         m_prop->serialize(prop_os);
1635         os<<serializeLongString(prop_os.str());
1636         // return result
1637         return os.str();
1638 }
1639
1640 std::string LuaEntitySAO::getStaticData()
1641 {
1642         infostream<<__FUNCTION_NAME<<std::endl;
1643         std::ostringstream os(std::ios::binary);
1644         // version
1645         writeU8(os, 0);
1646         // name
1647         os<<serializeString(m_init_name);
1648         // state
1649         if(m_registered){
1650                 lua_State *L = m_env->getLua();
1651                 std::string state = scriptapi_luaentity_get_staticdata(L, m_id);
1652                 os<<serializeLongString(state);
1653         } else {
1654                 os<<serializeLongString(m_init_state);
1655         }
1656         return os.str();
1657 }
1658
1659 void LuaEntitySAO::punch(ServerActiveObject *puncher, float time_from_last_punch)
1660 {
1661         if(!m_registered){
1662                 // Delete unknown LuaEntities when punched
1663                 m_removed = true;
1664                 return;
1665         }
1666         lua_State *L = m_env->getLua();
1667         scriptapi_luaentity_punch(L, m_id, puncher, time_from_last_punch);
1668 }
1669
1670 void LuaEntitySAO::rightClick(ServerActiveObject *clicker)
1671 {
1672         if(!m_registered)
1673                 return;
1674         lua_State *L = m_env->getLua();
1675         scriptapi_luaentity_rightclick(L, m_id, clicker);
1676 }
1677
1678 void LuaEntitySAO::setPos(v3f pos)
1679 {
1680         m_base_position = pos;
1681         sendPosition(false, true);
1682 }
1683
1684 void LuaEntitySAO::moveTo(v3f pos, bool continuous)
1685 {
1686         m_base_position = pos;
1687         if(!continuous)
1688                 sendPosition(true, true);
1689 }
1690
1691 float LuaEntitySAO::getMinimumSavedMovement()
1692 {
1693         return 0.1 * BS;
1694 }
1695
1696 void LuaEntitySAO::setVelocity(v3f velocity)
1697 {
1698         m_velocity = velocity;
1699 }
1700
1701 void LuaEntitySAO::setAcceleration(v3f acceleration)
1702 {
1703         m_acceleration = acceleration;
1704 }
1705
1706 v3f LuaEntitySAO::getAcceleration()
1707 {
1708         return m_acceleration;
1709 }
1710
1711 void LuaEntitySAO::setTextureMod(const std::string &mod)
1712 {
1713         std::ostringstream os(std::ios::binary);
1714         // command (1 = set texture modification)
1715         writeU8(os, 1);
1716         // parameters
1717         os<<serializeString(mod);
1718         // create message and add to list
1719         ActiveObjectMessage aom(getId(), false, os.str());
1720         m_messages_out.push_back(aom);
1721 }
1722
1723 void LuaEntitySAO::setSprite(v2s16 p, int num_frames, float framelength,
1724                 bool select_horiz_by_yawpitch)
1725 {
1726         std::ostringstream os(std::ios::binary);
1727         // command (2 = set sprite)
1728         writeU8(os, 2);
1729         // parameters
1730         writeV2S16(os, p);
1731         writeU16(os, num_frames);
1732         writeF1000(os, framelength);
1733         writeU8(os, select_horiz_by_yawpitch);
1734         // create message and add to list
1735         ActiveObjectMessage aom(getId(), false, os.str());
1736         m_messages_out.push_back(aom);
1737 }
1738
1739 void LuaEntitySAO::sendPosition(bool do_interpolate, bool is_movement_end)
1740 {
1741         m_last_sent_move_precision = m_base_position.getDistanceFrom(
1742                         m_last_sent_position);
1743         m_last_sent_position_timer = 0;
1744         m_last_sent_yaw = m_yaw;
1745         m_last_sent_position = m_base_position;
1746         m_last_sent_velocity = m_velocity;
1747         //m_last_sent_acceleration = m_acceleration;
1748
1749         float update_interval = m_env->getSendRecommendedInterval();
1750
1751         std::ostringstream os(std::ios::binary);
1752         // command (0 = update position)
1753         writeU8(os, 0);
1754
1755         // do_interpolate
1756         writeU8(os, do_interpolate);
1757         // pos
1758         writeV3F1000(os, m_base_position);
1759         // velocity
1760         writeV3F1000(os, m_velocity);
1761         // acceleration
1762         writeV3F1000(os, m_acceleration);
1763         // yaw
1764         writeF1000(os, m_yaw);
1765         // is_end_position (for interpolation)
1766         writeU8(os, is_movement_end);
1767         // update_interval (for interpolation)
1768         writeF1000(os, update_interval);
1769
1770         // create message and add to list
1771         ActiveObjectMessage aom(getId(), false, os.str());
1772         m_messages_out.push_back(aom);
1773 }
1774