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