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