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