f8b59ab2caf535b168ad086a2c42c72b9ad6fa87
[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                 local take_est = math.log(count * count) + math.random(0,4) - 2
53                 while count > 0 do
54                         local take = math.max(1,math.min(take_est,
55                                         item:get_count(),
56                                         item:get_stack_max()))
57                         rand_pos(pos, drop_pos, radius)
58                         local dropitem = ItemStack(item)
59                         dropitem:set_count(take)
60                         local obj = minetest.add_item(drop_pos, dropitem)
61                         if obj then
62                                 obj:get_luaentity().collect = true
63                                 obj:setacceleration({x = 0, y = -10, z = 0})
64                                 obj:setvelocity({x = math.random(-3, 3),
65                                                 y = math.random(0, 10),
66                                                 z = math.random(-3, 3)})
67                         end
68                         count = count - take
69                 end
70         end
71 end
72
73 local function add_drop(drops, item)
74         item = ItemStack(item)
75         local name = item:get_name()
76         if loss_prob[name] ~= nil and math.random(1, loss_prob[name]) == 1 then
77                 return
78         end
79
80         local drop = drops[name]
81         if drop == nil then
82                 drops[name] = item
83         else
84                 drop:set_count(drop:get_count() + item:get_count())
85         end
86 end
87
88
89 local function destroy(drops, npos, cid, c_air, c_fire, on_blast_queue, ignore_protection, ignore_on_blast)
90         if not ignore_protection and minetest.is_protected(npos, "") 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] = {pos = vector.new(npos), on_blast = def.on_blast}
100                 return cid
101         elseif def.flammable then
102                 return c_fire
103         else
104                 local node_drops = minetest.get_node_drops(def.name, "")
105                 for _, item in ipairs(node_drops) do
106                         add_drop(drops, item)
107                 end
108                 return c_air
109         end
110 end
111
112
113 local function calc_velocity(pos1, pos2, old_vel, power)
114         local vel = vector.direction(pos1, pos2)
115         vel = vector.normalize(vel)
116         vel = vector.multiply(vel, power)
117
118         -- Divide by distance
119         local dist = vector.distance(pos1, pos2)
120         dist = math.max(dist, 1)
121         vel = vector.divide(vel, dist)
122
123         -- Add old velocity
124         vel = vector.add(vel, old_vel)
125
126         -- Limit to terminal velocity
127         dist = vector.length(vel)
128         if dist > 250 then
129                 vel = vector.divide(vel, dist / 250)
130         end
131         return vel
132 end
133
134 local function entity_physics(pos, radius)
135         local objs = minetest.get_objects_inside_radius(pos, radius)
136         for _, obj in pairs(objs) do
137                 local obj_pos = obj:getpos()
138                 local obj_vel = obj:getvelocity()
139                 local dist = math.max(1, vector.distance(pos, obj_pos))
140
141                 if obj_vel ~= nil then
142                         obj:setvelocity(calc_velocity(pos, obj_pos,
143                                         obj_vel, radius * 10))
144                 end
145
146                 local damage = (4 / dist) * radius
147                 obj:set_hp(obj:get_hp() - damage)
148         end
149 end
150
151 local function add_effects(pos, radius, drops)
152         minetest.add_particlespawner({
153                 amount = 128,
154                 time = 1,
155                 minpos = vector.subtract(pos, radius / 2),
156                 maxpos = vector.add(pos, radius / 2),
157                 minvel = {x = -20, y = -20, z = -20},
158                 maxvel = {x = 20, y = 20, z = 20},
159                 minacc = vector.new(),
160                 maxacc = vector.new(),
161                 minexptime = 1,
162                 maxexptime = 3,
163                 minsize = 8,
164                 maxsize = 16,
165                 texture = "tnt_smoke.png",
166         })
167
168         -- we just dropped some items. Look at the items entities and pick
169         -- one of them to use as texture
170         local texture = "tnt_blast.png" --fallback texture
171         local most = 0
172         for name, stack in pairs(drops) do
173                 local count = stack:get_count()
174                 if count > most then
175                         most = count
176                         local def = minetest.registered_nodes[name]
177                         if def and def.tiles and def.tiles[1] then
178                                 texture = def.tiles[1]
179                         end
180                 end
181         end
182
183         minetest.add_particlespawner({
184                 amount = 64,
185                 time = 0.1,
186                 minpos = vector.subtract(pos, radius / 2),
187                 maxpos = vector.add(pos, radius / 2),
188                 minvel = {x = -3, y = 0, z = -3},
189                 maxvel = {x = 3, y = 5,  z = 3},
190                 minacc = {x = 0, y = -10, z = 0},
191                 maxacc = {x = 0, y = -10, z = 0},
192                 minexptime = 0.8,
193                 maxexptime = 2.0,
194                 minsize = 2,
195                 maxsize = 6,
196                 texture = texture,
197                 collisiondetection = true,
198         })
199 end
200
201 function tnt.burn(pos)
202         local name = minetest.get_node(pos).name
203         local group = minetest.get_item_group(name, "tnt")
204         if group > 0 then
205                 minetest.sound_play("tnt_ignite", {pos = pos})
206                 minetest.set_node(pos, {name = name .. "_burning"})
207                 minetest.get_node_timer(pos):start(1)
208         elseif name == "tnt:gunpowder" then
209                 minetest.set_node(pos, {name = "tnt:gunpowder_burning"})
210         end
211 end
212
213 local function tnt_explode(pos, radius, ignore_protection, ignore_on_blast)
214         local pos = vector.round(pos)
215         local vm = VoxelManip()
216         local pr = PseudoRandom(os.time())
217         local p1 = vector.subtract(pos, radius)
218         local p2 = vector.add(pos, radius)
219         local minp, maxp = vm:read_from_map(p1, p2)
220         local a = VoxelArea:new({MinEdge = minp, MaxEdge = maxp})
221         local data = vm:get_data()
222
223         local drops = {}
224         local on_blast_queue = {}
225
226         local c_air = minetest.get_content_id("air")
227         local c_fire = minetest.get_content_id("fire:basic_flame")
228         for z = -radius, radius do
229         for y = -radius, radius do
230         local vi = a:index(pos.x + (-radius), pos.y + y, pos.z + z)
231         for x = -radius, radius do
232                 local r = vector.length(vector.new(x, y, z))
233                 if (radius * radius) / (r * r) >= (pr:next(80, 125) / 100) then
234                         local cid = data[vi]
235                         local p = {x = pos.x + x, y = pos.y + y, z = pos.z + z}
236                         if cid ~= c_air then
237                                 data[vi] = destroy(drops, p, cid, c_air, c_fire,
238                                         on_blast_queue, ignore_protection,
239                                         ignore_on_blast)
240                         end
241                 end
242                 vi = vi + 1
243         end
244         end
245         end
246
247         vm:set_data(data)
248         vm:write_to_map()
249         vm:update_map()
250         vm:update_liquids()
251
252         -- call nodeupdate for everything within 1.5x blast radius
253         for z = -radius * 1.5, radius * 1.5 do
254         for x = -radius * 1.5, radius * 1.5 do
255         for y = -radius * 1.5, radius * 1.5 do
256                 local s = vector.add(pos, {x = x, y = y, z = z})
257                 local r = vector.distance(pos, s)
258                 if r / radius < 1.4 then
259                         nodeupdate(s)
260                 end
261         end
262         end
263         end
264
265         for _, data in ipairs(on_blast_queue) do
266                 local dist = math.max(1, vector.distance(data.pos, pos))
267                 local intensity = (radius * radius) / (dist * dist)
268                 local node_drops = data.on_blast(data.pos, intensity)
269                 if node_drops then
270                         for _, item in ipairs(node_drops) do
271                                 add_drop(drops, item)
272                         end
273                 end
274         end
275
276         return drops
277 end
278
279 function tnt.boom(pos, def)
280         minetest.sound_play("tnt_explode", {pos = pos, gain = 1.5, max_hear_distance = 2*64})
281         minetest.set_node(pos, {name = "tnt:boom"})
282         minetest.get_node_timer(pos):start(0.5)
283         local drops = tnt_explode(pos, def.radius, def.ignore_protection,
284                         def.ignore_on_blast)
285         entity_physics(pos, def.damage_radius)
286         if not def.disable_drops then
287                 eject_drops(drops, pos, def.radius)
288         end
289         add_effects(pos, def.radius, drops)
290 end
291
292 minetest.register_node("tnt:boom", {
293         drawtype = "plantlike",
294         tiles = {"tnt_boom.png"},
295         light_source = default.LIGHT_MAX,
296         walkable = false,
297         drop = "",
298         groups = {dig_immediate = 3},
299         on_timer = function(pos, elapsed)
300                 minetest.remove_node(pos)
301         end,
302         -- unaffected by explosions
303         on_blast = function() end,
304 })
305
306 minetest.register_node("tnt:gunpowder", {
307         description = "Gun Powder",
308         drawtype = "raillike",
309         paramtype = "light",
310         is_ground_content = false,
311         sunlight_propagates = true,
312         walkable = false,
313         tiles = {"tnt_gunpowder_straight.png", "tnt_gunpowder_curved.png", "tnt_gunpowder_t_junction.png", "tnt_gunpowder_crossing.png"},
314         inventory_image = "tnt_gunpowder_inventory.png",
315         wield_image = "tnt_gunpowder_inventory.png",
316         selection_box = {
317                 type = "fixed",
318                 fixed = {-1/2, -1/2, -1/2, 1/2, -1/2+1/16, 1/2},
319         },
320         groups = {dig_immediate = 2, attached_node = 1, connect_to_raillike = minetest.raillike_group("gunpowder")},
321         sounds = default.node_sound_leaves_defaults(),
322
323         on_punch = function(pos, node, puncher)
324                 if puncher:get_wielded_item():get_name() == "default:torch" then
325                         tnt.burn(pos)
326                 end
327         end,
328         on_blast = function(pos, intensity)
329                 tnt.burn(pos)
330         end,
331 })
332
333 minetest.register_node("tnt:gunpowder_burning", {
334         drawtype = "raillike",
335         paramtype = "light",
336         sunlight_propagates = true,
337         walkable = false,
338         light_source = 5,
339         tiles = {{
340                 name = "tnt_gunpowder_burning_straight_animated.png",
341                 animation = {
342                         type = "vertical_frames",
343                         aspect_w = 16,
344                         aspect_h = 16,
345                         length = 1,
346                 }
347         },
348         {
349                 name = "tnt_gunpowder_burning_curved_animated.png",
350                 animation = {
351                         type = "vertical_frames",
352                         aspect_w = 16,
353                         aspect_h = 16,
354                         length = 1,
355                 }
356         },
357         {
358                 name = "tnt_gunpowder_burning_t_junction_animated.png",
359                 animation = {
360                         type = "vertical_frames",
361                         aspect_w = 16,
362                         aspect_h = 16,
363                         length = 1,
364                 }
365         },
366         {
367                 name = "tnt_gunpowder_burning_crossing_animated.png",
368                 animation = {
369                         type = "vertical_frames",
370                         aspect_w = 16,
371                         aspect_h = 16,
372                         length = 1,
373                 }
374         }},
375         selection_box = {
376                 type = "fixed",
377                 fixed = {-1/2, -1/2, -1/2, 1/2, -1/2+1/16, 1/2},
378         },
379         drop = "",
380         groups = {dig_immediate = 2, attached_node = 1, connect_to_raillike = minetest.raillike_group("gunpowder")},
381         sounds = default.node_sound_leaves_defaults(),
382         on_timer = function(pos, elapsed)
383                 for dx = -1, 1 do
384                 for dz = -1, 1 do
385                 for dy = -1, 1 do
386                         if not (dx == 0 and dz == 0) then
387                                 tnt.burn({
388                                         x = pos.x + dx,
389                                         y = pos.y + dy,
390                                         z = pos.z + dz,
391                                 })
392                         end
393                 end
394                 end
395                 end
396                 minetest.remove_node(pos)
397         end,
398         -- unaffected by explosions
399         on_blast = function() end,
400         on_construct = function(pos)
401                 minetest.sound_play("tnt_gunpowder_burning", {pos = pos, gain = 2})
402                 minetest.get_node_timer(pos):start(1)
403         end,
404 })
405
406 minetest.register_abm({
407         nodenames = {"group:tnt", "tnt:gunpowder"},
408         neighbors = {"fire:basic_flame", "default:lava_source", "default:lava_flowing"},
409         interval = 4,
410         chance = 1,
411         action = tnt.burn,
412 })
413
414 minetest.register_craft({
415         output = "tnt:gunpowder",
416         type = "shapeless",
417         recipe = {"default:coal_lump", "default:gravel"}
418 })
419
420 minetest.register_craft({
421         output = "tnt:tnt",
422         recipe = {
423                 {"",           "group:wood",    ""},
424                 {"group:wood", "tnt:gunpowder", "group:wood"},
425                 {"",           "group:wood",    ""}
426         }
427 })
428
429 function tnt.register_tnt(def)
430         local name = ""
431         if not def.name:find(':') then
432                 name = "tnt:" .. def.name
433         else
434                 name = def.name
435                 def.name = def.name:match(":([%w_]+)")
436         end
437         if not def.tiles then def.tiles = {} end
438         local tnt_top = def.tiles.top or def.name .. "_top.png"
439         local tnt_bottom = def.tiles.bottom or def.name .. "_bottom.png"
440         local tnt_side = def.tiles.side or def.name .. "_side.png"
441         local tnt_burning = def.tiles.burning or def.name .. "_top_burning_animated.png"
442         if not def.damage_radius then def.damage_radius = def.radius * 2 end
443
444         minetest.register_node(":" .. name, {
445                 description = def.description,
446                 tiles = {tnt_top, tnt_bottom, tnt_side},
447                 is_ground_content = false,
448                 groups = {dig_immediate = 2, mesecon = 2, tnt = 1},
449                 sounds = default.node_sound_wood_defaults(),
450                 on_punch = function(pos, node, puncher)
451                         if puncher:get_wielded_item():get_name() == "default:torch" then
452                                 minetest.set_node(pos, {name = name .. "_burning"})
453                         end
454                 end,
455                 on_blast = function(pos, intensity)
456                         minetest.after(0.1, function()
457                                 tnt.boom(pos, def)
458                         end)
459                 end,
460                 mesecons = {effector =
461                         {action_on =
462                                 function(pos)
463                                         tnt.boom(pos, def)
464                                 end
465                         }
466                 },
467         })
468
469         minetest.register_node(":" .. name .. "_burning", {
470                 tiles = {
471                         {
472                                 name = tnt_burning,
473                                 animation = {
474                                         type = "vertical_frames",
475                                         aspect_w = 16,
476                                         aspect_h = 16,
477                                         length = 1,
478                                 }
479                         },
480                         tnt_bottom, tnt_side
481                         },
482                 light_source = 5,
483                 drop = "",
484                 sounds = default.node_sound_wood_defaults(),
485                 on_timer = function(pos, elapsed)
486                         tnt.boom(pos, def)
487                 end,
488                 -- unaffected by explosions
489                 on_blast = function() end,
490                 on_construct = function(pos)
491                         minetest.sound_play("tnt_ignite", {pos = pos})
492                         minetest.get_node_timer(pos):start(4)
493                 end,
494         })
495 end
496
497 tnt.register_tnt({
498         name = "tnt:tnt",
499         description = "TNT",
500         radius = radius,
501 })
502