TNT: Combine adjacent TNT into the explosion
[oweals/minetest_game.git] / mods / tnt / init.lua
1 tnt = {}
2 -- Default to enabled in singleplayer and disabled in multiplayer
3 local singleplayer = minetest.is_singleplayer()
4 local setting = minetest.setting_getbool("enable_tnt")
5 if (not singleplayer and setting ~= true) or
6                 (singleplayer and setting == false) then
7         return
8 end
9
10 -- loss probabilities array (one in X will be lost)
11 local loss_prob = {}
12
13 loss_prob["default:cobble"] = 3
14 loss_prob["default:dirt"] = 4
15
16 local radius = tonumber(minetest.setting_get("tnt_radius") or 3)
17
18 -- Fill a list with data for content IDs, after all nodes are registered
19 local cid_data = {}
20 minetest.after(0, function()
21         for name, def in pairs(minetest.registered_nodes) do
22                 cid_data[minetest.get_content_id(name)] = {
23                         name = name,
24                         drops = def.drops,
25                         flammable = def.groups.flammable,
26                         on_blast = def.on_blast,
27                 }
28         end
29 end)
30
31 local function rand_pos(center, pos, radius)
32         local def
33         local reg_nodes = minetest.registered_nodes
34         local i = 0
35         repeat
36                 -- Give up and use the center if this takes too long
37                 if i > 4 then
38                         pos.x, pos.z = center.x, center.z
39                         break
40                 end
41                 pos.x = center.x + math.random(-radius, radius)
42                 pos.z = center.z + math.random(-radius, radius)
43                 def = reg_nodes[minetest.get_node(pos).name]
44                 i = i + 1
45         until def and not def.walkable
46 end
47
48 local function eject_drops(drops, pos, radius)
49         local drop_pos = vector.new(pos)
50         for _, item in pairs(drops) do
51                 local count = item:get_count()
52                 while count > 0 do
53                         local take = math.max(1,math.min(radius * radius,
54                                         item:get_count(),
55                                         item:get_stack_max()))
56                         rand_pos(pos, drop_pos, radius)
57                         local dropitem = ItemStack(item)
58                         dropitem:set_count(take)
59                         local obj = minetest.add_item(drop_pos, dropitem)
60                         if obj then
61                                 obj:get_luaentity().collect = true
62                                 obj:setacceleration({x = 0, y = -10, z = 0})
63                                 obj:setvelocity({x = math.random(-3, 3),
64                                                 y = math.random(0, 10),
65                                                 z = math.random(-3, 3)})
66                         end
67                         count = count - take
68                 end
69         end
70 end
71
72 local function add_drop(drops, item)
73         item = ItemStack(item)
74         local name = item:get_name()
75         if loss_prob[name] ~= nil and math.random(1, loss_prob[name]) == 1 then
76                 return
77         end
78
79         local drop = drops[name]
80         if drop == nil then
81                 drops[name] = item
82         else
83                 drop:set_count(drop:get_count() + item:get_count())
84         end
85 end
86
87
88 local function destroy(drops, npos, cid, c_air, c_fire, on_blast_queue, ignore_protection, ignore_on_blast)
89         if not ignore_protection and minetest.is_protected(npos, "") then
90                 return cid
91         end
92
93         local def = cid_data[cid]
94
95         if not def then
96                 return c_air
97         elseif not ignore_on_blast and def.on_blast then
98                 on_blast_queue[#on_blast_queue + 1] = {pos = vector.new(npos), on_blast = def.on_blast}
99                 return cid
100         elseif def.flammable then
101                 return c_fire
102         else
103                 local node_drops = minetest.get_node_drops(def.name, "")
104                 for _, item in ipairs(node_drops) do
105                         add_drop(drops, item)
106                 end
107                 return c_air
108         end
109 end
110
111
112 local function calc_velocity(pos1, pos2, old_vel, power)
113         local vel = vector.direction(pos1, pos2)
114         vel = vector.normalize(vel)
115         vel = vector.multiply(vel, power)
116
117         -- Divide by distance
118         local dist = vector.distance(pos1, pos2)
119         dist = math.max(dist, 1)
120         vel = vector.divide(vel, dist)
121
122         -- Add old velocity
123         vel = vector.add(vel, old_vel)
124
125         -- randomize it a bit
126         vel = vector.add(vel, {
127                 x = math.random() - 0.5,
128                 y = math.random() - 0.5,
129                 z = math.random() - 0.5,
130         })
131
132         -- Limit to terminal velocity
133         dist = vector.length(vel)
134         if dist > 250 then
135                 vel = vector.divide(vel, dist / 250)
136         end
137         return vel
138 end
139
140 local function entity_physics(pos, radius, drops)
141         local objs = minetest.get_objects_inside_radius(pos, radius)
142         for _, obj in pairs(objs) do
143                 local obj_pos = obj:getpos()
144                 local dist = math.max(1, vector.distance(pos, obj_pos))
145
146                 local damage = (4 / dist) * radius
147                 if obj:is_player() then
148                         -- currently the engine has no method to set
149                         -- player velocity. See #2960
150                         -- instead, we knock the player back 1.0 node, and slightly upwards
151                         local dir = vector.normalize(vector.subtract(obj_pos, pos))
152                         local moveoff = vector.multiply(dir, dist + 1.0)
153                         local newpos = vector.add(pos, moveoff)
154                         local newpos = vector.add(newpos, {x = 0, y = 0.2, z = 0})
155                         obj:setpos(newpos)
156
157                         obj:set_hp(obj:get_hp() - damage)
158                 else
159                         local do_damage = true
160                         local do_knockback = true
161                         local entity_drops = {}
162                         local luaobj = obj:get_luaentity()
163                         local objdef = minetest.registered_entities[luaobj.name]
164
165                         if objdef and objdef.on_blast then
166                                 do_damage, do_knockback, entity_drops = objdef.on_blast(luaobj, damage)
167                         end
168
169                         if do_knockback then
170                                 local obj_vel = obj:getvelocity()
171                                 obj:setvelocity(calc_velocity(pos, obj_pos,
172                                                 obj_vel, radius * 10))
173                         end
174                         if do_damage then
175                                 if not obj:get_armor_groups().immortal then
176                                         obj:punch(obj, 1.0, {
177                                                 full_punch_interval = 1.0,
178                                                 damage_groups = {fleshy = damage},
179                                         }, nil)
180                                 end
181                         end
182                         for _, item in ipairs(entity_drops) do
183                                 add_drop(drops, item)
184                         end
185                 end
186         end
187 end
188
189 local function add_effects(pos, radius, drops)
190         minetest.add_particle({
191                 pos = pos,
192                 velocity = vector.new(),
193                 acceleration = vector.new(),
194                 expirationtime = 0.4,
195                 size = radius * 10,
196                 collisiondetection = false,
197                 vertical = false,
198                 texture = "tnt_boom.png",
199         })
200         minetest.add_particlespawner({
201                 amount = 64,
202                 time = 0.5,
203                 minpos = vector.subtract(pos, radius / 2),
204                 maxpos = vector.add(pos, radius / 2),
205                 minvel = {x = -10, y = -10, z = -10},
206                 maxvel = {x = 10, y = 10, z = 10},
207                 minacc = vector.new(),
208                 maxacc = vector.new(),
209                 minexptime = 1,
210                 maxexptime = 2.5,
211                 minsize = radius * 3,
212                 maxsize = radius * 5,
213                 texture = "tnt_smoke.png",
214         })
215
216         -- we just dropped some items. Look at the items entities and pick
217         -- one of them to use as texture
218         local texture = "tnt_blast.png" --fallback texture
219         local most = 0
220         for name, stack in pairs(drops) do
221                 local count = stack:get_count()
222                 if count > most then
223                         most = count
224                         local def = minetest.registered_nodes[name]
225                         if def and def.tiles and def.tiles[1] then
226                                 texture = def.tiles[1]
227                         end
228                 end
229         end
230
231         minetest.add_particlespawner({
232                 amount = 64,
233                 time = 0.1,
234                 minpos = vector.subtract(pos, radius / 2),
235                 maxpos = vector.add(pos, radius / 2),
236                 minvel = {x = -3, y = 0, z = -3},
237                 maxvel = {x = 3, y = 5,  z = 3},
238                 minacc = {x = 0, y = -10, z = 0},
239                 maxacc = {x = 0, y = -10, z = 0},
240                 minexptime = 0.8,
241                 maxexptime = 2.0,
242                 minsize = radius * 0.66,
243                 maxsize = radius * 2,
244                 texture = texture,
245                 collisiondetection = true,
246         })
247 end
248
249 function tnt.burn(pos)
250         local name = minetest.get_node(pos).name
251         local group = minetest.get_item_group(name, "tnt")
252         if group > 0 then
253                 minetest.sound_play("tnt_ignite", {pos = pos})
254                 minetest.set_node(pos, {name = name .. "_burning"})
255                 minetest.get_node_timer(pos):start(1)
256         elseif name == "tnt:gunpowder" then
257                 minetest.set_node(pos, {name = "tnt:gunpowder_burning"})
258         end
259 end
260
261 local function tnt_explode(pos, radius, ignore_protection, ignore_on_blast)
262         local pos = vector.round(pos)
263         -- scan for adjacent TNT nodes first, and enlarge the explosion
264         local vm1 = VoxelManip()
265         local p1 = vector.subtract(pos, 2)
266         local p2 = vector.add(pos, 2)
267         local minp, maxp = vm1:read_from_map(p1, p2)
268         local a = VoxelArea:new({MinEdge = minp, MaxEdge = maxp})
269         local data = vm1:get_data()
270         local count = 0
271         local c_tnt = minetest.get_content_id("tnt:tnt")
272         local c_tnt_burning = minetest.get_content_id("tnt:tnt_burning")
273         local c_tnt_boom = minetest.get_content_id("tnt:boom")
274         local c_air = minetest.get_content_id("air")
275
276         for z = pos.z - 2, pos.z + 2 do
277         for y = pos.y - 2, pos.y + 2 do
278                 local vi = a:index(pos.x - 2, y, z)
279                 for x = pos.x - 2, pos.x + 2 do
280                         local cid = data[vi]
281                         if cid == c_tnt or cid == c_tnt_boom or cid == c_tnt_burning then
282                                 count = count + 1
283                                 data[vi] = c_air
284                         end
285                         vi = vi + 1
286                 end
287         end
288         end
289
290         vm1:set_data(data)
291         vm1:write_to_map()
292
293         -- recalculate new radius
294         radius = math.floor(radius * math.pow(count, 1/3))
295
296         -- perform the explosion
297         local vm = VoxelManip()
298         local pr = PseudoRandom(os.time())
299         local p1 = vector.subtract(pos, radius)
300         local p2 = vector.add(pos, radius)
301         local minp, maxp = vm:read_from_map(p1, p2)
302         local a = VoxelArea:new({MinEdge = minp, MaxEdge = maxp})
303         local data = vm:get_data()
304
305         local drops = {}
306         local on_blast_queue = {}
307
308         local c_fire = minetest.get_content_id("fire:basic_flame")
309         for z = -radius, radius do
310         for y = -radius, radius do
311         local vi = a:index(pos.x + (-radius), pos.y + y, pos.z + z)
312         for x = -radius, radius do
313                 local r = vector.length(vector.new(x, y, z))
314                 if (radius * radius) / (r * r) >= (pr:next(80, 125) / 100) then
315                         local cid = data[vi]
316                         local p = {x = pos.x + x, y = pos.y + y, z = pos.z + z}
317                         if cid ~= c_air then
318                                 data[vi] = destroy(drops, p, cid, c_air, c_fire,
319                                         on_blast_queue, ignore_protection,
320                                         ignore_on_blast)
321                         end
322                 end
323                 vi = vi + 1
324         end
325         end
326         end
327
328         vm:set_data(data)
329         vm:write_to_map()
330         vm:update_map()
331         vm:update_liquids()
332
333         -- call nodeupdate for everything within 1.5x blast radius
334         for z = -radius * 1.5, radius * 1.5 do
335         for x = -radius * 1.5, radius * 1.5 do
336         for y = -radius * 1.5, radius * 1.5 do
337                 local s = vector.add(pos, {x = x, y = y, z = z})
338                 local r = vector.distance(pos, s)
339                 if r / radius < 1.4 then
340                         nodeupdate(s)
341                 end
342         end
343         end
344         end
345
346         for _, data in ipairs(on_blast_queue) do
347                 local dist = math.max(1, vector.distance(data.pos, pos))
348                 local intensity = (radius * radius) / (dist * dist)
349                 local node_drops = data.on_blast(data.pos, intensity)
350                 if node_drops then
351                         for _, item in ipairs(node_drops) do
352                                 add_drop(drops, item)
353                         end
354                 end
355         end
356
357         return drops, radius
358 end
359
360 function tnt.boom(pos, def)
361         minetest.sound_play("tnt_explode", {pos = pos, gain = 1.5, max_hear_distance = 2*64})
362         minetest.set_node(pos, {name = "tnt:boom"})
363         local drops, radius = tnt_explode(pos, def.radius, def.ignore_protection,
364                         def.ignore_on_blast)
365         -- append entity drops
366         local damage_radius = (radius / def.radius) * def.damage_radius
367         entity_physics(pos, damage_radius, drops)
368         if not def.disable_drops then
369                 eject_drops(drops, pos, radius)
370         end
371         add_effects(pos, radius, drops)
372 end
373
374 minetest.register_node("tnt:boom", {
375         drawtype = "airlike",
376         light_source = default.LIGHT_MAX,
377         walkable = false,
378         drop = "",
379         groups = {dig_immediate = 3},
380         on_construct = function(pos)
381                 minetest.get_node_timer(pos):start(0.4)
382         end,
383         on_timer = function(pos, elapsed)
384                 minetest.remove_node(pos)
385         end,
386         -- unaffected by explosions
387         on_blast = function() end,
388 })
389
390 minetest.register_node("tnt:gunpowder", {
391         description = "Gun Powder",
392         drawtype = "raillike",
393         paramtype = "light",
394         is_ground_content = false,
395         sunlight_propagates = true,
396         walkable = false,
397         tiles = {"tnt_gunpowder_straight.png", "tnt_gunpowder_curved.png", "tnt_gunpowder_t_junction.png", "tnt_gunpowder_crossing.png"},
398         inventory_image = "tnt_gunpowder_inventory.png",
399         wield_image = "tnt_gunpowder_inventory.png",
400         selection_box = {
401                 type = "fixed",
402                 fixed = {-1/2, -1/2, -1/2, 1/2, -1/2+1/16, 1/2},
403         },
404         groups = {dig_immediate = 2, attached_node = 1, connect_to_raillike = minetest.raillike_group("gunpowder")},
405         sounds = default.node_sound_leaves_defaults(),
406
407         on_punch = function(pos, node, puncher)
408                 if puncher:get_wielded_item():get_name() == "default:torch" then
409                         tnt.burn(pos)
410                 end
411         end,
412         on_blast = function(pos, intensity)
413                 tnt.burn(pos)
414         end,
415 })
416
417 minetest.register_node("tnt:gunpowder_burning", {
418         drawtype = "raillike",
419         paramtype = "light",
420         sunlight_propagates = true,
421         walkable = false,
422         light_source = 5,
423         tiles = {{
424                 name = "tnt_gunpowder_burning_straight_animated.png",
425                 animation = {
426                         type = "vertical_frames",
427                         aspect_w = 16,
428                         aspect_h = 16,
429                         length = 1,
430                 }
431         },
432         {
433                 name = "tnt_gunpowder_burning_curved_animated.png",
434                 animation = {
435                         type = "vertical_frames",
436                         aspect_w = 16,
437                         aspect_h = 16,
438                         length = 1,
439                 }
440         },
441         {
442                 name = "tnt_gunpowder_burning_t_junction_animated.png",
443                 animation = {
444                         type = "vertical_frames",
445                         aspect_w = 16,
446                         aspect_h = 16,
447                         length = 1,
448                 }
449         },
450         {
451                 name = "tnt_gunpowder_burning_crossing_animated.png",
452                 animation = {
453                         type = "vertical_frames",
454                         aspect_w = 16,
455                         aspect_h = 16,
456                         length = 1,
457                 }
458         }},
459         selection_box = {
460                 type = "fixed",
461                 fixed = {-1/2, -1/2, -1/2, 1/2, -1/2+1/16, 1/2},
462         },
463         drop = "",
464         groups = {dig_immediate = 2, attached_node = 1, connect_to_raillike = minetest.raillike_group("gunpowder")},
465         sounds = default.node_sound_leaves_defaults(),
466         on_timer = function(pos, elapsed)
467                 for dx = -1, 1 do
468                 for dz = -1, 1 do
469                 for dy = -1, 1 do
470                         if not (dx == 0 and dz == 0) then
471                                 tnt.burn({
472                                         x = pos.x + dx,
473                                         y = pos.y + dy,
474                                         z = pos.z + dz,
475                                 })
476                         end
477                 end
478                 end
479                 end
480                 minetest.remove_node(pos)
481         end,
482         -- unaffected by explosions
483         on_blast = function() end,
484         on_construct = function(pos)
485                 minetest.sound_play("tnt_gunpowder_burning", {pos = pos, gain = 2})
486                 minetest.get_node_timer(pos):start(1)
487         end,
488 })
489
490 minetest.register_abm({
491         nodenames = {"group:tnt", "tnt:gunpowder"},
492         neighbors = {"fire:basic_flame", "default:lava_source", "default:lava_flowing"},
493         interval = 4,
494         chance = 1,
495         action = tnt.burn,
496 })
497
498 minetest.register_craft({
499         output = "tnt:gunpowder",
500         type = "shapeless",
501         recipe = {"default:coal_lump", "default:gravel"}
502 })
503
504 minetest.register_craft({
505         output = "tnt:tnt",
506         recipe = {
507                 {"",           "group:wood",    ""},
508                 {"group:wood", "tnt:gunpowder", "group:wood"},
509                 {"",           "group:wood",    ""}
510         }
511 })
512
513 function tnt.register_tnt(def)
514         local name = ""
515         if not def.name:find(':') then
516                 name = "tnt:" .. def.name
517         else
518                 name = def.name
519                 def.name = def.name:match(":([%w_]+)")
520         end
521         if not def.tiles then def.tiles = {} end
522         local tnt_top = def.tiles.top or def.name .. "_top.png"
523         local tnt_bottom = def.tiles.bottom or def.name .. "_bottom.png"
524         local tnt_side = def.tiles.side or def.name .. "_side.png"
525         local tnt_burning = def.tiles.burning or def.name .. "_top_burning_animated.png"
526         if not def.damage_radius then def.damage_radius = def.radius * 2 end
527
528         minetest.register_node(":" .. name, {
529                 description = def.description,
530                 tiles = {tnt_top, tnt_bottom, tnt_side},
531                 is_ground_content = false,
532                 groups = {dig_immediate = 2, mesecon = 2, tnt = 1},
533                 sounds = default.node_sound_wood_defaults(),
534                 on_punch = function(pos, node, puncher)
535                         if puncher:get_wielded_item():get_name() == "default:torch" then
536                                 minetest.set_node(pos, {name = name .. "_burning"})
537                         end
538                 end,
539                 on_blast = function(pos, intensity)
540                         minetest.after(0.1, function()
541                                 tnt.boom(pos, def)
542                         end)
543                 end,
544                 mesecons = {effector =
545                         {action_on =
546                                 function(pos)
547                                         tnt.boom(pos, def)
548                                 end
549                         }
550                 },
551         })
552
553         minetest.register_node(":" .. name .. "_burning", {
554                 tiles = {
555                         {
556                                 name = tnt_burning,
557                                 animation = {
558                                         type = "vertical_frames",
559                                         aspect_w = 16,
560                                         aspect_h = 16,
561                                         length = 1,
562                                 }
563                         },
564                         tnt_bottom, tnt_side
565                         },
566                 light_source = 5,
567                 drop = "",
568                 sounds = default.node_sound_wood_defaults(),
569                 groups = {falling_node = 1},
570                 on_timer = function(pos, elapsed)
571                         tnt.boom(pos, def)
572                 end,
573                 -- unaffected by explosions
574                 on_blast = function() end,
575                 on_construct = function(pos)
576                         minetest.sound_play("tnt_ignite", {pos = pos})
577                         minetest.get_node_timer(pos):start(4)
578                         nodeupdate(pos)
579                 end,
580         })
581 end
582
583 tnt.register_tnt({
584         name = "tnt:tnt",
585         description = "TNT",
586         radius = radius,
587 })
588