]> git.lizzy.rs Git - dragonfireclient.git/blob - src/server/luaentity_sao.cpp
82f6da2314f8392d66b924844f53d3d6a3a385c2
[dragonfireclient.git] / src / server / luaentity_sao.cpp
1 /*
2 Minetest
3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4 Copyright (C) 2013-2020 Minetest core developers & community
5
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public License along
17 with this program; if not, write to the Free Software Foundation, Inc.,
18 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 */
20
21 #include "luaentity_sao.h"
22 #include "collision.h"
23 #include "constants.h"
24 #include "player_sao.h"
25 #include "scripting_server.h"
26 #include "server.h"
27 #include "serverenvironment.h"
28
29 LuaEntitySAO::LuaEntitySAO(ServerEnvironment *env, v3f pos, const std::string &data)
30         : UnitSAO(env, pos)
31 {
32         std::string name;
33         std::string state;
34         u16 hp = 1;
35         v3f velocity;
36         v3f rotation;
37
38         while (!data.empty()) { // breakable, run for one iteration
39                 std::istringstream is(data, std::ios::binary);
40                 // 'version' does not allow to incrementally extend the parameter list thus
41                 // we need another variable to build on top of 'version=1'. Ugly hack but works™
42                 u8 version2 = 0;
43                 u8 version = readU8(is);
44
45                 name = deSerializeString16(is);
46                 state = deSerializeString32(is);
47
48                 if (version < 1)
49                         break;
50
51                 hp = readU16(is);
52                 velocity = readV3F1000(is);
53                 // yaw must be yaw to be backwards-compatible
54                 rotation.Y = readF1000(is);
55
56                 if (is.good()) // EOF for old formats
57                         version2 = readU8(is);
58
59                 if (version2 < 1) // PROTOCOL_VERSION < 37
60                         break;
61
62                 // version2 >= 1
63                 rotation.X = readF1000(is);
64                 rotation.Z = readF1000(is);
65
66                 // if (version2 < 2)
67                 //     break;
68                 // <read new values>
69                 break;
70         }
71         // create object
72         infostream << "LuaEntitySAO::create(name=\"" << name << "\" state=\""
73                          << state << "\")" << std::endl;
74
75         m_init_name = name;
76         m_init_state = state;
77         m_hp = hp;
78         m_velocity = velocity;
79         m_rotation = rotation;
80 }
81
82 LuaEntitySAO::~LuaEntitySAO()
83 {
84         if(m_registered){
85                 m_env->getScriptIface()->luaentity_Remove(m_id);
86         }
87
88         for (u32 attached_particle_spawner : m_attached_particle_spawners) {
89                 m_env->deleteParticleSpawner(attached_particle_spawner, false);
90         }
91 }
92
93 void LuaEntitySAO::addedToEnvironment(u32 dtime_s)
94 {
95         ServerActiveObject::addedToEnvironment(dtime_s);
96
97         // Create entity from name
98         m_registered = m_env->getScriptIface()->
99                 luaentity_Add(m_id, m_init_name.c_str());
100
101         if(m_registered){
102                 // Get properties
103                 m_env->getScriptIface()->
104                         luaentity_GetProperties(m_id, this, &m_prop);
105                 // Initialize HP from properties
106                 m_hp = m_prop.hp_max;
107                 // Activate entity, supplying serialized state
108                 m_env->getScriptIface()->
109                         luaentity_Activate(m_id, m_init_state, dtime_s);
110         } else {
111                 // It's an unknown object
112                 // Use entitystring as infotext for debugging
113                 m_prop.infotext = m_init_name;
114                 // Set unknown object texture
115                 m_prop.textures.clear();
116                 m_prop.textures.emplace_back("unknown_object.png");
117         }
118 }
119
120 void LuaEntitySAO::dispatchScriptDeactivate()
121 {
122         // Ensure that this is in fact a registered entity,
123         // and that it isn't already gone.
124         // The latter also prevents this from ever being called twice.
125         if (m_registered && !isGone())
126                 m_env->getScriptIface()->luaentity_Deactivate(m_id);
127 }
128
129 void LuaEntitySAO::step(float dtime, bool send_recommended)
130 {
131         if(!m_properties_sent)
132         {
133                 m_properties_sent = true;
134                 std::string str = getPropertyPacket();
135                 // create message and add to list
136                 m_messages_out.emplace(getId(), true, str);
137         }
138
139         // If attached, check that our parent is still there. If it isn't, detach.
140         if (m_attachment_parent_id && !isAttached()) {
141                 // This is handled when objects are removed from the map
142                 warningstream << "LuaEntitySAO::step() id=" << m_id <<
143                         " is attached to nonexistent parent. This is a bug." << std::endl;
144                 clearParentAttachment();
145                 sendPosition(false, true);
146         }
147
148         m_last_sent_position_timer += dtime;
149
150         collisionMoveResult moveresult, *moveresult_p = nullptr;
151
152         // Each frame, parent position is copied if the object is attached, otherwise it's calculated normally
153         // If the object gets detached this comes into effect automatically from the last known origin
154         if (auto *parent = getParent()) {
155                 m_base_position = parent->getBasePosition();
156                 m_velocity = v3f(0,0,0);
157                 m_acceleration = v3f(0,0,0);
158         } else {
159                 if(m_prop.physical){
160                         aabb3f box = m_prop.collisionbox;
161                         box.MinEdge *= BS;
162                         box.MaxEdge *= BS;
163                         f32 pos_max_d = BS*0.25; // Distance per iteration
164                         v3f p_pos = m_base_position;
165                         v3f p_velocity = m_velocity;
166                         v3f p_acceleration = m_acceleration;
167                         moveresult = collisionMoveSimple(m_env, m_env->getGameDef(),
168                                         pos_max_d, box, m_prop.stepheight, dtime,
169                                         &p_pos, &p_velocity, p_acceleration,
170                                         this, m_prop.collideWithObjects);
171                         moveresult_p = &moveresult;
172
173                         // Apply results
174                         m_base_position = p_pos;
175                         m_velocity = p_velocity;
176                         m_acceleration = p_acceleration;
177                 } else {
178                         m_base_position += dtime * m_velocity + 0.5 * dtime
179                                         * dtime * m_acceleration;
180                         m_velocity += dtime * m_acceleration;
181                 }
182
183                 if (m_prop.automatic_face_movement_dir &&
184                                 (fabs(m_velocity.Z) > 0.001 || fabs(m_velocity.X) > 0.001)) {
185                         float target_yaw = atan2(m_velocity.Z, m_velocity.X) * 180 / M_PI
186                                 + m_prop.automatic_face_movement_dir_offset;
187                         float max_rotation_per_sec =
188                                         m_prop.automatic_face_movement_max_rotation_per_sec;
189
190                         if (max_rotation_per_sec > 0) {
191                                 m_rotation.Y = wrapDegrees_0_360(m_rotation.Y);
192                                 wrappedApproachShortest(m_rotation.Y, target_yaw,
193                                         dtime * max_rotation_per_sec, 360.f);
194                         } else {
195                                 // Negative values of max_rotation_per_sec mean disabled.
196                                 m_rotation.Y = target_yaw;
197                         }
198                 }
199         }
200
201         if(m_registered) {
202                 m_env->getScriptIface()->luaentity_Step(m_id, dtime, moveresult_p);
203         }
204
205         if (!send_recommended)
206                 return;
207
208         if(!isAttached())
209         {
210                 // TODO: force send when acceleration changes enough?
211                 float minchange = 0.2*BS;
212                 if(m_last_sent_position_timer > 1.0){
213                         minchange = 0.01*BS;
214                 } else if(m_last_sent_position_timer > 0.2){
215                         minchange = 0.05*BS;
216                 }
217                 float move_d = m_base_position.getDistanceFrom(m_last_sent_position);
218                 move_d += m_last_sent_move_precision;
219                 float vel_d = m_velocity.getDistanceFrom(m_last_sent_velocity);
220                 if (move_d > minchange || vel_d > minchange ||
221                                 std::fabs(m_rotation.X - m_last_sent_rotation.X) > 1.0f ||
222                                 std::fabs(m_rotation.Y - m_last_sent_rotation.Y) > 1.0f ||
223                                 std::fabs(m_rotation.Z - m_last_sent_rotation.Z) > 1.0f) {
224
225                         sendPosition(true, false);
226                 }
227         }
228
229         sendOutdatedData();
230 }
231
232 std::string LuaEntitySAO::getClientInitializationData(u16 protocol_version)
233 {
234         std::ostringstream os(std::ios::binary);
235
236         // PROTOCOL_VERSION >= 37
237         writeU8(os, 1); // version
238         os << serializeString16(""); // name
239         writeU8(os, 0); // is_player
240         writeU16(os, getId()); //id
241         writeV3F32(os, m_base_position);
242         writeV3F32(os, m_rotation);
243         writeU16(os, m_hp);
244
245         std::ostringstream msg_os(std::ios::binary);
246         msg_os << serializeString32(getPropertyPacket()); // message 1
247         msg_os << serializeString32(generateUpdateArmorGroupsCommand()); // 2
248         msg_os << serializeString32(generateUpdateAnimationCommand()); // 3
249         for (const auto &bone_pos : m_bone_position) {
250                 msg_os << serializeString32(generateUpdateBonePositionCommand(
251                         bone_pos.first, bone_pos.second.X, bone_pos.second.Y)); // 3 + N
252         }
253         msg_os << serializeString32(generateUpdateAttachmentCommand()); // 4 + m_bone_position.size
254
255         int message_count = 4 + m_bone_position.size();
256
257         for (const auto &id : getAttachmentChildIds()) {
258                 if (ServerActiveObject *obj = m_env->getActiveObject(id)) {
259                         message_count++;
260                         msg_os << serializeString32(obj->generateUpdateInfantCommand(
261                                 id, protocol_version));
262                 }
263         }
264
265         msg_os << serializeString32(generateSetTextureModCommand());
266         message_count++;
267
268         writeU8(os, message_count);
269         std::string serialized = msg_os.str();
270         os.write(serialized.c_str(), serialized.size());
271
272         // return result
273         return os.str();
274 }
275
276 void LuaEntitySAO::getStaticData(std::string *result) const
277 {
278         verbosestream<<FUNCTION_NAME<<std::endl;
279         std::ostringstream os(std::ios::binary);
280         // version must be 1 to keep backwards-compatibility. See version2
281         writeU8(os, 1);
282         // name
283         os<<serializeString16(m_init_name);
284         // state
285         if(m_registered){
286                 std::string state = m_env->getScriptIface()->
287                         luaentity_GetStaticdata(m_id);
288                 os<<serializeString32(state);
289         } else {
290                 os<<serializeString32(m_init_state);
291         }
292         writeU16(os, m_hp);
293         writeV3F1000(os, m_velocity);
294         // yaw
295         writeF1000(os, m_rotation.Y);
296
297         // version2. Increase this variable for new values
298         writeU8(os, 1); // PROTOCOL_VERSION >= 37
299
300         writeF1000(os, m_rotation.X);
301         writeF1000(os, m_rotation.Z);
302
303         // <write new values>
304
305         *result = os.str();
306 }
307
308 u32 LuaEntitySAO::punch(v3f dir,
309                 const ToolCapabilities *toolcap,
310                 ServerActiveObject *puncher,
311                 float time_from_last_punch,
312                 u16 initial_wear)
313 {
314         if (!m_registered) {
315                 // Delete unknown LuaEntities when punched
316                 markForRemoval();
317                 return 0;
318         }
319
320         FATAL_ERROR_IF(!puncher, "Punch action called without SAO");
321
322         s32 old_hp = getHP();
323         ItemStack selected_item, hand_item;
324         ItemStack tool_item = puncher->getWieldedItem(&selected_item, &hand_item);
325
326         PunchDamageResult result = getPunchDamage(
327                         m_armor_groups,
328                         toolcap,
329                         &tool_item,
330                         time_from_last_punch,
331                         initial_wear);
332
333         bool damage_handled = m_env->getScriptIface()->luaentity_Punch(m_id, puncher,
334                         time_from_last_punch, toolcap, dir, result.did_punch ? result.damage : 0);
335
336         if (!damage_handled) {
337                 if (result.did_punch) {
338                         setHP((s32)getHP() - result.damage,
339                                 PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, puncher));
340
341                         // create message and add to list
342                         sendPunchCommand();
343                 }
344         }
345
346         if (getHP() == 0 && !isGone()) {
347                 clearParentAttachment();
348                 clearChildAttachments();
349                 m_env->getScriptIface()->luaentity_on_death(m_id, puncher);
350                 markForRemoval();
351         }
352
353         actionstream << puncher->getDescription() << " (id=" << puncher->getId() <<
354                         ", hp=" << puncher->getHP() << ") punched " <<
355                         getDescription() << " (id=" << m_id << ", hp=" << m_hp <<
356                         "), damage=" << (old_hp - (s32)getHP()) <<
357                         (damage_handled ? " (handled by Lua)" : "") << std::endl;
358
359         // TODO: give Lua control over wear
360         return result.wear;
361 }
362
363 void LuaEntitySAO::rightClick(ServerActiveObject *clicker)
364 {
365         if (!m_registered)
366                 return;
367
368         m_env->getScriptIface()->luaentity_Rightclick(m_id, clicker);
369 }
370
371 void LuaEntitySAO::setPos(const v3f &pos)
372 {
373         if(isAttached())
374                 return;
375         m_base_position = pos;
376         sendPosition(false, true);
377 }
378
379 void LuaEntitySAO::moveTo(v3f pos, bool continuous)
380 {
381         if(isAttached())
382                 return;
383         m_base_position = pos;
384         if(!continuous)
385                 sendPosition(true, true);
386 }
387
388 float LuaEntitySAO::getMinimumSavedMovement()
389 {
390         return 0.1 * BS;
391 }
392
393 std::string LuaEntitySAO::getDescription()
394 {
395         std::ostringstream oss;
396         oss << "LuaEntitySAO \"" << m_init_name << "\" ";
397         auto pos = floatToInt(m_base_position, BS);
398         oss << "at " << PP(pos);
399         return oss.str();
400 }
401
402 void LuaEntitySAO::setHP(s32 hp, const PlayerHPChangeReason &reason)
403 {
404         m_hp = rangelim(hp, 0, U16_MAX);
405 }
406
407 u16 LuaEntitySAO::getHP() const
408 {
409         return m_hp;
410 }
411
412 void LuaEntitySAO::setVelocity(v3f velocity)
413 {
414         m_velocity = velocity;
415 }
416
417 v3f LuaEntitySAO::getVelocity()
418 {
419         return m_velocity;
420 }
421
422 void LuaEntitySAO::setAcceleration(v3f acceleration)
423 {
424         m_acceleration = acceleration;
425 }
426
427 v3f LuaEntitySAO::getAcceleration()
428 {
429         return m_acceleration;
430 }
431
432 void LuaEntitySAO::setTextureMod(const std::string &mod)
433 {
434         m_current_texture_modifier = mod;
435         // create message and add to list
436         m_messages_out.emplace(getId(), true, generateSetTextureModCommand());
437 }
438
439 std::string LuaEntitySAO::getTextureMod() const
440 {
441         return m_current_texture_modifier;
442 }
443
444
445 std::string LuaEntitySAO::generateSetTextureModCommand() const
446 {
447         std::ostringstream os(std::ios::binary);
448         // command
449         writeU8(os, AO_CMD_SET_TEXTURE_MOD);
450         // parameters
451         os << serializeString16(m_current_texture_modifier);
452         return os.str();
453 }
454
455 std::string LuaEntitySAO::generateSetSpriteCommand(v2s16 p, u16 num_frames,
456         f32 framelength, bool select_horiz_by_yawpitch)
457 {
458         std::ostringstream os(std::ios::binary);
459         // command
460         writeU8(os, AO_CMD_SET_SPRITE);
461         // parameters
462         writeV2S16(os, p);
463         writeU16(os, num_frames);
464         writeF32(os, framelength);
465         writeU8(os, select_horiz_by_yawpitch);
466         return os.str();
467 }
468
469 void LuaEntitySAO::setSprite(v2s16 p, int num_frames, float framelength,
470                 bool select_horiz_by_yawpitch)
471 {
472         std::string str = generateSetSpriteCommand(
473                 p,
474                 num_frames,
475                 framelength,
476                 select_horiz_by_yawpitch
477         );
478         // create message and add to list
479         m_messages_out.emplace(getId(), true, str);
480 }
481
482 std::string LuaEntitySAO::getName()
483 {
484         return m_init_name;
485 }
486
487 std::string LuaEntitySAO::getPropertyPacket()
488 {
489         return generateSetPropertiesCommand(m_prop);
490 }
491
492 void LuaEntitySAO::sendPosition(bool do_interpolate, bool is_movement_end)
493 {
494         // If the object is attached client-side, don't waste bandwidth sending its position to clients
495         if(isAttached())
496                 return;
497
498         // Send attachment updates instantly to the client prior updating position
499         sendOutdatedData();
500
501         m_last_sent_move_precision = m_base_position.getDistanceFrom(
502                         m_last_sent_position);
503         m_last_sent_position_timer = 0;
504         m_last_sent_position = m_base_position;
505         m_last_sent_velocity = m_velocity;
506         //m_last_sent_acceleration = m_acceleration;
507         m_last_sent_rotation = m_rotation;
508
509         float update_interval = m_env->getSendRecommendedInterval();
510
511         std::string str = generateUpdatePositionCommand(
512                 m_base_position,
513                 m_velocity,
514                 m_acceleration,
515                 m_rotation,
516                 do_interpolate,
517                 is_movement_end,
518                 update_interval
519         );
520         // create message and add to list
521         m_messages_out.emplace(getId(), false, str);
522 }
523
524 bool LuaEntitySAO::getCollisionBox(aabb3f *toset) const
525 {
526         if (m_prop.physical)
527         {
528                 //update collision box
529                 toset->MinEdge = m_prop.collisionbox.MinEdge * BS;
530                 toset->MaxEdge = m_prop.collisionbox.MaxEdge * BS;
531
532                 toset->MinEdge += m_base_position;
533                 toset->MaxEdge += m_base_position;
534
535                 return true;
536         }
537
538         return false;
539 }
540
541 bool LuaEntitySAO::getSelectionBox(aabb3f *toset) const
542 {
543         if (!m_prop.is_visible || !m_prop.pointable) {
544                 return false;
545         }
546
547         toset->MinEdge = m_prop.selectionbox.MinEdge * BS;
548         toset->MaxEdge = m_prop.selectionbox.MaxEdge * BS;
549
550         return true;
551 }
552
553 bool LuaEntitySAO::collideWithObjects() const
554 {
555         return m_prop.collideWithObjects;
556 }