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