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