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