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