]> git.lizzy.rs Git - minetest.git/blob - src/server/luaentity_sao.cpp
Move shared parameters sending to UnitSAO (#9968)
[minetest.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 = deSerializeString(is);
46                 state = deSerializeLongString(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                 m_prop.infotext = m_init_name;
112         }
113 }
114
115 void LuaEntitySAO::step(float dtime, bool send_recommended)
116 {
117         if(!m_properties_sent)
118         {
119                 m_properties_sent = true;
120                 std::string str = getPropertyPacket();
121                 // create message and add to list
122                 m_messages_out.emplace(getId(), true, str);
123         }
124
125         // If attached, check that our parent is still there. If it isn't, detach.
126         if (m_attachment_parent_id && !isAttached()) {
127                 // This is handled when objects are removed from the map
128                 warningstream << "LuaEntitySAO::step() id=" << m_id <<
129                         " is attached to nonexistent parent. This is a bug." << std::endl;
130                 clearParentAttachment();
131                 sendPosition(false, true);
132         }
133
134         m_last_sent_position_timer += dtime;
135
136         collisionMoveResult moveresult, *moveresult_p = nullptr;
137
138         // Each frame, parent position is copied if the object is attached, otherwise it's calculated normally
139         // If the object gets detached this comes into effect automatically from the last known origin
140         if(isAttached())
141         {
142                 v3f pos = m_env->getActiveObject(m_attachment_parent_id)->getBasePosition();
143                 m_base_position = pos;
144                 m_velocity = v3f(0,0,0);
145                 m_acceleration = v3f(0,0,0);
146         }
147         else
148         {
149                 if(m_prop.physical){
150                         aabb3f box = m_prop.collisionbox;
151                         box.MinEdge *= BS;
152                         box.MaxEdge *= BS;
153                         f32 pos_max_d = BS*0.25; // Distance per iteration
154                         v3f p_pos = m_base_position;
155                         v3f p_velocity = m_velocity;
156                         v3f p_acceleration = m_acceleration;
157                         moveresult = collisionMoveSimple(m_env, m_env->getGameDef(),
158                                         pos_max_d, box, m_prop.stepheight, dtime,
159                                         &p_pos, &p_velocity, p_acceleration,
160                                         this, m_prop.collideWithObjects);
161                         moveresult_p = &moveresult;
162
163                         // Apply results
164                         m_base_position = p_pos;
165                         m_velocity = p_velocity;
166                         m_acceleration = p_acceleration;
167                 } else {
168                         m_base_position += dtime * m_velocity + 0.5 * dtime
169                                         * dtime * m_acceleration;
170                         m_velocity += dtime * m_acceleration;
171                 }
172
173                 if (m_prop.automatic_face_movement_dir &&
174                                 (fabs(m_velocity.Z) > 0.001 || fabs(m_velocity.X) > 0.001)) {
175                         float target_yaw = atan2(m_velocity.Z, m_velocity.X) * 180 / M_PI
176                                 + m_prop.automatic_face_movement_dir_offset;
177                         float max_rotation_per_sec =
178                                         m_prop.automatic_face_movement_max_rotation_per_sec;
179
180                         if (max_rotation_per_sec > 0) {
181                                 m_rotation.Y = wrapDegrees_0_360(m_rotation.Y);
182                                 wrappedApproachShortest(m_rotation.Y, target_yaw,
183                                         dtime * max_rotation_per_sec, 360.f);
184                         } else {
185                                 // Negative values of max_rotation_per_sec mean disabled.
186                                 m_rotation.Y = target_yaw;
187                         }
188                 }
189         }
190
191         if(m_registered) {
192                 m_env->getScriptIface()->luaentity_Step(m_id, dtime, moveresult_p);
193         }
194
195         if (!send_recommended)
196                 return;
197
198         if(!isAttached())
199         {
200                 // TODO: force send when acceleration changes enough?
201                 float minchange = 0.2*BS;
202                 if(m_last_sent_position_timer > 1.0){
203                         minchange = 0.01*BS;
204                 } else if(m_last_sent_position_timer > 0.2){
205                         minchange = 0.05*BS;
206                 }
207                 float move_d = m_base_position.getDistanceFrom(m_last_sent_position);
208                 move_d += m_last_sent_move_precision;
209                 float vel_d = m_velocity.getDistanceFrom(m_last_sent_velocity);
210                 if (move_d > minchange || vel_d > minchange ||
211                                 std::fabs(m_rotation.X - m_last_sent_rotation.X) > 1.0f ||
212                                 std::fabs(m_rotation.Y - m_last_sent_rotation.Y) > 1.0f ||
213                                 std::fabs(m_rotation.Z - m_last_sent_rotation.Z) > 1.0f) {
214
215                         sendPosition(true, false);
216                 }
217         }
218
219         sendOutdatedData();
220 }
221
222 std::string LuaEntitySAO::getClientInitializationData(u16 protocol_version)
223 {
224         std::ostringstream os(std::ios::binary);
225
226         // PROTOCOL_VERSION >= 37
227         writeU8(os, 1); // version
228         os << serializeString(""); // name
229         writeU8(os, 0); // is_player
230         writeU16(os, getId()); //id
231         writeV3F32(os, m_base_position);
232         writeV3F32(os, m_rotation);
233         writeU16(os, m_hp);
234
235         std::ostringstream msg_os(std::ios::binary);
236         msg_os << serializeLongString(getPropertyPacket()); // message 1
237         msg_os << serializeLongString(generateUpdateArmorGroupsCommand()); // 2
238         msg_os << serializeLongString(generateUpdateAnimationCommand()); // 3
239         for (const auto &bone_pos : m_bone_position) {
240                 msg_os << serializeLongString(generateUpdateBonePositionCommand(
241                         bone_pos.first, bone_pos.second.X, bone_pos.second.Y)); // m_bone_position.size
242         }
243         msg_os << serializeLongString(generateUpdateAttachmentCommand()); // 4
244
245         int message_count = 4 + m_bone_position.size();
246
247         for (const auto &id : getAttachmentChildIds()) {
248                 if (ServerActiveObject *obj = m_env->getActiveObject(id)) {
249                         message_count++;
250                         msg_os << serializeLongString(obj->generateUpdateInfantCommand(
251                                 id, protocol_version));
252                 }
253         }
254
255         msg_os << serializeLongString(generateSetTextureModCommand());
256         message_count++;
257
258         writeU8(os, message_count);
259         std::string serialized = msg_os.str();
260         os.write(serialized.c_str(), serialized.size());
261
262         // return result
263         return os.str();
264 }
265
266 void LuaEntitySAO::getStaticData(std::string *result) const
267 {
268         verbosestream<<FUNCTION_NAME<<std::endl;
269         std::ostringstream os(std::ios::binary);
270         // version must be 1 to keep backwards-compatibility. See version2
271         writeU8(os, 1);
272         // name
273         os<<serializeString(m_init_name);
274         // state
275         if(m_registered){
276                 std::string state = m_env->getScriptIface()->
277                         luaentity_GetStaticdata(m_id);
278                 os<<serializeLongString(state);
279         } else {
280                 os<<serializeLongString(m_init_state);
281         }
282         writeU16(os, m_hp);
283         writeV3F1000(os, m_velocity);
284         // yaw
285         writeF1000(os, m_rotation.Y);
286
287         // version2. Increase this variable for new values
288         writeU8(os, 1); // PROTOCOL_VERSION >= 37
289
290         writeF1000(os, m_rotation.X);
291         writeF1000(os, m_rotation.Z);
292
293         // <write new values>
294
295         *result = os.str();
296 }
297
298 u16 LuaEntitySAO::punch(v3f dir,
299                 const ToolCapabilities *toolcap,
300                 ServerActiveObject *puncher,
301                 float time_from_last_punch)
302 {
303         if (!m_registered) {
304                 // Delete unknown LuaEntities when punched
305                 m_pending_removal = true;
306                 return 0;
307         }
308
309         FATAL_ERROR_IF(!puncher, "Punch action called without SAO");
310
311         s32 old_hp = getHP();
312         ItemStack selected_item, hand_item;
313         ItemStack tool_item = puncher->getWieldedItem(&selected_item, &hand_item);
314
315         PunchDamageResult result = getPunchDamage(
316                         m_armor_groups,
317                         toolcap,
318                         &tool_item,
319                         time_from_last_punch);
320
321         bool damage_handled = m_env->getScriptIface()->luaentity_Punch(m_id, puncher,
322                         time_from_last_punch, toolcap, dir, result.did_punch ? result.damage : 0);
323
324         if (!damage_handled) {
325                 if (result.did_punch) {
326                         setHP((s32)getHP() - result.damage,
327                                 PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, puncher));
328
329                         // create message and add to list
330                         sendPunchCommand();
331                 }
332         }
333
334         if (getHP() == 0 && !isGone()) {
335                 clearParentAttachment();
336                 clearChildAttachments();
337                 m_env->getScriptIface()->luaentity_on_death(m_id, puncher);
338                 m_pending_removal = true;
339         }
340
341         actionstream << puncher->getDescription() << " (id=" << puncher->getId() <<
342                         ", hp=" << puncher->getHP() << ") punched " <<
343                         getDescription() << " (id=" << m_id << ", hp=" << m_hp <<
344                         "), damage=" << (old_hp - (s32)getHP()) <<
345                         (damage_handled ? " (handled by Lua)" : "") << std::endl;
346
347         // TODO: give Lua control over wear
348         return result.wear;
349 }
350
351 void LuaEntitySAO::rightClick(ServerActiveObject *clicker)
352 {
353         if (!m_registered)
354                 return;
355
356         m_env->getScriptIface()->luaentity_Rightclick(m_id, clicker);
357 }
358
359 void LuaEntitySAO::setPos(const v3f &pos)
360 {
361         if(isAttached())
362                 return;
363         m_base_position = pos;
364         sendPosition(false, true);
365 }
366
367 void LuaEntitySAO::moveTo(v3f pos, bool continuous)
368 {
369         if(isAttached())
370                 return;
371         m_base_position = pos;
372         if(!continuous)
373                 sendPosition(true, true);
374 }
375
376 float LuaEntitySAO::getMinimumSavedMovement()
377 {
378         return 0.1 * BS;
379 }
380
381 std::string LuaEntitySAO::getDescription()
382 {
383         std::ostringstream oss;
384         oss << "LuaEntitySAO \"" << m_init_name << "\" ";
385         auto pos = floatToInt(m_base_position, BS);
386         oss << "at " << PP(pos);
387         return oss.str();
388 }
389
390 void LuaEntitySAO::setHP(s32 hp, const PlayerHPChangeReason &reason)
391 {
392         m_hp = rangelim(hp, 0, U16_MAX);
393 }
394
395 u16 LuaEntitySAO::getHP() const
396 {
397         return m_hp;
398 }
399
400 void LuaEntitySAO::setVelocity(v3f velocity)
401 {
402         m_velocity = velocity;
403 }
404
405 v3f LuaEntitySAO::getVelocity()
406 {
407         return m_velocity;
408 }
409
410 void LuaEntitySAO::setAcceleration(v3f acceleration)
411 {
412         m_acceleration = acceleration;
413 }
414
415 v3f LuaEntitySAO::getAcceleration()
416 {
417         return m_acceleration;
418 }
419
420 void LuaEntitySAO::setTextureMod(const std::string &mod)
421 {
422         m_current_texture_modifier = mod;
423         // create message and add to list
424         m_messages_out.emplace(getId(), true, generateSetTextureModCommand());
425 }
426
427 std::string LuaEntitySAO::getTextureMod() const
428 {
429         return m_current_texture_modifier;
430 }
431
432
433 std::string LuaEntitySAO::generateSetTextureModCommand() const
434 {
435         std::ostringstream os(std::ios::binary);
436         // command
437         writeU8(os, AO_CMD_SET_TEXTURE_MOD);
438         // parameters
439         os << serializeString(m_current_texture_modifier);
440         return os.str();
441 }
442
443 std::string LuaEntitySAO::generateSetSpriteCommand(v2s16 p, u16 num_frames,
444         f32 framelength, bool select_horiz_by_yawpitch)
445 {
446         std::ostringstream os(std::ios::binary);
447         // command
448         writeU8(os, AO_CMD_SET_SPRITE);
449         // parameters
450         writeV2S16(os, p);
451         writeU16(os, num_frames);
452         writeF32(os, framelength);
453         writeU8(os, select_horiz_by_yawpitch);
454         return os.str();
455 }
456
457 void LuaEntitySAO::setSprite(v2s16 p, int num_frames, float framelength,
458                 bool select_horiz_by_yawpitch)
459 {
460         std::string str = generateSetSpriteCommand(
461                 p,
462                 num_frames,
463                 framelength,
464                 select_horiz_by_yawpitch
465         );
466         // create message and add to list
467         m_messages_out.emplace(getId(), true, str);
468 }
469
470 std::string LuaEntitySAO::getName()
471 {
472         return m_init_name;
473 }
474
475 std::string LuaEntitySAO::getPropertyPacket()
476 {
477         return generateSetPropertiesCommand(m_prop);
478 }
479
480 void LuaEntitySAO::sendPosition(bool do_interpolate, bool is_movement_end)
481 {
482         // If the object is attached client-side, don't waste bandwidth sending its position to clients
483         if(isAttached())
484                 return;
485
486         m_last_sent_move_precision = m_base_position.getDistanceFrom(
487                         m_last_sent_position);
488         m_last_sent_position_timer = 0;
489         m_last_sent_position = m_base_position;
490         m_last_sent_velocity = m_velocity;
491         //m_last_sent_acceleration = m_acceleration;
492         m_last_sent_rotation = m_rotation;
493
494         float update_interval = m_env->getSendRecommendedInterval();
495
496         std::string str = generateUpdatePositionCommand(
497                 m_base_position,
498                 m_velocity,
499                 m_acceleration,
500                 m_rotation,
501                 do_interpolate,
502                 is_movement_end,
503                 update_interval
504         );
505         // create message and add to list
506         m_messages_out.emplace(getId(), false, str);
507 }
508
509 bool LuaEntitySAO::getCollisionBox(aabb3f *toset) const
510 {
511         if (m_prop.physical)
512         {
513                 //update collision box
514                 toset->MinEdge = m_prop.collisionbox.MinEdge * BS;
515                 toset->MaxEdge = m_prop.collisionbox.MaxEdge * BS;
516
517                 toset->MinEdge += m_base_position;
518                 toset->MaxEdge += m_base_position;
519
520                 return true;
521         }
522
523         return false;
524 }
525
526 bool LuaEntitySAO::getSelectionBox(aabb3f *toset) const
527 {
528         if (!m_prop.is_visible || !m_prop.pointable) {
529                 return false;
530         }
531
532         toset->MinEdge = m_prop.selectionbox.MinEdge * BS;
533         toset->MaxEdge = m_prop.selectionbox.MaxEdge * BS;
534
535         return true;
536 }
537
538 bool LuaEntitySAO::collideWithObjects() const
539 {
540         return m_prop.collideWithObjects;
541 }