Reset spawn position on bed destruction
[oweals/minetest_game.git] / mods / beds / spawns.lua
1 local world_path = minetest.get_worldpath()
2 local org_file = world_path .. "/beds_spawns"
3 local file = world_path .. "/beds_spawns"
4 local bkwd = false
5
6 -- check for PA's beds mod spawns
7 local cf = io.open(world_path .. "/beds_player_spawns", "r")
8 if cf ~= nil then
9         io.close(cf)
10         file = world_path .. "/beds_player_spawns"
11         bkwd = true
12 end
13
14 function beds.read_spawns()
15         local spawns = beds.spawn
16         local input = io.open(file, "r")
17         if input and not bkwd then
18                 repeat
19                         local x = input:read("*n")
20                         if x == nil then
21                                 break
22                         end
23                         local y = input:read("*n")
24                         local z = input:read("*n")
25                         local name = input:read("*l")
26                         spawns[name:sub(2)] = {x = x, y = y, z = z}
27                 until input:read(0) == nil
28                 io.close(input)
29         elseif input and bkwd then
30                 beds.spawn = minetest.deserialize(input:read("*all"))
31                 input:close()
32                 beds.save_spawns()
33                 os.rename(file, file .. ".backup")
34                 file = org_file
35         end
36 end
37
38 beds.read_spawns()
39
40 function beds.save_spawns()
41         if not beds.spawn then
42                 return
43         end
44         local data = {}
45         local output = io.open(org_file, "w")
46         for k, v in pairs(beds.spawn) do
47                 table.insert(data, string.format("%.1f %.1f %.1f %s\n", v.x, v.y, v.z, k))
48         end
49         output:write(table.concat(data))
50         io.close(output)
51 end
52
53 function beds.set_spawns()
54         for name,_ in pairs(beds.player) do
55                 local player = minetest.get_player_by_name(name)
56                 local p = player:get_pos()
57                 -- but don't change spawn location if borrowing a bed
58                 if not minetest.is_protected(p, name) then
59                         beds.spawn[name] = p
60                 end
61         end
62         beds.save_spawns()
63 end
64
65 function beds.remove_spawns_at(pos)
66         for name, p in pairs(beds.spawn) do
67                 if vector.equals(vector.round(p), pos) then
68                         beds.spawn[name] = nil
69                 end
70         end
71         beds.save_spawns()
72 end