tnt_boom.lua 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  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, 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. 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. -- Admin is exempt from TNT blasts.
  164. if not gdac.player_is_admin(obj) then
  165. -- Damage player. For reasons having to do with bone placement, this
  166. -- needs to happen before any knockback effects. And knockback effects
  167. -- should only be applied if the player does not actually die.
  168. if obj:get_hp() > 0 then
  169. obj:set_hp(obj:get_hp() - damage)
  170. if obj:get_hp() <= 0 then
  171. local pname = obj:get_player_name()
  172. if player_labels.query_nametag_onoff(pname) == true and not cloaking.is_cloaked(pname) then
  173. minetest.chat_send_all("# Server: <" .. rename.gpn(pname) .. "> exploded.")
  174. else
  175. minetest.chat_send_all("# Server: Someone exploded.")
  176. end
  177. end
  178. end
  179. -- Do knockback only if player didn't die.
  180. if obj:get_hp() > 0 then
  181. local dir = vector.normalize(vector.subtract(obj_pos, pos))
  182. local moveoff = vector.multiply(dir, 2 / dist * radius)
  183. moveoff = vector.multiply(moveoff, 3)
  184. obj:add_player_velocity(moveoff)
  185. end
  186. end
  187. else
  188. local do_damage = true
  189. local do_knockback = true
  190. local entity_drops = {}
  191. local luaobj = obj:get_luaentity()
  192. -- Ignore mobs of the same type as the one that launched the TNT boom.
  193. local ignore = false
  194. if boomdef.mob and luaobj.mob and boomdef.mob == luaobj.name then
  195. ignore = true
  196. end
  197. if not ignore then
  198. local objdef = minetest.registered_entities[luaobj.name]
  199. if objdef and objdef.on_blast then
  200. do_damage, do_knockback, entity_drops = objdef.on_blast(luaobj, damage)
  201. end
  202. if do_knockback then
  203. local obj_vel = obj:getvelocity()
  204. obj:setvelocity(calc_velocity(pos, obj_pos,
  205. obj_vel, radius * 10))
  206. end
  207. if do_damage then
  208. if not obj:get_armor_groups().immortal then
  209. obj:punch(obj, 1.0, {
  210. full_punch_interval = 1.0,
  211. damage_groups = {fleshy = damage},
  212. }, nil)
  213. end
  214. end
  215. for _, item in ipairs(entity_drops) do
  216. add_drop(drops, item)
  217. end
  218. end
  219. end
  220. end
  221. end
  222. local function add_effects(pos, radius, drops)
  223. minetest.add_particle({
  224. pos = pos,
  225. velocity = vector.new(),
  226. acceleration = vector.new(),
  227. expirationtime = 0.4,
  228. size = radius * 10,
  229. collisiondetection = false,
  230. vertical = false,
  231. texture = "tnt_boom.png",
  232. })
  233. minetest.add_particlespawner({
  234. amount = 64,
  235. time = 0.5,
  236. minpos = vector.subtract(pos, radius / 2),
  237. maxpos = vector.add(pos, radius / 2),
  238. minvel = {x = -10, y = -10, z = -10},
  239. maxvel = {x = 10, y = 10, z = 10},
  240. minacc = vector.new(),
  241. maxacc = vector.new(),
  242. minexptime = 1,
  243. maxexptime = 2.5,
  244. minsize = radius * 3,
  245. maxsize = radius * 5,
  246. texture = "tnt_smoke.png",
  247. })
  248. -- we just dropped some items. Look at the items entities and pick
  249. -- one of them to use as texture
  250. local texture = "tnt_blast.png" --fallback texture
  251. local most = 0
  252. for name, count in pairs(drops) do
  253. --local count = stack:get_count()
  254. if count > most then
  255. most = count
  256. local def = minetest.registered_nodes[name]
  257. if def and def.tiles and def.tiles[1] then
  258. if type(def.tiles[1]) == "string" then
  259. texture = def.tiles[1]
  260. end
  261. end
  262. end
  263. end
  264. minetest.add_particlespawner({
  265. amount = 64,
  266. time = 0.1,
  267. minpos = vector.subtract(pos, radius / 2),
  268. maxpos = vector.add(pos, radius / 2),
  269. minvel = {x = -3, y = 0, z = -3},
  270. maxvel = {x = 3, y = 5, z = 3},
  271. minacc = {x = 0, y = -10, z = 0},
  272. maxacc = {x = 0, y = -10, z = 0},
  273. minexptime = 0.8,
  274. maxexptime = 2.0,
  275. minsize = radius * 0.66,
  276. maxsize = radius * 2,
  277. texture = texture,
  278. collisiondetection = true,
  279. })
  280. end
  281. -- Quickly check for protection in an area.
  282. local function check_protection(pos, radius, pname)
  283. -- How much beyond the radius to check for protections.
  284. local e = 10
  285. local minp = vector.new(pos.x-(radius+e), pos.y-(radius+e), pos.z-(radius+e))
  286. local maxp = vector.new(pos.x+(radius+e), pos.y+(radius+e), pos.z+(radius+e))
  287. -- Step size, to avoid checking every single node.
  288. -- This assumes protections cannot be smaller than this size.
  289. local ss = 5
  290. local check = minetest.test_protection
  291. for x=minp.x, maxp.x, ss do
  292. for y=minp.y, maxp.y, ss do
  293. for z=minp.z, maxp.z, ss do
  294. if check({x=x, y=y, z=z}, pname) then
  295. -- Protections are present.
  296. return true
  297. end
  298. end
  299. end
  300. end
  301. -- Nothing in the area is protected.
  302. return false
  303. end
  304. local function tnt_explode(pos, radius, ignore_protection, ignore_on_blast, pname)
  305. pos = vector_round(pos)
  306. -- scan for adjacent TNT nodes first, and enlarge the explosion
  307. local vm1 = VoxelManip()
  308. local p1 = vector.subtract(pos, 2)
  309. local p2 = vector.add(pos, 2)
  310. local minp, maxp = vm1:read_from_map(p1, p2)
  311. local a = VoxelArea:new({MinEdge = minp, MaxEdge = maxp})
  312. local data = vm1:get_data()
  313. local count = 0
  314. local c_tnt = minetest.get_content_id("tnt:tnt")
  315. local c_tnt_burning = minetest.get_content_id("tnt:tnt_burning")
  316. local c_tnt_boom = minetest.get_content_id("tnt:boom")
  317. local c_air = minetest.get_content_id("air")
  318. for z = pos.z - 2, pos.z + 2 do
  319. for y = pos.y - 2, pos.y + 2 do
  320. local vi = a:index(pos.x - 2, y, z)
  321. for x = pos.x - 2, pos.x + 2 do
  322. local cid = data[vi]
  323. if cid == c_tnt or cid == c_tnt_boom or cid == c_tnt_burning then
  324. count = count + 1
  325. data[vi] = c_air
  326. end
  327. vi = vi + 1
  328. end
  329. end
  330. end
  331. -- 'count' may be 0 if the bomb exploded in a protected area -- in which case no tnt boom
  332. -- will have been created. Clamping 'count' to a minimum of 1 fixes the problem.
  333. -- [MustTest]
  334. if count < 1 then
  335. count = 1
  336. end
  337. -- Clamp to avoid massive explosions.
  338. if count > 64 then count = 64 end
  339. vm1:set_data(data)
  340. vm1:write_to_map()
  341. -- recalculate new radius
  342. radius = math_floor(radius * math.pow(count, 0.60))
  343. -- If no protections are present, we can optimize by skipping the protection
  344. -- check for individual nodes. If we have a small radius, then don't bother.
  345. if radius > 8 then
  346. if not check_protection(pos, radius, pname) then
  347. ignore_protection = true
  348. end
  349. end
  350. -- perform the explosion
  351. local vm = VoxelManip()
  352. local pr = PseudoRandom(os.time())
  353. p1 = vector.subtract(pos, radius)
  354. p2 = vector.add(pos, radius)
  355. minp, maxp = vm:read_from_map(p1, p2)
  356. a = VoxelArea:new({MinEdge = minp, MaxEdge = maxp})
  357. data = vm:get_data()
  358. local drops = {}
  359. local on_blast_queue = {}
  360. local on_destruct_queue = {}
  361. local on_after_destruct_queue = {}
  362. local fire_locations = {}
  363. local c_fire = minetest.get_content_id("fire:basic_flame")
  364. for z = -radius, radius do
  365. for y = -radius, radius do
  366. local vi = a:index(pos.x + (-radius), pos.y + y, pos.z + z)
  367. for x = -radius, radius do
  368. local r = vector.length(vector.new(x, y, z))
  369. local r2 = radius
  370. -- Roughen the walls a bit.
  371. if pr:next(0, 6) == 0 then
  372. r2 = radius - 0.8
  373. end
  374. if r <= r2 then
  375. local cid = data[vi]
  376. local p = {x = pos.x + x, y = pos.y + y, z = pos.z + z}
  377. if cid ~= c_air then
  378. data[vi] = destroy(drops, p, cid, c_air, c_fire,
  379. on_blast_queue, on_destruct_queue, on_after_destruct_queue,
  380. fire_locations, ignore_protection, ignore_on_blast, pname)
  381. end
  382. end
  383. vi = vi + 1
  384. end
  385. end
  386. end
  387. -- Call on_destruct callbacks.
  388. for k, v in ipairs(on_destruct_queue) do
  389. v.on_destruct(v.pos)
  390. end
  391. vm:set_data(data)
  392. vm:write_to_map()
  393. vm:update_map()
  394. vm:update_liquids()
  395. -- Check unstable nodes for everything within blast effect.
  396. local minr = {x=pos.x-(radius+2), y=pos.y-(radius+2), z=pos.z-(radius+2)}
  397. local maxr = {x=pos.x+(radius+2), y=pos.y+(radius+2), z=pos.z+(radius+2)}
  398. for z=minr.z, maxr.z do
  399. for x=minr.x, maxr.x do
  400. for y=minr.y, maxr.y do
  401. local p = {x=x, y=y, z=z}
  402. local d = vector_distance(pos, p)
  403. if d < radius+2 and d > radius-2 then
  404. -- Check for nodes with 'falling_node' in groups.
  405. minetest.check_single_for_falling(p)
  406. -- Now check using additional falling node logic.
  407. instability.check_unsupported_single(p)
  408. end
  409. end
  410. end
  411. end
  412. -- Execute after-destruct callbacks.
  413. for k, v in ipairs(on_after_destruct_queue) do
  414. v.after_destruct(v.pos, v.oldnode)
  415. end
  416. for _, queued_data in ipairs(on_blast_queue) do
  417. local dist = math_max(1, vector_distance(queued_data.pos, pos))
  418. local intensity = (radius * radius) / (dist * dist)
  419. local node_drops = queued_data.on_blast(queued_data.pos, intensity)
  420. if node_drops then
  421. for _, item in ipairs(node_drops) do
  422. add_drop(drops, item)
  423. end
  424. end
  425. end
  426. -- Initialize flames.
  427. local fdef = minetest.registered_nodes["fire:basic_flame"]
  428. if fdef and fdef.on_construct then
  429. for k, v in ipairs(fire_locations) do
  430. fdef.on_construct(v)
  431. end
  432. end
  433. return drops, radius
  434. end
  435. --[[
  436. {
  437. radius,
  438. ignore_protection,
  439. ignore_on_blast,
  440. damage_radius,
  441. disable_drops,
  442. name, -- Name to use when testing protection. Defaults to "".
  443. }
  444. --]]
  445. function tnt.boom(pos, def)
  446. pos = vector_round(pos)
  447. -- The TNT code crashes sometimes, for no particular reason?
  448. local func = function()
  449. tnt.boom_impl(pos, def)
  450. end
  451. pcall(func)
  452. end
  453. -- Not to be called externally.
  454. function tnt.boom_impl(pos, def)
  455. if def.make_sound == nil or def.make_sound == true then
  456. minetest.sound_play("tnt_explode", {pos = pos, gain = 1.5, max_hear_distance = 2*64})
  457. end
  458. -- Make sure TNT never somehow gets keyed to the admin!
  459. if def.name and def.name == "MustTest" then
  460. def.name = nil
  461. end
  462. if not minetest.test_protection(pos, "") then
  463. local node = minetest.get_node(pos)
  464. -- Never destroy death boxes.
  465. if node.name ~= "bones:bones" then
  466. minetest.set_node(pos, {name = "tnt:boom"})
  467. end
  468. end
  469. local drops, radius = tnt_explode(pos, def.radius, def.ignore_protection, def.ignore_on_blast, def.name or "")
  470. -- append entity drops
  471. local damage_radius = (radius / def.radius) * def.damage_radius
  472. entity_physics(pos, damage_radius, drops, def)
  473. if not def.disable_drops then
  474. eject_drops(drops, pos, radius)
  475. end
  476. add_effects(pos, radius, drops)
  477. minetest.log("action", "A TNT explosion occurred at " .. minetest.pos_to_string(pos) ..
  478. " with radius " .. radius)
  479. end