luaentity_sao.cpp 14 KB

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