tnt_boom.lua 17 KB

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