0e061fa62d3a6d6b4e3db1de8a6fba4ad2d6a2b7
[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.after(0, 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                         -- currently the engine has no method to set
167                         -- player velocity. See #2960
168                         -- instead, we knock the player back 1.0 node, and slightly upwards
169                         local dir = vector.normalize(vector.subtract(obj_pos, pos))
170                         local moveoff = vector.multiply(dir, dist + 1.0)
171                         local newpos = vector.add(pos, moveoff)
172                         newpos = vector.add(newpos, {x = 0, y = 0.2, z = 0})
173                         obj:set_pos(newpos)
174
175                         obj:set_hp(obj:get_hp() - damage)
176                 else
177                         local do_damage = true
178                         local do_knockback = true
179                         local entity_drops = {}
180                         local luaobj = obj:get_luaentity()
181                         local objdef = minetest.registered_entities[luaobj.name]
182
183                         if objdef and objdef.on_blast then
184                                 do_damage, do_knockback, entity_drops = objdef.on_blast(luaobj, damage)
185                         end
186
187                         if do_knockback then
188                                 local obj_vel = obj:get_velocity()
189                                 obj:set_velocity(calc_velocity(pos, obj_pos,
190                                                 obj_vel, radius * 10))
191                         end
192                         if do_damage then
193                                 if not obj:get_armor_groups().immortal then
194                                         obj:punch(obj, 1.0, {
195                                                 full_punch_interval = 1.0,
196                                                 damage_groups = {fleshy = damage},
197                                         }, nil)
198                                 end
199                         end
200                         for _, item in pairs(entity_drops) do
201                                 add_drop(drops, item)
202                         end
203                 end
204         end
205 end
206
207 local function add_effects(pos, radius, drops)
208         minetest.add_particle({
209                 pos = pos,
210                 velocity = vector.new(),
211                 acceleration = vector.new(),
212                 expirationtime = 0.4,
213                 size = radius * 10,
214                 collisiondetection = false,
215                 vertical = false,
216                 texture = "tnt_boom.png",
217                 glow = 15,
218         })
219         minetest.add_particlespawner({
220                 amount = 64,
221                 time = 0.5,
222                 minpos = vector.subtract(pos, radius / 2),
223                 maxpos = vector.add(pos, radius / 2),
224                 minvel = {x = -10, y = -10, z = -10},
225                 maxvel = {x = 10, y = 10, z = 10},
226                 minacc = vector.new(),
227                 maxacc = vector.new(),
228                 minexptime = 1,
229                 maxexptime = 2.5,
230                 minsize = radius * 3,
231                 maxsize = radius * 5,
232                 texture = "tnt_smoke.png",
233         })
234
235         -- we just dropped some items. Look at the items entities and pick
236         -- one of them to use as texture
237         local texture = "tnt_blast.png" --fallback texture
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 and def.tiles and def.tiles[1] then
245                                 texture = def.tiles[1]
246                         end
247                 end
248         end
249
250         minetest.add_particlespawner({
251                 amount = 64,
252                 time = 0.1,
253                 minpos = vector.subtract(pos, radius / 2),
254                 maxpos = vector.add(pos, radius / 2),
255                 minvel = {x = -3, y = 0, z = -3},
256                 maxvel = {x = 3, y = 5,  z = 3},
257                 minacc = {x = 0, y = -10, z = 0},
258                 maxacc = {x = 0, y = -10, z = 0},
259                 minexptime = 0.8,
260                 maxexptime = 2.0,
261                 minsize = radius * 0.66,
262                 maxsize = radius * 2,
263                 texture = texture,
264                 collisiondetection = true,
265         })
266 end
267
268 function tnt.burn(pos, nodename)
269         local name = nodename or minetest.get_node(pos).name
270         local def = minetest.registered_nodes[name]
271         if not def then
272                 return
273         elseif def.on_ignite then
274                 def.on_ignite(pos)
275         elseif minetest.get_item_group(name, "tnt") > 0 then
276                 minetest.swap_node(pos, {name = name .. "_burning"})
277                 minetest.sound_play("tnt_ignite", {pos = pos})
278                 minetest.get_node_timer(pos):start(1)
279         end
280 end
281
282 local function tnt_explode(pos, radius, ignore_protection, ignore_on_blast, owner, explode_center)
283         pos = vector.round(pos)
284         -- scan for adjacent TNT nodes first, and enlarge the explosion
285         local vm1 = VoxelManip()
286         local p1 = vector.subtract(pos, 2)
287         local p2 = vector.add(pos, 2)
288         local minp, maxp = vm1:read_from_map(p1, p2)
289         local a = VoxelArea:new({MinEdge = minp, MaxEdge = maxp})
290         local data = vm1:get_data()
291         local count = 0
292         local c_tnt = minetest.get_content_id("tnt:tnt")
293         local c_tnt_burning = minetest.get_content_id("tnt:tnt_burning")
294         local c_tnt_boom = minetest.get_content_id("tnt:boom")
295         local c_air = minetest.get_content_id("air")
296         -- make sure we still have explosion even when centre node isnt tnt related
297         if explode_center then
298                 count = 1
299         end
300
301         for z = pos.z - 2, pos.z + 2 do
302         for y = pos.y - 2, pos.y + 2 do
303                 local vi = a:index(pos.x - 2, y, z)
304                 for x = pos.x - 2, pos.x + 2 do
305                         local cid = data[vi]
306                         if cid == c_tnt or cid == c_tnt_boom or cid == c_tnt_burning then
307                                 count = count + 1
308                                 data[vi] = c_air
309                         end
310                         vi = vi + 1
311                 end
312         end
313         end
314
315         vm1:set_data(data)
316         vm1:write_to_map()
317
318         -- recalculate new radius
319         radius = math.floor(radius * math.pow(count, 1/3))
320
321         -- perform the explosion
322         local vm = VoxelManip()
323         local pr = PseudoRandom(os.time())
324         p1 = vector.subtract(pos, radius)
325         p2 = vector.add(pos, radius)
326         minp, maxp = vm:read_from_map(p1, p2)
327         a = VoxelArea:new({MinEdge = minp, MaxEdge = maxp})
328         data = vm:get_data()
329
330         local drops = {}
331         local on_blast_queue = {}
332         local on_construct_queue = {}
333         basic_flame_on_construct = minetest.registered_nodes["fire:basic_flame"].on_construct
334
335         local c_fire = minetest.get_content_id("fire:basic_flame")
336         for z = -radius, radius do
337         for y = -radius, radius do
338         local vi = a:index(pos.x + (-radius), pos.y + y, pos.z + z)
339         for x = -radius, radius do
340                 local r = vector.length(vector.new(x, y, z))
341                 if (radius * radius) / (r * r) >= (pr:next(80, 125) / 100) then
342                         local cid = data[vi]
343                         local p = {x = pos.x + x, y = pos.y + y, z = pos.z + z}
344                         if cid ~= c_air then
345                                 data[vi] = destroy(drops, p, cid, c_air, c_fire,
346                                         on_blast_queue, on_construct_queue,
347                                         ignore_protection, ignore_on_blast, owner)
348                         end
349                 end
350                 vi = vi + 1
351         end
352         end
353         end
354
355         vm:set_data(data)
356         vm:write_to_map()
357         vm:update_map()
358         vm:update_liquids()
359
360         -- call check_single_for_falling for everything within 1.5x blast radius
361         for y = -radius * 1.5, radius * 1.5 do
362         for z = -radius * 1.5, radius * 1.5 do
363         for x = -radius * 1.5, radius * 1.5 do
364                 local rad = {x = x, y = y, z = z}
365                 local s = vector.add(pos, rad)
366                 local r = vector.length(rad)
367                 if r / radius < 1.4 then
368                         minetest.check_single_for_falling(s)
369                 end
370         end
371         end
372         end
373
374         for _, queued_data in pairs(on_blast_queue) do
375                 local dist = math.max(1, vector.distance(queued_data.pos, pos))
376                 local intensity = (radius * radius) / (dist * dist)
377                 local node_drops = queued_data.on_blast(queued_data.pos, intensity)
378                 if node_drops then
379                         for _, item in pairs(node_drops) do
380                                 add_drop(drops, item)
381                         end
382                 end
383         end
384
385         for _, queued_data in pairs(on_construct_queue) do
386                 queued_data.fn(queued_data.pos)
387         end
388
389         minetest.log("action", "TNT owned by " .. owner .. " detonated at " ..
390                 minetest.pos_to_string(pos) .. " with radius " .. radius)
391
392         return drops, radius
393 end
394
395 function tnt.boom(pos, def)
396         def = def or {}
397         def.radius = def.radius or 1
398         def.damage_radius = def.damage_radius or def.radius * 2
399         local meta = minetest.get_meta(pos)
400         local owner = meta:get_string("owner")
401         if not def.explode_center then
402                 minetest.set_node(pos, {name = "tnt:boom"})
403         end
404         local sound = def.sound or "tnt_explode"
405         minetest.sound_play(sound, {pos = pos, gain = 2.5,
406                         max_hear_distance = math.min(def.radius * 20, 128)})
407         local drops, radius = tnt_explode(pos, def.radius, def.ignore_protection,
408                         def.ignore_on_blast, owner, def.explode_center)
409         -- append entity drops
410         local damage_radius = (radius / math.max(1, def.radius)) * def.damage_radius
411         entity_physics(pos, damage_radius, drops)
412         if not def.disable_drops then
413                 eject_drops(drops, pos, radius)
414         end
415         add_effects(pos, radius, drops)
416         minetest.log("action", "A TNT explosion occurred at " .. minetest.pos_to_string(pos) ..
417                 " with radius " .. radius)
418 end
419
420 minetest.register_node("tnt:boom", {
421         drawtype = "airlike",
422         light_source = default.LIGHT_MAX,
423         walkable = false,
424         drop = "",
425         groups = {dig_immediate = 3},
426         -- unaffected by explosions
427         on_blast = function() end,
428 })
429
430 minetest.register_node("tnt:gunpowder", {
431         description = S("Gun Powder"),
432         drawtype = "raillike",
433         paramtype = "light",
434         is_ground_content = false,
435         sunlight_propagates = true,
436         walkable = false,
437         tiles = {
438                 "tnt_gunpowder_straight.png",
439                 "tnt_gunpowder_curved.png",
440                 "tnt_gunpowder_t_junction.png",
441                 "tnt_gunpowder_crossing.png"
442         },
443         inventory_image = "tnt_gunpowder_inventory.png",
444         wield_image = "tnt_gunpowder_inventory.png",
445         selection_box = {
446                 type = "fixed",
447                 fixed = {-1/2, -1/2, -1/2, 1/2, -1/2+1/16, 1/2},
448         },
449         groups = {dig_immediate = 2, attached_node = 1, flammable = 5,
450                 connect_to_raillike = minetest.raillike_group("gunpowder")},
451         sounds = default.node_sound_leaves_defaults(),
452
453         on_punch = function(pos, node, puncher)
454                 if puncher:get_wielded_item():get_name() == "default:torch" then
455                         minetest.set_node(pos, {name = "tnt:gunpowder_burning"})
456                         minetest.log("action", puncher:get_player_name() ..
457                                 " ignites tnt:gunpowder at " ..
458                                 minetest.pos_to_string(pos))
459                 end
460         end,
461         on_blast = function(pos, intensity)
462                 minetest.set_node(pos, {name = "tnt:gunpowder_burning"})
463         end,
464         on_burn = function(pos)
465                 minetest.set_node(pos, {name = "tnt:gunpowder_burning"})
466         end,
467         on_ignite = function(pos, igniter)
468                 minetest.set_node(pos, {name = "tnt:gunpowder_burning"})
469         end,
470 })
471
472 minetest.register_node("tnt:gunpowder_burning", {
473         drawtype = "raillike",
474         paramtype = "light",
475         sunlight_propagates = true,
476         walkable = false,
477         light_source = 5,
478         tiles = {{
479                 name = "tnt_gunpowder_burning_straight_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_curved_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_t_junction_animated.png",
498                 animation = {
499                         type = "vertical_frames",
500                         aspect_w = 16,
501                         aspect_h = 16,
502                         length = 1,
503                 }
504         },
505         {
506                 name = "tnt_gunpowder_burning_crossing_animated.png",
507                 animation = {
508                         type = "vertical_frames",
509                         aspect_w = 16,
510                         aspect_h = 16,
511                         length = 1,
512                 }
513         }},
514         selection_box = {
515                 type = "fixed",
516                 fixed = {-1/2, -1/2, -1/2, 1/2, -1/2+1/16, 1/2},
517         },
518         drop = "",
519         groups = {
520                 dig_immediate = 2,
521                 attached_node = 1,
522                 connect_to_raillike = minetest.raillike_group("gunpowder")
523         },
524         sounds = default.node_sound_leaves_defaults(),
525         on_timer = function(pos, elapsed)
526                 for dx = -1, 1 do
527                 for dz = -1, 1 do
528                         if math.abs(dx) + math.abs(dz) == 1 then
529                                 for dy = -1, 1 do
530                                         tnt.burn({
531                                                 x = pos.x + dx,
532                                                 y = pos.y + dy,
533                                                 z = pos.z + dz,
534                                         })
535                                 end
536                         end
537                 end
538                 end
539                 minetest.remove_node(pos)
540         end,
541         -- unaffected by explosions
542         on_blast = function() end,
543         on_construct = function(pos)
544                 minetest.sound_play("tnt_gunpowder_burning", {pos = pos, gain = 2})
545                 minetest.get_node_timer(pos):start(1)
546         end,
547 })
548
549 minetest.register_craft({
550         output = "tnt:gunpowder 5",
551         type = "shapeless",
552         recipe = {"default:coal_lump", "default:gravel"}
553 })
554
555 minetest.register_craftitem("tnt:tnt_stick", {
556         description = S("TNT Stick"),
557         inventory_image = "tnt_tnt_stick.png",
558         groups = {flammable = 5},
559 })
560
561 if enable_tnt then
562         minetest.register_craft({
563                 output = "tnt:tnt_stick 2",
564                 recipe = {
565                         {"tnt:gunpowder", "", "tnt:gunpowder"},
566                         {"tnt:gunpowder", "default:paper", "tnt:gunpowder"},
567                         {"tnt:gunpowder", "", "tnt:gunpowder"},
568                 }
569         })
570
571         minetest.register_craft({
572                 output = "tnt:tnt",
573                 recipe = {
574                         {"tnt:tnt_stick", "tnt:tnt_stick", "tnt:tnt_stick"},
575                         {"tnt:tnt_stick", "tnt:tnt_stick", "tnt:tnt_stick"},
576                         {"tnt:tnt_stick", "tnt:tnt_stick", "tnt:tnt_stick"}
577                 }
578         })
579
580         minetest.register_abm({
581                 label = "TNT ignition",
582                 nodenames = {"group:tnt", "tnt:gunpowder"},
583                 neighbors = {"fire:basic_flame", "default:lava_source", "default:lava_flowing"},
584                 interval = 4,
585                 chance = 1,
586                 action = function(pos, node)
587                         tnt.burn(pos, node.name)
588                 end,
589         })
590 end
591
592 function tnt.register_tnt(def)
593         local name
594         if not def.name:find(':') then
595                 name = "tnt:" .. def.name
596         else
597                 name = def.name
598                 def.name = def.name:match(":([%w_]+)")
599         end
600         if not def.tiles then def.tiles = {} end
601         local tnt_top = def.tiles.top or def.name .. "_top.png"
602         local tnt_bottom = def.tiles.bottom or def.name .. "_bottom.png"
603         local tnt_side = def.tiles.side or def.name .. "_side.png"
604         local tnt_burning = def.tiles.burning or def.name .. "_top_burning_animated.png"
605         if not def.damage_radius then def.damage_radius = def.radius * 2 end
606
607         if enable_tnt then
608                 minetest.register_node(":" .. name, {
609                         description = def.description,
610                         tiles = {tnt_top, tnt_bottom, tnt_side},
611                         is_ground_content = false,
612                         groups = {dig_immediate = 2, mesecon = 2, tnt = 1, flammable = 5},
613                         sounds = default.node_sound_wood_defaults(),
614                         after_place_node = function(pos, placer)
615                                 if placer:is_player() then
616                                         local meta = minetest.get_meta(pos)
617                                         meta:set_string("owner", placer:get_player_name())
618                                 end
619                         end,
620                         on_punch = function(pos, node, puncher)
621                                 if puncher:get_wielded_item():get_name() == "default:torch" then
622                                         minetest.swap_node(pos, {name = name .. "_burning"})
623                                         minetest.registered_nodes[name .. "_burning"].on_construct(pos)
624                                         minetest.log("action", puncher:get_player_name() ..
625                                                 " ignites " .. node.name .. " at " ..
626                                                 minetest.pos_to_string(pos))
627                                 end
628                         end,
629                         on_blast = function(pos, intensity)
630                                 minetest.after(0.1, function()
631                                         tnt.boom(pos, def)
632                                 end)
633                         end,
634                         mesecons = {effector =
635                                 {action_on =
636                                         function(pos)
637                                                 tnt.boom(pos, def)
638                                         end
639                                 }
640                         },
641                         on_burn = function(pos)
642                                 minetest.swap_node(pos, {name = name .. "_burning"})
643                                 minetest.registered_nodes[name .. "_burning"].on_construct(pos)
644                         end,
645                         on_ignite = function(pos, igniter)
646                                 minetest.swap_node(pos, {name = name .. "_burning"})
647                                 minetest.registered_nodes[name .. "_burning"].on_construct(pos)
648                         end,
649                 })
650         end
651
652         minetest.register_node(":" .. name .. "_burning", {
653                 tiles = {
654                         {
655                                 name = tnt_burning,
656                                 animation = {
657                                         type = "vertical_frames",
658                                         aspect_w = 16,
659                                         aspect_h = 16,
660                                         length = 1,
661                                 }
662                         },
663                         tnt_bottom, tnt_side
664                         },
665                 light_source = 5,
666                 drop = "",
667                 sounds = default.node_sound_wood_defaults(),
668                 groups = {falling_node = 1},
669                 on_timer = function(pos, elapsed)
670                         tnt.boom(pos, def)
671                 end,
672                 -- unaffected by explosions
673                 on_blast = function() end,
674                 on_construct = function(pos)
675                         minetest.sound_play("tnt_ignite", {pos = pos})
676                         minetest.get_node_timer(pos):start(4)
677                         minetest.check_for_falling(pos)
678                 end,
679         })
680 end
681
682 tnt.register_tnt({
683         name = "tnt:tnt",
684         description = S("TNT"),
685         radius = tnt_radius,
686 })