tnt_boom.lua 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  1. -- Localize for performance.
  2. local vector_distance = vector.distance
  3. local vector_round = vector.round
  4. local math_floor = math.floor
  5. local math_random = math.random
  6. local math_min = math.min
  7. local math_max = math.max
  8. -- Fill a list with data for content IDs, after all nodes are registered
  9. local cid_data = {}
  10. minetest.register_on_mods_loaded(function()
  11. for name, def in pairs(minetest.registered_nodes) do
  12. cid_data[minetest.get_content_id(name)] = {
  13. name = name,
  14. -- Why is this misspelled? Not used? (drops: no such key)
  15. drops = def.drops,
  16. _tnt_drop = def._tnt_drop,
  17. flammable = def.groups.flammable,
  18. on_blast = def.on_blast,
  19. on_destruct = def.on_destruct,
  20. after_destruct = def.after_destruct,
  21. _is_bulk_mapgen_stone = def._is_bulk_mapgen_stone,
  22. }
  23. end
  24. end)
  25. -- loss probabilities array (one in X will be lost)
  26. local stack_loss_prob = {}
  27. stack_loss_prob["default:cobble"] = 4
  28. stack_loss_prob["rackstone:redrack"] = 4
  29. stack_loss_prob["default:ice"] = 4
  30. local function rand_pos(center, pos, radius)
  31. pos.x = center.x + math_random(-radius, radius)
  32. pos.z = center.z + math_random(-radius, radius)
  33. -- Keep picking random positions until a position inside the sphere is chosen.
  34. -- This gives us a uniform (flattened) spherical distribution.
  35. while vector_distance(center, pos) >= radius do
  36. pos.x = center.x + math_random(-radius, radius)
  37. pos.z = center.z + math_random(-radius, radius)
  38. end
  39. end
  40. local function eject_drops(drops, pos, radius)
  41. local drop_pos = vector.new(pos)
  42. for _, item in pairs(drops) do
  43. local count = math_min(item:get_count(), item:get_stack_max())
  44. while count > 0 do
  45. local take = math_max(1, math_min(radius * radius, count, item:get_stack_max()))
  46. rand_pos(pos, drop_pos, radius*0.9)
  47. local dropitem = ItemStack(item)
  48. dropitem:set_count(take)
  49. local obj = minetest.add_item(drop_pos, dropitem)
  50. if obj then
  51. obj:get_luaentity().collect = true
  52. obj:set_acceleration({x = 0, y = -10, z = 0})
  53. obj:set_velocity({x = math_random(-3, 3), y = math_random(0, 10), z = math_random(-3, 3)})
  54. droplift.invoke(obj, math_random(3, 10))
  55. end
  56. count = count - take
  57. end
  58. end
  59. end
  60. local function add_drop(drops, item)
  61. -- Make sure it's an item stack.
  62. item = ItemStack(item)
  63. local name = item:get_name()
  64. -- Deal with trash.
  65. if stack_loss_prob[name] ~= nil and math_random(1, stack_loss_prob[name]) == 1 then
  66. return
  67. end
  68. local drop = drops[name]
  69. if drop == nil then
  70. drops[name] = item
  71. else
  72. -- Note: this should NOT get clamped by stack_max anymore.
  73. drop:set_count(drop:get_count() + item:get_count())
  74. end
  75. end
  76. local function destroy(drops, npos, cid, c_air, c_fire, on_blast_queue, on_destruct_queue, on_after_destruct_queue, fire_locations, ignore_protection, ignore_on_blast, pname)
  77. -- This, right here, is probably what slows TNT code down the most.
  78. -- Perhaps we can avoid the issue by not allowing TNT to be placed within
  79. -- a hundred meters of a city block?
  80. -- Must also consider: explosions caused by mobs, arrows, other code ...
  81. -- Idea: TNT blasts ignore protection, but TNT can only be placed away from
  82. -- cityblocks. Explosions from mobs and arrows respect protection as usual.
  83. if not ignore_protection then
  84. if minetest.test_protection(npos, pname) then
  85. return cid
  86. end
  87. end
  88. local def = cid_data[cid]
  89. if not def then
  90. return c_air
  91. end
  92. if def.on_destruct then
  93. -- Queue on_destruct callbacks only if ignoring on_blast.
  94. if ignore_on_blast or not def.on_blast then
  95. on_destruct_queue[#on_destruct_queue+1] = {
  96. pos = vector.new(npos),
  97. on_destruct = def.on_destruct,
  98. }
  99. end
  100. end
  101. if def.after_destruct then
  102. -- Queue after_destruct callbacks only if ignoring on_blast.
  103. if ignore_on_blast or not def.on_blast then
  104. on_after_destruct_queue[#on_after_destruct_queue+1] = {
  105. pos = vector.new(npos),
  106. after_destruct = def.after_destruct,
  107. oldnode = minetest.get_node(npos),
  108. }
  109. end
  110. end
  111. if not ignore_on_blast and def.on_blast then
  112. on_blast_queue[#on_blast_queue + 1] = {
  113. pos = vector.new(npos),
  114. on_blast = def.on_blast,
  115. }
  116. return cid
  117. elseif def.flammable then
  118. fire_locations[#fire_locations+1] = vector.new(npos)
  119. return c_fire
  120. elseif def._is_bulk_mapgen_stone then
  121. -- Ignore drops.
  122. return c_air
  123. elseif def._tnt_drop then
  124. local t = type(def._tnt_drop)
  125. if t == "string" then
  126. add_drop(drops, def._tnt_drop)
  127. elseif t == "table" then
  128. local b = def._tnt_drop
  129. for k = 1, #b do
  130. add_drop(drops, b[k])
  131. end
  132. end
  133. return c_air
  134. else
  135. local node_drops = minetest.get_node_drops(def.name, "")
  136. for k = 1, #node_drops do
  137. add_drop(drops, node_drops[k])
  138. end
  139. return c_air
  140. end
  141. end
  142. local function calc_velocity(pos1, pos2, old_vel, power)
  143. -- Avoid errors caused by a vector of zero length
  144. if vector.equals(pos1, pos2) then
  145. return old_vel
  146. end
  147. local vel = vector.direction(pos1, pos2)
  148. vel = vector.normalize(vel)
  149. vel = vector.multiply(vel, power)
  150. -- Divide by distance
  151. local dist = vector_distance(pos1, pos2)
  152. dist = math_max(dist, 1)
  153. vel = vector.divide(vel, dist)
  154. -- Add old velocity
  155. vel = vector.add(vel, old_vel)
  156. -- randomize it a bit
  157. vel = vector.add(vel, {
  158. x = math_random() - 0.5,
  159. y = math_random() - 0.5,
  160. z = math_random() - 0.5,
  161. })
  162. -- Limit to terminal velocity
  163. dist = vector.length(vel)
  164. if dist > 250 then
  165. vel = vector.divide(vel, dist / 250)
  166. end
  167. return vel
  168. end
  169. local function entity_physics(pos, radius, drops, boomdef)
  170. local objs = minetest.get_objects_inside_radius(pos, radius)
  171. for _, obj in pairs(objs) do
  172. local obj_pos = obj:get_pos()
  173. local dist = math_max(1, vector_distance(pos, obj_pos))
  174. -- Calculate damage to be applied to player or mob.
  175. local SCALE = 500
  176. local damage = ((8 / dist) * radius) * SCALE
  177. if obj:is_player() then
  178. local pname = obj:get_player_name()
  179. -- Admin is exempt from TNT blasts.
  180. if not gdac.player_is_admin(obj) then
  181. -- Damage player. For reasons having to do with bone placement, this
  182. -- needs to happen before any knockback effects. And knockback effects
  183. -- should only be applied if the player does not actually die.
  184. if obj:get_hp() > 0 then
  185. local dg = {
  186. boom = damage,
  187. }
  188. local hitter = obj
  189. -- If tnt was launched by a player, use them as the hitter.
  190. if boomdef.name and boomdef.name ~= "" and boomdef.from_arrow then
  191. dg.from_arrow = 0
  192. local pref = minetest.get_player_by_name(boomdef.name)
  193. if pref then
  194. hitter = pref
  195. end
  196. end
  197. armor.notify_punch_reason({reason="boom"})
  198. obj:punch(hitter, 1.0, {
  199. full_punch_interval = 1.0,
  200. max_drop_level = 0,
  201. damage_groups = dg,
  202. }, nil)
  203. if obj:get_hp() <= 0 then
  204. if player_labels.query_nametag_onoff(pname) == true and not cloaking.is_cloaked(pname) then
  205. minetest.chat_send_all("# Server: <" .. rename.gpn(pname) .. "> exploded.")
  206. else
  207. minetest.chat_send_all("# Server: Someone exploded.")
  208. end
  209. end
  210. end
  211. -- Do knockback only if player didn't die.
  212. if obj:get_hp() > 0 then
  213. -- HACK: do not apply knockback if the player is in a duel.
  214. -- This has a HIGH chance of causing fall damage leading to death, which would
  215. -- bypass the duel!
  216. -- This check is needed because it is way too easy to kill someone by fall damage
  217. -- when using TNT arrows.
  218. if not armor.dueling_players[obj:get_player_name()] then
  219. local dir = vector.normalize(vector.subtract(obj_pos, pos))
  220. local moveoff = vector.multiply(dir, 2 / dist * radius)
  221. moveoff = vector.multiply(moveoff, 3)
  222. moveoff.y = math.min(math.abs(moveoff.y), 20)
  223. obj:add_player_velocity(moveoff)
  224. end
  225. end
  226. end
  227. else
  228. local do_damage = true
  229. local do_knockback = true
  230. local entity_drops = {}
  231. local luaobj = obj:get_luaentity()
  232. -- Ignore mobs of the same type as the one that launched the TNT boom.
  233. local ignore = false
  234. if boomdef.mob and luaobj.mob and boomdef.mob == luaobj.name then
  235. ignore = true
  236. end
  237. if not ignore then
  238. local objdef = minetest.registered_entities[luaobj.name]
  239. if objdef and objdef.on_blast then
  240. do_damage, do_knockback, entity_drops = objdef.on_blast(luaobj, damage)
  241. end
  242. if do_knockback then
  243. local obj_vel = obj:get_velocity()
  244. obj:set_velocity(calc_velocity(pos, obj_pos,
  245. obj_vel, radius * 10))
  246. end
  247. if do_damage then
  248. if not obj:get_armor_groups().immortal then
  249. obj:punch(obj, 1.0, {
  250. full_punch_interval = 1.0,
  251. damage_groups = {boom = damage},
  252. }, nil)
  253. end
  254. end
  255. for k = 1, #entity_drops do
  256. add_drop(drops, entity_drops[k])
  257. end
  258. end
  259. end
  260. end
  261. end
  262. local function add_effects(pos, radius, drops)
  263. minetest.add_particle({
  264. pos = pos,
  265. velocity = vector.new(),
  266. acceleration = vector.new(),
  267. expirationtime = 0.4,
  268. size = radius * 10,
  269. collisiondetection = false,
  270. vertical = false,
  271. texture = "tnt_boom.png",
  272. })
  273. minetest.add_particlespawner({
  274. amount = 64,
  275. time = 0.5,
  276. minpos = vector.subtract(pos, radius / 2),
  277. maxpos = vector.add(pos, radius / 2),
  278. minvel = {x = -10, y = -10, z = -10},
  279. maxvel = {x = 10, y = 10, z = 10},
  280. minacc = vector.new(),
  281. maxacc = vector.new(),
  282. minexptime = 1,
  283. maxexptime = 2.5,
  284. minsize = radius * 3,
  285. maxsize = radius * 5,
  286. texture = "tnt_smoke.png",
  287. })
  288. -- we just dropped some items. Look at the items entities and pick
  289. -- one of them to use as texture
  290. local texture = "tnt_blast.png" --fallback texture
  291. local most = 0
  292. for name, count in pairs(drops) do
  293. --local count = stack:get_count()
  294. if count > most then
  295. most = count
  296. local def = minetest.registered_nodes[name]
  297. if def and def.tiles and def.tiles[1] then
  298. if type(def.tiles[1]) == "string" then
  299. texture = def.tiles[1]
  300. end
  301. end
  302. end
  303. end
  304. minetest.add_particlespawner({
  305. amount = 64,
  306. time = 0.1,
  307. minpos = vector.subtract(pos, radius / 2),
  308. maxpos = vector.add(pos, radius / 2),
  309. minvel = {x = -3, y = 0, z = -3},
  310. maxvel = {x = 3, y = 5, z = 3},
  311. minacc = {x = 0, y = -10, z = 0},
  312. maxacc = {x = 0, y = -10, z = 0},
  313. minexptime = 0.8,
  314. maxexptime = 2.0,
  315. minsize = radius * 0.66,
  316. maxsize = radius * 2,
  317. texture = texture,
  318. collisiondetection = true,
  319. })
  320. end
  321. -- Quickly check for protection in an area.
  322. local function check_protection(pos, radius, pname)
  323. -- How much beyond the radius to check for protections.
  324. local e = 10
  325. local minp = vector.new(pos.x-(radius+e), pos.y-(radius+e), pos.z-(radius+e))
  326. local maxp = vector.new(pos.x+(radius+e), pos.y+(radius+e), pos.z+(radius+e))
  327. -- Step size, to avoid checking every single node.
  328. -- This assumes protections cannot be smaller than this size.
  329. local ss = 5
  330. local check = minetest.test_protection
  331. for x=minp.x, maxp.x, ss do
  332. for y=minp.y, maxp.y, ss do
  333. for z=minp.z, maxp.z, ss do
  334. if check({x=x, y=y, z=z}, pname) then
  335. -- Protections are present.
  336. return true
  337. end
  338. end
  339. end
  340. end
  341. -- Nothing in the area is protected.
  342. return false
  343. end
  344. local function tnt_explode(pos, radius, ignore_protection, ignore_on_blast, pname, protection_name)
  345. pos = vector_round(pos)
  346. -- scan for adjacent TNT nodes first, and enlarge the explosion
  347. local vm1 = VoxelManip()
  348. local p1 = vector.subtract(pos, 3)
  349. local p2 = vector.add(pos, 3)
  350. local minp, maxp = vm1:read_from_map(p1, p2)
  351. local a = VoxelArea:new({MinEdge = minp, MaxEdge = maxp})
  352. local data = vm1:get_data()
  353. local count = 0
  354. local c_tnt = minetest.get_content_id("tnt:tnt")
  355. local c_tnt_burning = minetest.get_content_id("tnt:tnt_burning")
  356. local c_tnt_boom = minetest.get_content_id("tnt:boom")
  357. local c_air = minetest.get_content_id("air")
  358. for z = pos.z - 3, pos.z + 3 do
  359. for y = pos.y - 3, pos.y + 3 do
  360. for x = pos.x - 3, pos.x + 3 do
  361. local vi = a:index(x, y, z)
  362. local cid = data[vi]
  363. if cid == c_tnt or cid == c_tnt_boom or cid == c_tnt_burning then
  364. count = count + 1
  365. data[vi] = c_air
  366. end
  367. end
  368. end
  369. end
  370. -- The variable 'count' may be 0 if the bomb exploded in a protected area. In
  371. -- which case no "tnt boom" flash (node) will have been created. Clamping
  372. -- 'count' to a minimum of 1 fixes the problem.
  373. -- [MustTest]
  374. if count < 1 then
  375. count = 1
  376. end
  377. -- Clamp to avoid massive explosions.
  378. if count > 64 then count = 64 end
  379. vm1:set_data(data)
  380. vm1:write_to_map()
  381. -- recalculate new radius
  382. radius = math_floor(radius * math.pow(count, 0.60))
  383. -- If no protections are present, we can optimize by skipping the protection
  384. -- check for individual nodes. If we have a small radius, then don't bother.
  385. if radius > 8 then
  386. if not check_protection(pos, radius, protection_name) then
  387. ignore_protection = true
  388. end
  389. end
  390. -- perform the explosion
  391. local vm = VoxelManip()
  392. local pr = PseudoRandom(os.time())
  393. p1 = vector.subtract(pos, radius)
  394. p2 = vector.add(pos, radius)
  395. minp, maxp = vm:read_from_map(p1, p2)
  396. a = VoxelArea:new({MinEdge = minp, MaxEdge = maxp})
  397. data = vm:get_data()
  398. local drops = {}
  399. local on_blast_queue = {}
  400. local on_destruct_queue = {}
  401. local on_after_destruct_queue = {}
  402. local fire_locations = {}
  403. local c_fire = minetest.get_content_id("fire:basic_flame")
  404. for z = -radius, radius do
  405. for y = -radius, radius do
  406. local vi = a:index(pos.x + (-radius), pos.y + y, pos.z + z)
  407. for x = -radius, radius do
  408. local r = vector.length(vector.new(x, y, z))
  409. local r2 = radius
  410. -- Roughen the walls a bit.
  411. if pr:next(0, 6) == 0 then
  412. r2 = radius - 0.8
  413. end
  414. if r <= r2 then
  415. local cid = data[vi]
  416. local p = {x = pos.x + x, y = pos.y + y, z = pos.z + z}
  417. if cid ~= c_air then
  418. data[vi] = destroy(drops, p, cid, c_air, c_fire,
  419. on_blast_queue, on_destruct_queue, on_after_destruct_queue,
  420. fire_locations, ignore_protection, ignore_on_blast, protection_name)
  421. end
  422. end
  423. vi = vi + 1
  424. end
  425. end
  426. end
  427. -- Call on_destruct callbacks.
  428. for k = 1, #on_destruct_queue do
  429. local v = on_destruct_queue[k]
  430. v.on_destruct(v.pos)
  431. end
  432. vm:set_data(data)
  433. vm:write_to_map()
  434. vm:update_map()
  435. vm:update_liquids()
  436. -- Check unstable nodes for everything within blast effect.
  437. local minr = {x=pos.x-(radius+2), y=pos.y-(radius+2), z=pos.z-(radius+2)}
  438. local maxr = {x=pos.x+(radius+2), y=pos.y+(radius+2), z=pos.z+(radius+2)}
  439. for z=minr.z, maxr.z do
  440. for x=minr.x, maxr.x do
  441. for y=minr.y, maxr.y do
  442. local p = {x=x, y=y, z=z}
  443. local d = vector_distance(pos, p)
  444. if d < radius+2 and d > radius-2 then
  445. -- Check for nodes with 'falling_node' in groups.
  446. minetest.check_single_for_falling(p)
  447. -- Now check using additional falling node logic.
  448. instability.check_unsupported_single(p)
  449. end
  450. end
  451. end
  452. end
  453. -- Execute after-destruct callbacks.
  454. for k = 1, #on_after_destruct_queue do
  455. local v = on_after_destruct_queue[k]
  456. v.after_destruct(v.pos, v.oldnode)
  457. end
  458. for k = 1, #on_blast_queue do
  459. local queued_data = on_blast_queue[k]
  460. local dist = math_max(1, vector_distance(queued_data.pos, pos))
  461. local intensity = (radius * radius) / (dist * dist)
  462. local node_drops = queued_data.on_blast(queued_data.pos, intensity)
  463. if node_drops then
  464. for j = 1, #node_drops do
  465. add_drop(drops, node_drops[j])
  466. end
  467. end
  468. end
  469. -- Initialize flames.
  470. local fdef = minetest.registered_nodes["fire:basic_flame"]
  471. if fdef and fdef.on_construct then
  472. for k = 1, #fire_locations do
  473. fdef.on_construct(fire_locations[k])
  474. end
  475. end
  476. return drops, radius
  477. end
  478. --[[
  479. {
  480. radius,
  481. ignore_protection,
  482. ignore_on_blast,
  483. damage_radius,
  484. disable_drops,
  485. name, -- Name to use when testing protection. Defaults to "".
  486. }
  487. --]]
  488. function tnt.boom(pos, def)
  489. pos = vector_round(pos)
  490. -- The TNT code crashes sometimes, for no particular reason?
  491. local func = function()
  492. tnt.boom_impl(pos, def)
  493. end
  494. pcall(func)
  495. end
  496. -- Not to be called externally.
  497. function tnt.boom_impl(pos, def)
  498. if def.make_sound == nil or def.make_sound == true then
  499. minetest.sound_play("tnt_explode", {pos = pos, gain = 1.5, max_hear_distance = 2*64}, true)
  500. end
  501. -- Make sure TNT never somehow gets keyed to the admin!
  502. if def.name and gdac.player_is_admin(def.name) then
  503. def.name = nil
  504. end
  505. if def.protection_name and gdac.player_is_admin(def.protection_name) then
  506. def.protection_name = nil
  507. end
  508. if not minetest.test_protection(pos, "") then
  509. local node = minetest.get_node(pos)
  510. -- Never destroy death boxes.
  511. if node.name ~= "bones:bones" then
  512. minetest.set_node(pos, {name = "tnt:boom"})
  513. end
  514. end
  515. local drops, radius = tnt_explode(pos, def.radius, def.ignore_protection,
  516. def.ignore_on_blast, (def.name or ""), (def.protection_name or ""))
  517. -- append entity drops
  518. local damage_radius = (radius / def.radius) * def.damage_radius
  519. entity_physics(pos, damage_radius, drops, def)
  520. if not def.disable_drops then
  521. eject_drops(drops, pos, radius)
  522. end
  523. add_effects(pos, radius, drops)
  524. minetest.log("action", "A TNT explosion occurred at " .. minetest.pos_to_string(pos) ..
  525. " with radius " .. radius)
  526. end