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