Fix and tune stars
[oweals/minetest.git] / src / content_sao.cpp
1 /*
2 Minetest-c55
3 Copyright (C) 2010-2011 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "content_sao.h"
21 #include "collision.h"
22 #include "environment.h"
23 #include "settings.h"
24 #include "main.h" // For g_profiler
25 #include "profiler.h"
26 #include "serialization.h" // For compressZlib
27 #include "tool.h" // For ToolCapabilities
28 #include "gamedef.h"
29
30 core::map<u16, ServerActiveObject::Factory> ServerActiveObject::m_types;
31
32 /*
33         DummyLoadSAO
34 */
35
36 class DummyLoadSAO : public ServerActiveObject
37 {
38 public:
39         DummyLoadSAO(ServerEnvironment *env, v3f pos, u8 type):
40                 ServerActiveObject(env, pos)
41         {
42                 ServerActiveObject::registerType(type, create);
43         }
44         // Pretend to be the test object (to fool the client)
45         u8 getType() const
46         { return ACTIVEOBJECT_TYPE_TEST; }
47         // And never save to disk
48         bool isStaticAllowed() const
49         { return false; }
50         
51         static ServerActiveObject* create(ServerEnvironment *env, v3f pos,
52                         const std::string &data)
53         {
54                 return new DummyLoadSAO(env, pos, 0);
55         }
56
57         void step(float dtime, bool send_recommended)
58         {
59                 m_removed = true;
60                 infostream<<"DummyLoadSAO step"<<std::endl;
61         }
62
63 private:
64 };
65
66 // Prototype (registers item for deserialization)
67 DummyLoadSAO proto1_DummyLoadSAO(NULL, v3f(0,0,0), ACTIVEOBJECT_TYPE_RAT);
68 DummyLoadSAO proto2_DummyLoadSAO(NULL, v3f(0,0,0), ACTIVEOBJECT_TYPE_OERKKI1);
69 DummyLoadSAO proto3_DummyLoadSAO(NULL, v3f(0,0,0), ACTIVEOBJECT_TYPE_FIREFLY);
70 DummyLoadSAO proto4_DummyLoadSAO(NULL, v3f(0,0,0), ACTIVEOBJECT_TYPE_MOBV2);
71
72 /*
73         TestSAO
74 */
75
76 class TestSAO : public ServerActiveObject
77 {
78 public:
79         TestSAO(ServerEnvironment *env, v3f pos):
80                 ServerActiveObject(env, pos),
81                 m_timer1(0),
82                 m_age(0)
83         {
84                 ServerActiveObject::registerType(getType(), create);
85         }
86         u8 getType() const
87         { return ACTIVEOBJECT_TYPE_TEST; }
88         
89         static ServerActiveObject* create(ServerEnvironment *env, v3f pos,
90                         const std::string &data)
91         {
92                 return new TestSAO(env, pos);
93         }
94
95         void step(float dtime, bool send_recommended)
96         {
97                 m_age += dtime;
98                 if(m_age > 10)
99                 {
100                         m_removed = true;
101                         return;
102                 }
103
104                 m_base_position.Y += dtime * BS * 2;
105                 if(m_base_position.Y > 8*BS)
106                         m_base_position.Y = 2*BS;
107
108                 if(send_recommended == false)
109                         return;
110
111                 m_timer1 -= dtime;
112                 if(m_timer1 < 0.0)
113                 {
114                         m_timer1 += 0.125;
115
116                         std::string data;
117
118                         data += itos(0); // 0 = position
119                         data += " ";
120                         data += itos(m_base_position.X);
121                         data += " ";
122                         data += itos(m_base_position.Y);
123                         data += " ";
124                         data += itos(m_base_position.Z);
125
126                         ActiveObjectMessage aom(getId(), false, data);
127                         m_messages_out.push_back(aom);
128                 }
129         }
130
131 private:
132         float m_timer1;
133         float m_age;
134 };
135
136 // Prototype (registers item for deserialization)
137 TestSAO proto_TestSAO(NULL, v3f(0,0,0));
138
139 /*
140         ItemSAO
141 */
142
143 class ItemSAO : public ServerActiveObject
144 {
145 public:
146         u8 getType() const
147         { return ACTIVEOBJECT_TYPE_ITEM; }
148         
149         float getMinimumSavedMovement()
150         { return 0.1*BS; }
151
152         static ServerActiveObject* create(ServerEnvironment *env, v3f pos,
153                         const std::string &data)
154         {
155                 std::istringstream is(data, std::ios::binary);
156                 char buf[1];
157                 // read version
158                 is.read(buf, 1);
159                 u8 version = buf[0];
160                 // check if version is supported
161                 if(version != 0)
162                         return NULL;
163                 std::string itemstring = deSerializeString(is);
164                 infostream<<"create(): Creating item \""
165                                 <<itemstring<<"\""<<std::endl;
166                 return new ItemSAO(env, pos, itemstring);
167         }
168
169         ItemSAO(ServerEnvironment *env, v3f pos,
170                         const std::string itemstring):
171                 ServerActiveObject(env, pos),
172                 m_itemstring(itemstring),
173                 m_itemstring_changed(false),
174                 m_speed_f(0,0,0),
175                 m_last_sent_position(0,0,0)
176         {
177                 ServerActiveObject::registerType(getType(), create);
178         }
179
180         void step(float dtime, bool send_recommended)
181         {
182                 ScopeProfiler sp2(g_profiler, "step avg", SPT_AVG);
183
184                 assert(m_env);
185
186                 const float interval = 0.2;
187                 if(m_move_interval.step(dtime, interval)==false)
188                         return;
189                 dtime = interval;
190                 
191                 core::aabbox3d<f32> box(-BS/3.,0.0,-BS/3., BS/3.,BS*2./3.,BS/3.);
192                 collisionMoveResult moveresult;
193                 // Apply gravity
194                 m_speed_f += v3f(0, -dtime*9.81*BS, 0);
195                 // Maximum movement without glitches
196                 f32 pos_max_d = BS*0.25;
197                 // Limit speed
198                 if(m_speed_f.getLength()*dtime > pos_max_d)
199                         m_speed_f *= pos_max_d / (m_speed_f.getLength()*dtime);
200                 v3f pos_f = getBasePosition();
201                 v3f pos_f_old = pos_f;
202                 IGameDef *gamedef = m_env->getGameDef();
203                 moveresult = collisionMoveSimple(&m_env->getMap(), gamedef,
204                                 pos_max_d, box, dtime, pos_f, m_speed_f);
205                 
206                 if(send_recommended == false)
207                         return;
208
209                 if(pos_f.getDistanceFrom(m_last_sent_position) > 0.05*BS)
210                 {
211                         setBasePosition(pos_f);
212                         m_last_sent_position = pos_f;
213
214                         std::ostringstream os(std::ios::binary);
215                         // command (0 = update position)
216                         writeU8(os, 0);
217                         // pos
218                         writeV3F1000(os, m_base_position);
219                         // create message and add to list
220                         ActiveObjectMessage aom(getId(), false, os.str());
221                         m_messages_out.push_back(aom);
222                 }
223                 if(m_itemstring_changed)
224                 {
225                         m_itemstring_changed = false;
226
227                         std::ostringstream os(std::ios::binary);
228                         // command (1 = update itemstring)
229                         writeU8(os, 1);
230                         // itemstring
231                         os<<serializeString(m_itemstring);
232                         // create message and add to list
233                         ActiveObjectMessage aom(getId(), false, os.str());
234                         m_messages_out.push_back(aom);
235                 }
236         }
237
238         std::string getClientInitializationData()
239         {
240                 std::ostringstream os(std::ios::binary);
241                 // version
242                 writeU8(os, 0);
243                 // pos
244                 writeV3F1000(os, m_base_position);
245                 // itemstring
246                 os<<serializeString(m_itemstring);
247                 return os.str();
248         }
249
250         std::string getStaticData()
251         {
252                 infostream<<__FUNCTION_NAME<<std::endl;
253                 std::ostringstream os(std::ios::binary);
254                 // version
255                 writeU8(os, 0);
256                 // itemstring
257                 os<<serializeString(m_itemstring);
258                 return os.str();
259         }
260
261         ItemStack createItemStack()
262         {
263                 try{
264                         IItemDefManager *idef = m_env->getGameDef()->idef();
265                         ItemStack item;
266                         item.deSerialize(m_itemstring, idef);
267                         infostream<<__FUNCTION_NAME<<": m_itemstring=\""<<m_itemstring
268                                         <<"\" -> item=\""<<item.getItemString()<<"\""
269                                         <<std::endl;
270                         return item;
271                 }
272                 catch(SerializationError &e)
273                 {
274                         infostream<<__FUNCTION_NAME<<": serialization error: "
275                                         <<"m_itemstring=\""<<m_itemstring<<"\""<<std::endl;
276                         return ItemStack();
277                 }
278         }
279
280         int punch(v3f dir,
281                         const ToolCapabilities *toolcap,
282                         ServerActiveObject *puncher,
283                         float time_from_last_punch)
284         {
285                 // Directly delete item in creative mode
286                 if(g_settings->getBool("creative_mode") == true)
287                 {
288                         m_removed = true;
289                         return 0;
290                 }
291                 
292                 // Take item into inventory
293                 ItemStack item = createItemStack();
294                 Inventory *inv = puncher->getInventory();
295                 if(inv != NULL)
296                 {
297                         std::string wieldlist = puncher->getWieldList();
298                         ItemStack leftover = inv->addItem(wieldlist, item);
299                         puncher->setInventoryModified();
300                         if(leftover.empty())
301                         {
302                                 m_removed = true;
303                         }
304                         else
305                         {
306                                 m_itemstring = leftover.getItemString();
307                                 m_itemstring_changed = true;
308                         }
309                 }
310                 
311                 return 0;
312         }
313
314
315 private:
316         std::string m_itemstring;
317         bool m_itemstring_changed;
318         v3f m_speed_f;
319         v3f m_last_sent_position;
320         IntervalLimiter m_move_interval;
321 };
322
323 // Prototype (registers item for deserialization)
324 ItemSAO proto_ItemSAO(NULL, v3f(0,0,0), "");
325
326 ServerActiveObject* createItemSAO(ServerEnvironment *env, v3f pos,
327                 const std::string itemstring)
328 {
329         return new ItemSAO(env, pos, itemstring);
330 }
331
332 /*
333         LuaEntitySAO
334 */
335
336 #include "scriptapi.h"
337 #include "luaentity_common.h"
338
339 // Prototype (registers item for deserialization)
340 LuaEntitySAO proto_LuaEntitySAO(NULL, v3f(0,0,0), "_prototype", "");
341
342 LuaEntitySAO::LuaEntitySAO(ServerEnvironment *env, v3f pos,
343                 const std::string &name, const std::string &state):
344         ServerActiveObject(env, pos),
345         m_init_name(name),
346         m_init_state(state),
347         m_registered(false),
348         m_prop(new LuaEntityProperties),
349         m_hp(-1),
350         m_velocity(0,0,0),
351         m_acceleration(0,0,0),
352         m_yaw(0),
353         m_last_sent_yaw(0),
354         m_last_sent_position(0,0,0),
355         m_last_sent_velocity(0,0,0),
356         m_last_sent_position_timer(0),
357         m_last_sent_move_precision(0),
358         m_armor_groups_sent(false)
359 {
360         // Only register type if no environment supplied
361         if(env == NULL){
362                 ServerActiveObject::registerType(getType(), create);
363                 return;
364         }
365         
366         // Initialize something to armor groups
367         m_armor_groups["fleshy"] = 3;
368         m_armor_groups["snappy"] = 2;
369 }
370
371 LuaEntitySAO::~LuaEntitySAO()
372 {
373         if(m_registered){
374                 lua_State *L = m_env->getLua();
375                 scriptapi_luaentity_rm(L, m_id);
376         }
377         delete m_prop;
378 }
379
380 void LuaEntitySAO::addedToEnvironment()
381 {
382         ServerActiveObject::addedToEnvironment();
383         
384         // Create entity from name
385         lua_State *L = m_env->getLua();
386         m_registered = scriptapi_luaentity_add(L, m_id, m_init_name.c_str());
387         
388         if(m_registered){
389                 // Get properties
390                 scriptapi_luaentity_get_properties(L, m_id, m_prop);
391                 // Initialize HP from properties
392                 m_hp = m_prop->hp_max;
393         }
394         
395         // Activate entity, supplying serialized state
396         scriptapi_luaentity_activate(L, m_id, m_init_state.c_str());
397 }
398
399 ServerActiveObject* LuaEntitySAO::create(ServerEnvironment *env, v3f pos,
400                 const std::string &data)
401 {
402         std::string name;
403         std::string state;
404         s16 hp = 1;
405         v3f velocity;
406         float yaw = 0;
407         if(data != ""){
408                 std::istringstream is(data, std::ios::binary);
409                 // read version
410                 u8 version = readU8(is);
411                 // check if version is supported
412                 if(version == 0){
413                         name = deSerializeString(is);
414                         state = deSerializeLongString(is);
415                 }
416                 else if(version == 1){
417                         name = deSerializeString(is);
418                         state = deSerializeLongString(is);
419                         hp = readS16(is);
420                         velocity = readV3F1000(is);
421                         yaw = readF1000(is);
422                 }
423         }
424         // create object
425         infostream<<"LuaEntitySAO::create(name=\""<<name<<"\" state=\""
426                         <<state<<"\")"<<std::endl;
427         LuaEntitySAO *sao = new LuaEntitySAO(env, pos, name, state);
428         sao->m_hp = hp;
429         sao->m_velocity = velocity;
430         sao->m_yaw = yaw;
431         return sao;
432 }
433
434 void LuaEntitySAO::step(float dtime, bool send_recommended)
435 {
436         m_last_sent_position_timer += dtime;
437         
438         if(m_prop->physical){
439                 core::aabbox3d<f32> box = m_prop->collisionbox;
440                 box.MinEdge *= BS;
441                 box.MaxEdge *= BS;
442                 collisionMoveResult moveresult;
443                 f32 pos_max_d = BS*0.25; // Distance per iteration
444                 v3f p_pos = getBasePosition();
445                 v3f p_velocity = m_velocity;
446                 IGameDef *gamedef = m_env->getGameDef();
447                 moveresult = collisionMovePrecise(&m_env->getMap(), gamedef,
448                                 pos_max_d, box, dtime, p_pos, p_velocity);
449                 // Apply results
450                 setBasePosition(p_pos);
451                 m_velocity = p_velocity;
452
453                 m_velocity += dtime * m_acceleration;
454         } else {
455                 m_base_position += dtime * m_velocity + 0.5 * dtime
456                                 * dtime * m_acceleration;
457                 m_velocity += dtime * m_acceleration;
458         }
459
460         if(m_registered){
461                 lua_State *L = m_env->getLua();
462                 scriptapi_luaentity_step(L, m_id, dtime);
463         }
464
465         if(send_recommended == false)
466                 return;
467         
468         // TODO: force send when acceleration changes enough?
469         float minchange = 0.2*BS;
470         if(m_last_sent_position_timer > 1.0){
471                 minchange = 0.01*BS;
472         } else if(m_last_sent_position_timer > 0.2){
473                 minchange = 0.05*BS;
474         }
475         float move_d = m_base_position.getDistanceFrom(m_last_sent_position);
476         move_d += m_last_sent_move_precision;
477         float vel_d = m_velocity.getDistanceFrom(m_last_sent_velocity);
478         if(move_d > minchange || vel_d > minchange ||
479                         fabs(m_yaw - m_last_sent_yaw) > 1.0){
480                 sendPosition(true, false);
481         }
482
483         if(m_armor_groups_sent == false){
484                 m_armor_groups_sent = true;
485                 std::ostringstream os(std::ios::binary);
486                 writeU8(os, LUAENTITY_CMD_UPDATE_ARMOR_GROUPS);
487                 writeU16(os, m_armor_groups.size());
488                 for(ItemGroupList::const_iterator i = m_armor_groups.begin();
489                                 i != m_armor_groups.end(); i++){
490                         os<<serializeString(i->first);
491                         writeS16(os, i->second);
492                 }
493                 // create message and add to list
494                 ActiveObjectMessage aom(getId(), true, os.str());
495                 m_messages_out.push_back(aom);
496         }
497 }
498
499 std::string LuaEntitySAO::getClientInitializationData()
500 {
501         std::ostringstream os(std::ios::binary);
502         // version
503         writeU8(os, 1);
504         // pos
505         writeV3F1000(os, m_base_position);
506         // yaw
507         writeF1000(os, m_yaw);
508         // hp
509         writeS16(os, m_hp);
510         // properties
511         std::ostringstream prop_os(std::ios::binary);
512         m_prop->serialize(prop_os);
513         os<<serializeLongString(prop_os.str());
514         // return result
515         return os.str();
516 }
517
518 std::string LuaEntitySAO::getStaticData()
519 {
520         verbosestream<<__FUNCTION_NAME<<std::endl;
521         std::ostringstream os(std::ios::binary);
522         // version
523         writeU8(os, 1);
524         // name
525         os<<serializeString(m_init_name);
526         // state
527         if(m_registered){
528                 lua_State *L = m_env->getLua();
529                 std::string state = scriptapi_luaentity_get_staticdata(L, m_id);
530                 os<<serializeLongString(state);
531         } else {
532                 os<<serializeLongString(m_init_state);
533         }
534         // hp
535         writeS16(os, m_hp);
536         // velocity
537         writeV3F1000(os, m_velocity);
538         // yaw
539         writeF1000(os, m_yaw);
540         return os.str();
541 }
542
543 int LuaEntitySAO::punch(v3f dir,
544                 const ToolCapabilities *toolcap,
545                 ServerActiveObject *puncher,
546                 float time_from_last_punch)
547 {
548         if(!m_registered){
549                 // Delete unknown LuaEntities when punched
550                 m_removed = true;
551                 return 0;
552         }
553         
554         ItemStack *punchitem = NULL;
555         ItemStack punchitem_static;
556         if(puncher){
557                 punchitem_static = puncher->getWieldedItem();
558                 punchitem = &punchitem_static;
559         }
560
561         PunchDamageResult result = getPunchDamage(
562                         m_armor_groups,
563                         toolcap,
564                         punchitem,
565                         time_from_last_punch);
566         
567         if(result.did_punch)
568         {
569                 setHP(getHP() - result.damage);
570                 
571                 actionstream<<getDescription()<<" punched by "
572                                 <<puncher->getDescription()<<", damage "<<result.damage
573                                 <<" hp, health now "<<getHP()<<" hp"<<std::endl;
574                 
575                 {
576                         std::ostringstream os(std::ios::binary);
577                         // command 
578                         writeU8(os, LUAENTITY_CMD_PUNCHED);
579                         // damage
580                         writeS16(os, result.damage);
581                         // result_hp
582                         writeS16(os, getHP());
583                         // create message and add to list
584                         ActiveObjectMessage aom(getId(), true, os.str());
585                         m_messages_out.push_back(aom);
586                 }
587
588                 if(getHP() == 0)
589                         m_removed = true;
590         }
591
592         lua_State *L = m_env->getLua();
593         scriptapi_luaentity_punch(L, m_id, puncher,
594                         time_from_last_punch, toolcap, dir);
595
596         return result.wear;
597 }
598
599 void LuaEntitySAO::rightClick(ServerActiveObject *clicker)
600 {
601         if(!m_registered)
602                 return;
603         lua_State *L = m_env->getLua();
604         scriptapi_luaentity_rightclick(L, m_id, clicker);
605 }
606
607 void LuaEntitySAO::setHP(s16 hp)
608 {
609         if(hp < 0) hp = 0;
610         m_hp = hp;
611 }
612
613 s16 LuaEntitySAO::getHP()
614 {
615         return m_hp;
616 }
617
618 void LuaEntitySAO::setPos(v3f pos)
619 {
620         m_base_position = pos;
621         sendPosition(false, true);
622 }
623
624 void LuaEntitySAO::moveTo(v3f pos, bool continuous)
625 {
626         m_base_position = pos;
627         if(!continuous)
628                 sendPosition(true, true);
629 }
630
631 float LuaEntitySAO::getMinimumSavedMovement()
632 {
633         return 0.1 * BS;
634 }
635
636 std::string LuaEntitySAO::getDescription()
637 {
638         std::ostringstream os(std::ios::binary);
639         os<<"LuaEntitySAO at (";
640         os<<(m_base_position.X/BS)<<",";
641         os<<(m_base_position.Y/BS)<<",";
642         os<<(m_base_position.Z/BS);
643         os<<")";
644         return os.str();
645 }
646
647 void LuaEntitySAO::setVelocity(v3f velocity)
648 {
649         m_velocity = velocity;
650 }
651
652 v3f LuaEntitySAO::getVelocity()
653 {
654         return m_velocity;
655 }
656
657 void LuaEntitySAO::setAcceleration(v3f acceleration)
658 {
659         m_acceleration = acceleration;
660 }
661
662 v3f LuaEntitySAO::getAcceleration()
663 {
664         return m_acceleration;
665 }
666
667 void LuaEntitySAO::setYaw(float yaw)
668 {
669         m_yaw = yaw;
670 }
671
672 float LuaEntitySAO::getYaw()
673 {
674         return m_yaw;
675 }
676
677 void LuaEntitySAO::setTextureMod(const std::string &mod)
678 {
679         std::ostringstream os(std::ios::binary);
680         // command 
681         writeU8(os, LUAENTITY_CMD_SET_TEXTURE_MOD);
682         // parameters
683         os<<serializeString(mod);
684         // create message and add to list
685         ActiveObjectMessage aom(getId(), false, os.str());
686         m_messages_out.push_back(aom);
687 }
688
689 void LuaEntitySAO::setSprite(v2s16 p, int num_frames, float framelength,
690                 bool select_horiz_by_yawpitch)
691 {
692         std::ostringstream os(std::ios::binary);
693         // command
694         writeU8(os, LUAENTITY_CMD_SET_SPRITE);
695         // parameters
696         writeV2S16(os, p);
697         writeU16(os, num_frames);
698         writeF1000(os, framelength);
699         writeU8(os, select_horiz_by_yawpitch);
700         // create message and add to list
701         ActiveObjectMessage aom(getId(), false, os.str());
702         m_messages_out.push_back(aom);
703 }
704
705 std::string LuaEntitySAO::getName()
706 {
707         return m_init_name;
708 }
709
710 void LuaEntitySAO::setArmorGroups(const ItemGroupList &armor_groups)
711 {
712         m_armor_groups = armor_groups;
713         m_armor_groups_sent = false;
714 }
715
716 void LuaEntitySAO::sendPosition(bool do_interpolate, bool is_movement_end)
717 {
718         m_last_sent_move_precision = m_base_position.getDistanceFrom(
719                         m_last_sent_position);
720         m_last_sent_position_timer = 0;
721         m_last_sent_yaw = m_yaw;
722         m_last_sent_position = m_base_position;
723         m_last_sent_velocity = m_velocity;
724         //m_last_sent_acceleration = m_acceleration;
725
726         float update_interval = m_env->getSendRecommendedInterval();
727
728         std::ostringstream os(std::ios::binary);
729         // command
730         writeU8(os, LUAENTITY_CMD_UPDATE_POSITION);
731
732         // do_interpolate
733         writeU8(os, do_interpolate);
734         // pos
735         writeV3F1000(os, m_base_position);
736         // velocity
737         writeV3F1000(os, m_velocity);
738         // acceleration
739         writeV3F1000(os, m_acceleration);
740         // yaw
741         writeF1000(os, m_yaw);
742         // is_end_position (for interpolation)
743         writeU8(os, is_movement_end);
744         // update_interval (for interpolation)
745         writeF1000(os, update_interval);
746
747         // create message and add to list
748         ActiveObjectMessage aom(getId(), false, os.str());
749         m_messages_out.push_back(aom);
750 }
751