]> git.lizzy.rs Git - dragonfireclient.git/blob - src/server/luaentity_sao.cpp
Drop content_sao.{cpp,h}
[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 = 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                 ActiveObjectMessage aom(getId(), true, str);
123                 m_messages_out.push(aom);
124         }
125
126         // If attached, check that our parent is still there. If it isn't, detach.
127         if(m_attachment_parent_id && !isAttached())
128         {
129                 m_attachment_parent_id = 0;
130                 m_attachment_bone = "";
131                 m_attachment_position = v3f(0,0,0);
132                 m_attachment_rotation = v3f(0,0,0);
133                 sendPosition(false, true);
134         }
135
136         m_last_sent_position_timer += dtime;
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                         collisionMoveResult moveresult;
154                         f32 pos_max_d = BS*0.25; // Distance per iteration
155                         v3f p_pos = m_base_position;
156                         v3f p_velocity = m_velocity;
157                         v3f p_acceleration = m_acceleration;
158                         moveresult = collisionMoveSimple(m_env, m_env->getGameDef(),
159                                         pos_max_d, box, m_prop.stepheight, dtime,
160                                         &p_pos, &p_velocity, p_acceleration,
161                                         this, m_prop.collideWithObjects);
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);
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         if (!m_armor_groups_sent) {
220                 m_armor_groups_sent = true;
221                 // create message and add to list
222                 m_messages_out.emplace(getId(), true, generateUpdateArmorGroupsCommand());
223         }
224
225         if (!m_animation_sent) {
226                 m_animation_sent = true;
227                 std::string str = generateUpdateAnimationCommand();
228                 // create message and add to list
229                 ActiveObjectMessage aom(getId(), true, str);
230                 m_messages_out.push(aom);
231         }
232
233         if (!m_animation_speed_sent) {
234                 m_animation_speed_sent = true;
235                 std::string str = generateUpdateAnimationSpeedCommand();
236                 // create message and add to list
237                 ActiveObjectMessage aom(getId(), true, str);
238                 m_messages_out.push(aom);
239         }
240
241         if (!m_bone_position_sent) {
242                 m_bone_position_sent = true;
243                 for (std::unordered_map<std::string, core::vector2d<v3f>>::const_iterator
244                                 ii = m_bone_position.begin(); ii != m_bone_position.end(); ++ii){
245                         std::string str = generateUpdateBonePositionCommand((*ii).first,
246                                         (*ii).second.X, (*ii).second.Y);
247                         // create message and add to list
248                         ActiveObjectMessage aom(getId(), true, str);
249                         m_messages_out.push(aom);
250                 }
251         }
252
253         if (!m_attachment_sent) {
254                 m_attachment_sent = true;
255                 std::string str = generateUpdateAttachmentCommand();
256                 // create message and add to list
257                 ActiveObjectMessage aom(getId(), true, str);
258                 m_messages_out.push(aom);
259         }
260 }
261
262 std::string LuaEntitySAO::getClientInitializationData(u16 protocol_version)
263 {
264         std::ostringstream os(std::ios::binary);
265
266         // PROTOCOL_VERSION >= 37
267         writeU8(os, 1); // version
268         os << serializeString(""); // name
269         writeU8(os, 0); // is_player
270         writeU16(os, getId()); //id
271         writeV3F32(os, m_base_position);
272         writeV3F32(os, m_rotation);
273         writeU16(os, m_hp);
274
275         std::ostringstream msg_os(std::ios::binary);
276         msg_os << serializeLongString(getPropertyPacket()); // message 1
277         msg_os << serializeLongString(generateUpdateArmorGroupsCommand()); // 2
278         msg_os << serializeLongString(generateUpdateAnimationCommand()); // 3
279         for (std::unordered_map<std::string, core::vector2d<v3f>>::const_iterator
280                         ii = m_bone_position.begin(); ii != m_bone_position.end(); ++ii) {
281                 msg_os << serializeLongString(generateUpdateBonePositionCommand((*ii).first,
282                                 (*ii).second.X, (*ii).second.Y)); // m_bone_position.size
283         }
284         msg_os << serializeLongString(generateUpdateAttachmentCommand()); // 4
285         int message_count = 4 + m_bone_position.size();
286         for (std::unordered_set<int>::const_iterator ii = m_attachment_child_ids.begin();
287                         (ii != m_attachment_child_ids.end()); ++ii) {
288                 if (ServerActiveObject *obj = m_env->getActiveObject(*ii)) {
289                         message_count++;
290                         // TODO after a protocol bump: only send the object initialization data
291                         // to older clients (superfluous since this message exists)
292                         msg_os << serializeLongString(obj->generateUpdateInfantCommand(*ii, protocol_version));
293                 }
294         }
295
296         msg_os << serializeLongString(generateSetTextureModCommand());
297         message_count++;
298
299         writeU8(os, message_count);
300         os.write(msg_os.str().c_str(), msg_os.str().size());
301
302         // return result
303         return os.str();
304 }
305
306 void LuaEntitySAO::getStaticData(std::string *result) const
307 {
308         verbosestream<<FUNCTION_NAME<<std::endl;
309         std::ostringstream os(std::ios::binary);
310         // version must be 1 to keep backwards-compatibility. See version2
311         writeU8(os, 1);
312         // name
313         os<<serializeString(m_init_name);
314         // state
315         if(m_registered){
316                 std::string state = m_env->getScriptIface()->
317                         luaentity_GetStaticdata(m_id);
318                 os<<serializeLongString(state);
319         } else {
320                 os<<serializeLongString(m_init_state);
321         }
322         writeU16(os, m_hp);
323         writeV3F1000(os, m_velocity);
324         // yaw
325         writeF1000(os, m_rotation.Y);
326
327         // version2. Increase this variable for new values
328         writeU8(os, 1); // PROTOCOL_VERSION >= 37
329
330         writeF1000(os, m_rotation.X);
331         writeF1000(os, m_rotation.Z);
332
333         // <write new values>
334
335         *result = os.str();
336 }
337
338 u16 LuaEntitySAO::punch(v3f dir,
339                 const ToolCapabilities *toolcap,
340                 ServerActiveObject *puncher,
341                 float time_from_last_punch)
342 {
343         if (!m_registered) {
344                 // Delete unknown LuaEntities when punched
345                 m_pending_removal = true;
346                 return 0;
347         }
348
349         FATAL_ERROR_IF(!puncher, "Punch action called without SAO");
350
351         s32 old_hp = getHP();
352         ItemStack selected_item, hand_item;
353         ItemStack tool_item = puncher->getWieldedItem(&selected_item, &hand_item);
354
355         PunchDamageResult result = getPunchDamage(
356                         m_armor_groups,
357                         toolcap,
358                         &tool_item,
359                         time_from_last_punch);
360
361         bool damage_handled = m_env->getScriptIface()->luaentity_Punch(m_id, puncher,
362                         time_from_last_punch, toolcap, dir, result.did_punch ? result.damage : 0);
363
364         if (!damage_handled) {
365                 if (result.did_punch) {
366                         setHP((s32)getHP() - result.damage,
367                                 PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, puncher));
368
369                         // create message and add to list
370                         sendPunchCommand();
371                 }
372         }
373
374         if (getHP() == 0 && !isGone()) {
375                 clearParentAttachment();
376                 clearChildAttachments();
377                 m_env->getScriptIface()->luaentity_on_death(m_id, puncher);
378                 m_pending_removal = true;
379         }
380
381         actionstream << puncher->getDescription() << " (id=" << puncher->getId() <<
382                         ", hp=" << puncher->getHP() << ") punched " <<
383                         getDescription() << " (id=" << m_id << ", hp=" << m_hp <<
384                         "), damage=" << (old_hp - (s32)getHP()) <<
385                         (damage_handled ? " (handled by Lua)" : "") << std::endl;
386
387         // TODO: give Lua control over wear
388         return result.wear;
389 }
390
391 void LuaEntitySAO::rightClick(ServerActiveObject *clicker)
392 {
393         if (!m_registered)
394                 return;
395
396         m_env->getScriptIface()->luaentity_Rightclick(m_id, clicker);
397 }
398
399 void LuaEntitySAO::setPos(const v3f &pos)
400 {
401         if(isAttached())
402                 return;
403         m_base_position = pos;
404         sendPosition(false, true);
405 }
406
407 void LuaEntitySAO::moveTo(v3f pos, bool continuous)
408 {
409         if(isAttached())
410                 return;
411         m_base_position = pos;
412         if(!continuous)
413                 sendPosition(true, true);
414 }
415
416 float LuaEntitySAO::getMinimumSavedMovement()
417 {
418         return 0.1 * BS;
419 }
420
421 std::string LuaEntitySAO::getDescription()
422 {
423         std::ostringstream oss;
424         oss << "LuaEntitySAO \"" << m_init_name << "\" ";
425         auto pos = floatToInt(m_base_position, BS);
426         oss << "at " << PP(pos);
427         return oss.str();
428 }
429
430 void LuaEntitySAO::setHP(s32 hp, const PlayerHPChangeReason &reason)
431 {
432         m_hp = rangelim(hp, 0, U16_MAX);
433 }
434
435 u16 LuaEntitySAO::getHP() const
436 {
437         return m_hp;
438 }
439
440 void LuaEntitySAO::setVelocity(v3f velocity)
441 {
442         m_velocity = velocity;
443 }
444
445 v3f LuaEntitySAO::getVelocity()
446 {
447         return m_velocity;
448 }
449
450 void LuaEntitySAO::setAcceleration(v3f acceleration)
451 {
452         m_acceleration = acceleration;
453 }
454
455 v3f LuaEntitySAO::getAcceleration()
456 {
457         return m_acceleration;
458 }
459
460 void LuaEntitySAO::setTextureMod(const std::string &mod)
461 {
462         m_current_texture_modifier = mod;
463         // create message and add to list
464         m_messages_out.emplace(getId(), true, generateSetTextureModCommand());
465 }
466
467 std::string LuaEntitySAO::getTextureMod() const
468 {
469         return m_current_texture_modifier;
470 }
471
472
473 std::string LuaEntitySAO::generateSetTextureModCommand() const
474 {
475         std::ostringstream os(std::ios::binary);
476         // command
477         writeU8(os, AO_CMD_SET_TEXTURE_MOD);
478         // parameters
479         os << serializeString(m_current_texture_modifier);
480         return os.str();
481 }
482
483 std::string LuaEntitySAO::generateSetSpriteCommand(v2s16 p, u16 num_frames,
484         f32 framelength, bool select_horiz_by_yawpitch)
485 {
486         std::ostringstream os(std::ios::binary);
487         // command
488         writeU8(os, AO_CMD_SET_SPRITE);
489         // parameters
490         writeV2S16(os, p);
491         writeU16(os, num_frames);
492         writeF32(os, framelength);
493         writeU8(os, select_horiz_by_yawpitch);
494         return os.str();
495 }
496
497 void LuaEntitySAO::setSprite(v2s16 p, int num_frames, float framelength,
498                 bool select_horiz_by_yawpitch)
499 {
500         std::string str = generateSetSpriteCommand(
501                 p,
502                 num_frames,
503                 framelength,
504                 select_horiz_by_yawpitch
505         );
506         // create message and add to list
507         m_messages_out.emplace(getId(), true, str);
508 }
509
510 std::string LuaEntitySAO::getName()
511 {
512         return m_init_name;
513 }
514
515 std::string LuaEntitySAO::getPropertyPacket()
516 {
517         return generateSetPropertiesCommand(m_prop);
518 }
519
520 void LuaEntitySAO::sendPosition(bool do_interpolate, bool is_movement_end)
521 {
522         // If the object is attached client-side, don't waste bandwidth sending its position to clients
523         if(isAttached())
524                 return;
525
526         m_last_sent_move_precision = m_base_position.getDistanceFrom(
527                         m_last_sent_position);
528         m_last_sent_position_timer = 0;
529         m_last_sent_position = m_base_position;
530         m_last_sent_velocity = m_velocity;
531         //m_last_sent_acceleration = m_acceleration;
532         m_last_sent_rotation = m_rotation;
533
534         float update_interval = m_env->getSendRecommendedInterval();
535
536         std::string str = generateUpdatePositionCommand(
537                 m_base_position,
538                 m_velocity,
539                 m_acceleration,
540                 m_rotation,
541                 do_interpolate,
542                 is_movement_end,
543                 update_interval
544         );
545         // create message and add to list
546         m_messages_out.emplace(getId(), false, str);
547 }
548
549 bool LuaEntitySAO::getCollisionBox(aabb3f *toset) const
550 {
551         if (m_prop.physical)
552         {
553                 //update collision box
554                 toset->MinEdge = m_prop.collisionbox.MinEdge * BS;
555                 toset->MaxEdge = m_prop.collisionbox.MaxEdge * BS;
556
557                 toset->MinEdge += m_base_position;
558                 toset->MaxEdge += m_base_position;
559
560                 return true;
561         }
562
563         return false;
564 }
565
566 bool LuaEntitySAO::getSelectionBox(aabb3f *toset) const
567 {
568         if (!m_prop.is_visible || !m_prop.pointable) {
569                 return false;
570         }
571
572         toset->MinEdge = m_prop.selectionbox.MinEdge * BS;
573         toset->MaxEdge = m_prop.selectionbox.MaxEdge * BS;
574
575         return true;
576 }
577
578 bool LuaEntitySAO::collideWithObjects() const
579 {
580         return m_prop.collideWithObjects;
581 }