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