]> git.lizzy.rs Git - diglib.git/blob - init.lua
Create README.md
[diglib.git] / init.lua
1 diglib = {}
2
3 function diglib.calculate_dig_time(toolcaps, groups)
4         local best_time
5
6         for group, groupdef in pairs(toolcaps.groupcaps) do
7                 local level = groups[group]
8
9                 if level then
10                         local tm = groupdef.times[level]
11
12                         if tm and (not best_time or best_time > tm) then
13                                 best_time = tm
14                         end
15                 end
16         end
17
18         return best_time
19 end
20
21 function diglib.get_dig_time(pos)
22         local node = minetest.get_node_or_nil(pos)
23         local nodedef = node and minetest.get_node_def(node.name)
24         local groups = nodedef and nodedef.groups
25
26         if not groups then
27                 return
28         end
29
30         local player = minetest.localplayer
31         local wielditem = player and player:get_wielded_item()
32         local toolcaps = wielditem and wielditem:get_tool_capabilities()
33         local tool_time = toolcaps and diglib.calculate_dig_time(toolcaps, groups)
34
35         local inv = minetest.get_inventory("current_player")
36         local hand = inv and inv.hand and inv.hand[1] or ItemStack("")
37         local hand_toolcaps = hand and hand:get_tool_capabilities()
38         local hand_time = hand_toolcaps and diglib.calculate_dig_time(hand_toolcaps, groups)
39
40         local tm = math.min(tool_time or math.huge, hand_time or math.huge)
41
42         if tm == math.huge then
43                 return
44         end
45
46         return tm
47 end
48
49 diglib.dig_node = async(function(pos, max_time)
50         local tm = diglib.get_dig_time(pos)
51         if not tm or max_time and max_time > 0 and tm > max_time then
52                 return
53         end
54
55         local debug_msgs = minetest.settings:get_bool("diglib_debug")
56
57         if debug_msgs then
58                 print("start_digging", pos.x, pos.y, pos.z)
59         end
60         minetest.interact("start_digging", {type = "node", under = pos, above = pos})
61
62         if debug_msgs then
63                 print("sleep", tm)
64         end
65         lua_async.sleep(tm * 1000)
66
67         if debug_msgs then
68                 print("digging_completed", pos.x, pos.y, pos.z)
69         end
70         minetest.interact("digging_completed", {type = "node", under = pos, above = pos})
71 end)