]> git.lizzy.rs Git - signs_lib.git/blob - api.lua
cac59a81ed55f5f5770d2af8b3a140a1f8976fb5
[signs_lib.git] / api.lua
1 -- signs_lib api, backported from street_signs
2
3 local S = signs_lib.gettext
4
5 signs_lib.lbm_restore_nodes = {}
6 signs_lib.old_fenceposts = {}
7 signs_lib.old_fenceposts_replacement_signs = {}
8 signs_lib.old_fenceposts_with_signs = {}
9
10 -- Settings used for a standard wood or steel wall sign
11 signs_lib.standard_lines = 6
12 signs_lib.standard_hscale = 1
13 signs_lib.standard_vscale = 1
14 signs_lib.standard_lspace = 1
15 signs_lib.standard_fsize = 15
16 signs_lib.standard_xoffs = 4
17 signs_lib.standard_yoffs = 0
18 signs_lib.standard_cpl = 35
19
20 signs_lib.standard_wood_groups = table.copy(minetest.registered_items["default:sign_wall_wood"].groups)
21 signs_lib.standard_wood_groups.sign = 1
22 signs_lib.standard_wood_groups.attached_node = nil
23
24 signs_lib.standard_steel_groups = table.copy(minetest.registered_items["default:sign_wall_steel"].groups)
25 signs_lib.standard_steel_groups.sign = 1
26 signs_lib.standard_steel_groups.attached_node = nil
27
28 signs_lib.standard_wood_sign_sounds  = table.copy(minetest.registered_items["default:sign_wall_wood"].sounds)
29 signs_lib.standard_steel_sign_sounds = table.copy(minetest.registered_items["default:sign_wall_steel"].sounds)
30
31 signs_lib.default_text_scale = {x=10, y=10}
32
33 signs_lib.old_widefont_signs = {}
34
35 signs_lib.block_list = {}
36 signs_lib.totalblocks = 0
37
38 signs_lib.standard_yaw = {
39         0,
40         math.pi / -2,
41         math.pi,
42         math.pi / 2,
43 }
44
45 signs_lib.wallmounted_yaw = {
46         nil,
47         nil,
48         math.pi / -2,
49         math.pi / 2,
50         0,
51         math.pi,
52 }
53
54 signs_lib.fdir_to_back = {
55         {  0, -1 },
56         { -1,  0 },
57         {  0,  1 },
58         {  1,  0 },
59 }
60
61 signs_lib.wall_fdir_to_back = {
62         nil,
63         nil,
64         {  0,  1 },
65         {  0, -1 },
66         { -1,  0 },
67         {  1,  0 },
68 }
69
70 signs_lib.fdir_flip_to_back = {
71         [0] = {  0,  2 },
72         [1] = {  2,  0 },
73         [2] = {  0, -2 },
74         [3] = { -2,  0 }
75 }
76
77 signs_lib.wall_fdir_flip_to_back = {
78         [2] = {  2,  0 },
79         [3] = { -2,  0 },
80         [4] = {  0,  2 },
81         [5] = {  0, -2 },
82 }
83
84 signs_lib.fdir_to_back_left = {
85         [0] = { -1,  1 },
86         [1] = {  1,  1 },
87         [2] = {  1, -1 },
88         [3] = { -1, -1 }
89 }
90
91 signs_lib.wall_fdir_to_back_left = {
92         [2] = {  1,  1 },
93         [3] = { -1, -1 },
94         [4] = { -1,  1 },
95         [5] = {  1, -1 }
96 }
97
98 signs_lib.rotate_walldir = {
99         [0] = 4,
100         [1] = 0,
101         [2] = 5,
102         [3] = 1,
103         [4] = 2,
104         [5] = 3
105 }
106
107 signs_lib.rotate_walldir_simple = {
108         [0] = 4,
109         [1] = 4,
110         [2] = 5,
111         [3] = 4,
112         [4] = 2,
113         [5] = 3
114 }
115
116 signs_lib.rotate_facedir = {
117         [0] = 1,
118         [1] = 2,
119         [2] = 3,
120         [3] = 4,
121         [4] = 6,
122         [5] = 6,
123         [6] = 0
124 }
125
126 signs_lib.rotate_facedir_simple = {
127         [0] = 1,
128         [1] = 2,
129         [2] = 3,
130         [3] = 0,
131         [4] = 0,
132         [5] = 0
133 }
134
135 signs_lib.flip_facedir = {
136         [0] = 2,
137         [1] = 3,
138         [2] = 0,
139         [3] = 1,
140         [4] = 6,
141         [5] = 4,
142         [6] = 4
143 }
144
145 signs_lib.flip_walldir = {
146         [0] = 1,
147         [1] = 0,
148         [2] = 3,
149         [3] = 2,
150         [4] = 5,
151         [5] = 4
152 }
153
154 -- Initialize character texture cache
155 local ctexcache = {}
156
157 -- entity handling
158
159 minetest.register_entity("signs_lib:text", {
160         collisionbox = { 0, 0, 0, 0, 0, 0 },
161         visual = "mesh",
162         mesh = "signs_lib_standard_wall_sign_entity.obj",
163         textures = {},
164         static_save = false,
165         backface_culling = false
166 })
167
168 function signs_lib.delete_objects(pos)
169         local objects = minetest.get_objects_inside_radius(pos, 0.5)
170         for _, v in ipairs(objects) do
171                 if v then
172                         local e = v:get_luaentity()
173                         if e and string.match(e.name, "sign.*text") then
174                                 v:remove()
175                         end
176                 end
177         end
178 end
179
180 function signs_lib.spawn_entity(pos, texture)
181         local node = minetest.get_node(pos)
182         local def = minetest.registered_items[node.name]
183         if not def or not def.entity_info then return end
184
185         local text_scale = (node and node.text_scale) or signs_lib.default_text_scale
186         local objects = minetest.get_objects_inside_radius(pos, 0.5)
187         local obj
188
189         if #objects > 0 then
190                 for _, v in ipairs(objects) do
191                         if v then
192                                 local e = v:get_luaentity()
193                                 if e and e.name == "signs_lib:text" then
194                                         obj = v
195                                 end
196                         end
197                 end
198         end
199
200         if not obj then
201                 obj = minetest.add_entity(pos, "signs_lib:text")
202         end
203
204         local yaw = def.entity_info.yaw[node.param2 + 1]
205         local pitch = 0
206
207         if not string.find(node.name, "onpole") and not string.find(node.name, "hanging") then
208                 local rot90 = math.pi/2
209
210                 if def.paramtype2 == "wallmounted" then
211                         if node.param2 == 1 then -- on floor
212                                 pitch = -rot90
213                                 yaw = 0
214                         elseif node.param2 == 0 then -- on ceiling
215                                 pitch = rot90
216                                 yaw = math.pi
217                         end
218                 elseif def.paramtype2 == "facedir" then
219                         if node.param2 == 4 then
220                                 pitch = -rot90
221                                 yaw = 0
222                         elseif node.param2 == 6 then
223                                 pitch = rot90
224                                 yaw = math.pi
225                         end
226                 end
227         end
228
229         if yaw then
230                 obj:set_rotation({x = pitch, y = yaw, z=0})
231
232                 if not texture then
233                         obj:set_properties({
234                                 mesh = def.entity_info.mesh,
235                                 visual_size = text_scale,
236                         })
237                 else
238                         obj:set_properties({
239                                 mesh = def.entity_info.mesh,
240                                 visual_size = text_scale,
241                                 textures={texture},
242                         })
243                 end
244         end
245 end
246
247 function signs_lib.set_obj_text(pos, text)
248         local split = signs_lib.split_lines_and_words
249         local text_ansi = Utf8ToAnsi(text)
250         local n = minetest.registered_nodes[minetest.get_node(pos).name]
251         signs_lib.delete_objects(pos)
252         signs_lib.spawn_entity(pos, signs_lib.make_sign_texture(split(text_ansi), pos) )
253 end
254
255 -- rotation
256
257 function signs_lib.handle_rotation(pos, node, user, mode)
258         if not signs_lib.can_modify(pos, user)
259           or mode ~= screwdriver.ROTATE_FACE then
260                 return false
261         end
262         local newparam2
263         local tpos = pos
264         local def = minetest.registered_items[node.name]
265
266         if string.match(node.name, "_onpole") then
267                 if not string.match(node.name, "_horiz") then
268                         newparam2 = signs_lib.rotate_walldir_simple[node.param2] or 4
269                         local t = signs_lib.wall_fdir_to_back_left
270
271                         if def.paramtype2 ~= "wallmounted" then
272                                 newparam2 = signs_lib.rotate_facedir_simple[node.param2] or 0
273                                 t  = signs_lib.fdir_to_back_left
274                         end
275
276                         tpos = {
277                                 x = pos.x + t[node.param2][1],
278                                 y = pos.y,
279                                 z = pos.z + t[node.param2][2]
280                         }
281                 else
282                         -- flip the sign to the other side of the horizontal pole
283                         newparam2 = signs_lib.flip_walldir[node.param2] or 4
284                         local t = signs_lib.wall_fdir_flip_to_back
285
286                         if def.paramtype2 ~= "wallmounted" then
287                                 newparam2 = signs_lib.flip_facedir[node.param2] or 0
288                                 t  = signs_lib.fdir_flip_to_back
289                         end
290
291                         tpos = {
292                                 x = pos.x + t[node.param2][1],
293                                 y = pos.y,
294                                 z = pos.z + t[node.param2][2]
295                         }
296                 end
297                 local node2 = minetest.get_node(tpos)
298                 local def2 = minetest.registered_items[node2.name]
299                 if not def2 or not def2.buildable_to then return true end -- undefined, or not buildable_to.
300
301                 minetest.set_node(tpos, {name = node.name, param2 = newparam2})
302                 minetest.get_meta(tpos):from_table(minetest.get_meta(pos):to_table())
303                 minetest.remove_node(pos)
304                 signs_lib.delete_objects(pos)
305         elseif string.match(node.name, "_hanging") or string.match(node.name, "yard") then
306                 minetest.swap_node(tpos, { name = node.name, param2 = signs_lib.rotate_facedir_simple[node.param2] or 0 })
307         elseif minetest.registered_items[node.name].paramtype2 == "wallmounted" then
308                 minetest.swap_node(tpos, { name = node.name, param2 = signs_lib.rotate_walldir[node.param2] or 0 })
309         else
310                 minetest.swap_node(tpos, { name = node.name, param2 = signs_lib.rotate_facedir[node.param2] or 0 })
311         end
312
313         signs_lib.update_sign(tpos)
314         return true
315 end
316
317 -- infinite stacks
318
319 if not minetest.settings:get_bool("creative_mode") then
320         signs_lib.expect_infinite_stacks = false
321 else
322         signs_lib.expect_infinite_stacks = true
323 end
324
325 -- CONSTANTS
326
327 -- Path to the textures.
328 local TP = signs_lib.path .. "/textures"
329 -- Font file formatter
330 local CHAR_FILE = "%s_%02x.png"
331 -- Fonts path
332 local CHAR_PATH = TP .. "/" .. CHAR_FILE
333
334 -- Lots of overkill here. KISS advocates, go away, shoo! ;) -- kaeza
335
336 local PNG_HDR = string.char(0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A)
337
338 -- check if a file does exist
339 -- to avoid reopening file after checking again
340 -- pass TRUE as second argument
341 local function file_exists(name, return_handle, mode)
342         mode = mode or "r";
343         local f = io.open(name, mode)
344         if f ~= nil then
345                 if (return_handle) then
346                         return f
347                 end
348                 io.close(f) 
349                 return true 
350         else 
351                 return false 
352         end
353 end
354
355 -- Read the image size from a PNG file.
356 -- Returns image_w, image_h.
357 -- Only the LSB is read from each field!
358 function signs_lib.read_image_size(filename)
359         local f = file_exists(filename, true, "rb")
360         -- file might not exist (don't crash the game)
361         if (not f) then
362                 return 0, 0
363         end
364         f:seek("set", 0x0)
365         local hdr = f:read(string.len(PNG_HDR))
366         if hdr ~= PNG_HDR then
367                 f:close()
368                 return
369         end
370         f:seek("set", 0x13)
371         local ws = f:read(1)
372         f:seek("set", 0x17)
373         local hs = f:read(1)
374         f:close()
375         return ws:byte(), hs:byte()
376 end
377
378 -- 4 rows, max 80 chars per, plus a bit of fudge to
379 -- avoid excess trimming (e.g. due to color codes)
380
381 local MAX_INPUT_CHARS = 400
382
383 -- helper functions to trim sign text input/output
384
385 local function trim_input(text)
386         return text:sub(1, math.min(MAX_INPUT_CHARS, text:len()))
387 end
388
389 local function build_char_db(font_size)
390
391         local cw = {}
392
393         -- To calculate average char width.
394         local total_width = 0
395         local char_count = 0
396
397         for c = 32, 255 do
398                 local w, h = signs_lib.read_image_size(CHAR_PATH:format("signs_lib_font_"..font_size.."px", c))
399                 if w and h then
400                         local ch = string.char(c)
401                         cw[ch] = w
402                         total_width = total_width + w
403                         char_count = char_count + 1
404                 end
405         end
406
407         local cbw, cbh = signs_lib.read_image_size(TP.."/signs_lib_color_"..font_size.."px_n.png")
408         assert(cbw and cbh, "error reading bg dimensions")
409         return cw, cbw, cbh, (total_width / char_count)
410 end
411
412 signs_lib.charwidth15,
413 signs_lib.colorbgw15,
414 signs_lib.lineheight15,
415 signs_lib.avgwidth15 = build_char_db(15)
416
417 signs_lib.charwidth31,
418 signs_lib.colorbgw31,
419 signs_lib.lineheight31,
420 signs_lib.avgwidth31 = build_char_db(31)
421
422 local sign_groups = {choppy=2, dig_immediate=2}
423 local fences_with_sign = { }
424
425 -- some local helper functions
426
427 local math_max = math.max
428
429 local function fill_line(x, y, w, c, font_size, colorbgw)
430         c = c or "0"
431         local tex = { }
432         for xx = 0, math.max(0, w), colorbgw do
433                 table.insert(tex, (":%d,%d=signs_lib_color_"..font_size.."px_%s.png"):format(x + xx, y, c))
434         end
435         return table.concat(tex)
436 end
437
438 -- make char texture file name
439 -- if texture file does not exist use fallback texture instead
440 local function char_tex(font_name, ch)
441         if ctexcache[font_name..ch] then
442                 return ctexcache[font_name..ch], true
443         else
444                 local c = ch:byte()
445                 local exists, tex = file_exists(CHAR_PATH:format(font_name, c))
446                 if exists and c ~= 14 then
447                         tex = CHAR_FILE:format(font_name, c)
448                 else
449                         tex = CHAR_FILE:format(font_name, 0x0)
450                 end
451                 ctexcache[font_name..ch] = tex
452                 return tex, exists
453         end
454 end
455
456 local function make_line_texture(line, lineno, pos, line_width, line_height, cwidth_tab, font_size, colorbgw)
457         local width = 0
458         local maxw = 0
459         local font_name = "signs_lib_font_"..font_size.."px"
460
461         local words = { }
462         local node = minetest.get_node(pos)
463         local def = minetest.registered_items[node.name]
464         local default_color = def.default_color or 0
465
466         local cur_color = tonumber(default_color, 16)
467
468         -- We check which chars are available here.
469         for word_i, word in ipairs(line) do
470                 local chars = { }
471                 local ch_offs = 0
472                 word = string.gsub(word, "%^[12345678abcdefgh]", {
473                         ["^1"] = string.char(0x81),
474                         ["^2"] = string.char(0x82),
475                         ["^3"] = string.char(0x83),
476                         ["^4"] = string.char(0x84),
477                         ["^5"] = string.char(0x85),
478                         ["^6"] = string.char(0x86),
479                         ["^7"] = string.char(0x87),
480                         ["^8"] = string.char(0x88),
481                         ["^a"] = string.char(0x8a),
482                         ["^b"] = string.char(0x8b),
483                         ["^c"] = string.char(0x8c),
484                         ["^d"] = string.char(0x8d),
485                         ["^e"] = string.char(0x8e),
486                         ["^f"] = string.char(0x8f),
487                         ["^g"] = string.char(0x90),
488                         ["^h"] = string.char(0x91)
489                 })
490                 local word_l = #word
491                 local i = 1
492                 while i <= word_l  do
493                         local c = word:sub(i, i)
494                         if c == "#" then
495                                 local cc = tonumber(word:sub(i+1, i+1), 16)
496                                 if cc then
497                                         i = i + 1
498                                         cur_color = cc
499                                 end
500                         else
501                                 local w = cwidth_tab[c]
502                                 if w then
503                                         width = width + w + 1
504                                         if width >= (line_width - cwidth_tab[" "]) then
505                                                 width = 0
506                                         else
507                                                 maxw = math_max(width, maxw)
508                                         end
509                                         if #chars < MAX_INPUT_CHARS then
510                                                 table.insert(chars, {
511                                                         off = ch_offs,
512                                                         tex = char_tex(font_name, c),
513                                                         col = ("%X"):format(cur_color),
514                                                 })
515                                         end
516                                         ch_offs = ch_offs + w
517                                 end
518                         end
519                         i = i + 1
520                 end
521                 width = width + cwidth_tab[" "] + 1
522                 maxw = math_max(width, maxw)
523                 table.insert(words, { chars=chars, w=ch_offs })
524         end
525
526         -- Okay, we actually build the "line texture" here.
527
528         local texture = { }
529
530         local start_xpos = math.floor((line_width - maxw) / 2) + def.x_offset
531
532         local xpos = start_xpos
533         local ypos = (line_height + def.line_spacing)* lineno + def.y_offset
534
535         cur_color = nil
536
537         for word_i, word in ipairs(words) do
538                 local xoffs = (xpos - start_xpos)
539                 if (xoffs > 0) and ((xoffs + word.w) > maxw) then
540                         table.insert(texture, fill_line(xpos, ypos, maxw, "n", font_size, colorbgw))
541                         xpos = start_xpos
542                         ypos = ypos + line_height + def.line_spacing
543                         lineno = lineno + 1
544                         if lineno >= def.number_of_lines then break end
545                         table.insert(texture, fill_line(xpos, ypos, maxw, cur_color, font_size, colorbgw))
546                 end
547                 for ch_i, ch in ipairs(word.chars) do
548                         if ch.col ~= cur_color then
549                                 cur_color = ch.col
550                                 table.insert(texture, fill_line(xpos + ch.off, ypos, maxw, cur_color, font_size, colorbgw))
551                         end
552                         table.insert(texture, (":%d,%d=%s"):format(xpos + ch.off, ypos, ch.tex))
553                 end
554                 table.insert(
555                         texture, 
556                         (":%d,%d="):format(xpos + word.w, ypos) .. char_tex(font_name, " ")
557                 )
558                 xpos = xpos + word.w + cwidth_tab[" "]
559                 if xpos >= (line_width + cwidth_tab[" "]) then break end
560         end
561
562         table.insert(texture, fill_line(xpos, ypos, maxw, "n", font_size, colorbgw))
563         table.insert(texture, fill_line(start_xpos, ypos + line_height, maxw, "n", font_size, colorbgw))
564
565         return table.concat(texture), lineno
566 end
567
568 function signs_lib.make_sign_texture(lines, pos)
569         local node = minetest.get_node(pos)
570         local meta = minetest.get_meta(pos)
571
572         local def = minetest.registered_items[node.name]
573         if not def or not def.entity_info then return end
574
575         local font_size
576         local line_width
577         local line_height
578         local char_width
579         local colorbgw
580         local widemult = 1
581
582         if meta:get_int("widefont") == 1 then
583                 widemult = 0.5
584         end
585
586         if def.font_size and def.font_size == 31 then
587                 font_size = 31
588                 line_width = math.floor(signs_lib.avgwidth31 * def.chars_per_line) * (def.horiz_scaling * widemult)
589                 line_height = signs_lib.lineheight31
590                 char_width = signs_lib.charwidth31
591                 colorbgw = signs_lib.colorbgw31
592         else
593                 font_size = 15
594                 line_width = math.floor(signs_lib.avgwidth15 * def.chars_per_line) * (def.horiz_scaling * widemult)
595                 line_height = signs_lib.lineheight15
596                 char_width = signs_lib.charwidth15
597                 colorbgw = signs_lib.colorbgw15
598         end
599
600         local texture = { ("[combine:%dx%d"):format(line_width, (line_height + def.line_spacing) * def.number_of_lines * def.vert_scaling) }
601
602         local lineno = 0
603         for i = 1, #lines do
604                 if lineno >= def.number_of_lines then break end
605                 local linetex, ln = make_line_texture(lines[i], lineno, pos, line_width, line_height, char_width, font_size, colorbgw)
606                 table.insert(texture, linetex)
607                 lineno = ln + 1
608         end
609         table.insert(texture, "^[makealpha:0,0,0")
610         return table.concat(texture, "")
611 end
612
613 function signs_lib.split_lines_and_words(text)
614         if not text then return end
615         local lines = { }
616         for _, line in ipairs(text:split("\n", true)) do
617                 table.insert(lines, line:split(" "))
618         end
619         return lines
620 end
621
622 function signs_lib.construct_sign(pos)
623         local form = "size[6,4]"..
624                 "textarea[0,-0.3;6.5,3;text;;${text}]"..
625                 "background[-0.5,-0.5;7,5;signs_lib_sign_bg.jpg]"
626         local node = minetest.get_node(pos)
627         local def = minetest.registered_items[node.name]
628         local meta = minetest.get_meta(pos)
629
630         if def.allow_widefont then
631                 local state = "off"
632                 if meta:get_int("widefont") == 1 then state = "on" end
633                 form = form.."label[1,3.4;Use wide font]"..
634                         "image_button[1.1,3.7;1,0.6;signs_lib_switch_"..
635                         state..".png;"..
636                         state..";;;false;signs_lib_switch_interm.png]"..
637                         "button_exit[3,3.4;2,1;ok;"..S("Write").."]"
638         else
639                 form = form.."button_exit[2,3.4;2,1;ok;"..S("Write").."]"
640         end
641
642         meta:set_string("formspec", form)
643         local i = meta:get_string("infotext")
644         if i == "" then -- it wasn't even set, so set it.
645                 meta:set_string("infotext", "")
646         end
647 end
648
649 function signs_lib.destruct_sign(pos)
650         signs_lib.delete_objects(pos)
651 end
652
653 local function make_infotext(text)
654         text = trim_input(text)
655         local lines = signs_lib.split_lines_and_words(text) or {}
656         local lines2 = { }
657         for _, line in ipairs(lines) do
658                 table.insert(lines2, (table.concat(line, " "):gsub("#[0-9a-fA-F]", ""):gsub("##", "#")))
659         end
660         return table.concat(lines2, "\n")
661 end
662
663 function signs_lib.update_sign(pos, fields)
664         local meta = minetest.get_meta(pos)
665
666         local text = fields and fields.text or meta:get_string("text")
667         text = trim_input(text)
668
669         local owner = meta:get_string("owner")
670         local ownstr = ""
671         if owner ~= "" then ownstr = S("Locked sign, owned by @1\n", owner) end
672
673         meta:set_string("text", text)
674         meta:set_string("infotext", ownstr..make_infotext(text).." ")
675         signs_lib.set_obj_text(pos, text)
676 end
677
678 function signs_lib.receive_fields(pos, formname, fields, sender)
679
680         if not fields or not signs_lib.can_modify(pos, sender) then return end
681
682         if fields.text and fields.ok then
683                 minetest.log("action", S("@1 wrote \"@2\" to sign at @3",
684                         (sender:get_player_name() or ""),
685                         fields.text:gsub('\\', '\\\\'):gsub("\n", "\\n"),
686                         minetest.pos_to_string(pos)
687                 ))
688                 signs_lib.update_sign(pos, fields)
689         elseif fields.on or fields.off then
690                 local node = minetest.get_node(pos)
691                 local meta = minetest.get_meta(pos)
692                 local change
693
694                 if fields.on and meta:get_int("widefont") == 1 then
695                         meta:set_int("widefont", 0)
696                         change = true
697                 elseif fields.off and meta:get_int("widefont") == 0 then
698                         meta:set_int("widefont", 1)
699                         change = true
700                 end
701                 if change then
702                         minetest.log("action", S("@1 flipped the wide-font switch to \"@2\" at @3",
703                                 (sender:get_player_name() or ""),
704                                 (fields.on and "off" or "on"),
705                                 minetest.pos_to_string(pos)
706                         ))
707                         signs_lib.construct_sign(pos)
708                         signs_lib.update_sign(pos, fields)
709                 end
710         end
711 end
712
713 function signs_lib.can_modify(pos, player)
714         local meta = minetest.get_meta(pos)
715         local owner = meta:get_string("owner")
716         local playername = player:get_player_name()
717
718         if minetest.is_protected(pos, playername) then 
719                 minetest.record_protection_violation(pos, playername)
720                 return false
721         end
722
723         if owner == ""
724           or playername == owner
725           or (minetest.check_player_privs(playername, {sign_editor=true}))
726           or (playername == minetest.settings:get("name")) then
727                 return true
728         end
729         minetest.record_protection_violation(pos, playername)
730         return false
731 end
732
733 -- make selection boxes
734 -- sizex/sizey specified in inches because that's what MUTCD uses.
735
736 function signs_lib.make_selection_boxes(sizex, sizey, foo, xoffs, yoffs, zoffs, is_facedir)
737
738         local tx = (sizex * 0.0254 ) / 2
739         local ty = (sizey * 0.0254 ) / 2
740         local xo = xoffs and xoffs * 0.0254 or 0
741         local yo = yoffs and yoffs * 0.0254 or 0
742         local zo = zoffs and zoffs * 0.0254 or 0
743
744         if not is_facedir then
745                 return {
746                         type = "wallmounted",
747                         wall_side =   { -0.5 + zo, -ty + yo, -tx + xo, -0.4375 + zo, ty + yo, tx + xo },
748                         wall_top =    { -tx - xo, 0.5 + zo, -ty + yo, tx - xo, 0.4375 + zo, ty + yo},
749                         wall_bottom = { -tx - xo, -0.5 + zo, -ty + yo, tx - xo, -0.4375 + zo, ty + yo }
750                 }
751         else
752                 return {
753                         type = "fixed",
754                         fixed = { -tx + xo, -ty + yo, 0.5 + zo, tx + xo, ty + yo, 0.4375 + zo}
755                 }
756         end
757 end
758
759 function signs_lib.check_for_pole(pos, pointed_thing)
760         local ppos = minetest.get_pointed_thing_position(pointed_thing)
761         local pnode = minetest.get_node(ppos)
762         local pdef = minetest.registered_items[pnode.name]
763
764         if not pdef then return end
765
766         if type(pdef.check_for_pole) == "function" then
767                 local node = minetest.get_node(pos)
768                 local def = minetest.registered_items[node.name]
769                 return pdef.check_for_pole(pos, node, def, ppos, pnode, pdef)
770         elseif pdef.check_for_pole
771           or pdef.drawtype == "fencelike"
772           or string.find(pnode.name, "_post")
773           or string.find(pnode.name, "fencepost") then
774                 return true
775         end
776 end
777
778 function signs_lib.check_for_horizontal_pole(pos, pointed_thing)
779         local ppos = minetest.get_pointed_thing_position(pointed_thing)
780         local pnode = minetest.get_node(ppos)
781         local pdef = minetest.registered_items[pnode.name]
782
783         if not pdef then return end
784
785         if type(pdef.check_for_horiz_pole) == "function" then
786                 local node = minetest.get_node(pos)
787                 local def = minetest.registered_items[node.name]
788                 return pdef.check_for_horiz_pole(pos, node, def, ppos, pnode, pdef)
789         elseif pdef.check_for_horiz_pole then
790                 return true
791         end
792 end
793
794 function signs_lib.check_for_ceiling(pointed_thing)
795         if pointed_thing.above.x == pointed_thing.under.x
796           and pointed_thing.above.z == pointed_thing.under.z
797           and pointed_thing.above.y < pointed_thing.under.y then
798                 return true
799         end
800 end
801
802 function signs_lib.check_for_floor(pointed_thing)
803         if pointed_thing.above.x == pointed_thing.under.x
804           and pointed_thing.above.z == pointed_thing.under.z
805           and pointed_thing.above.y > pointed_thing.under.y then
806                 return true
807         end
808 end
809
810 function signs_lib.after_place_node(pos, placer, itemstack, pointed_thing, locked)
811         local playername = placer:get_player_name()
812         local def = minetest.registered_items[itemstack:get_name()]
813
814         local ppos = minetest.get_pointed_thing_position(pointed_thing)
815         local pnode = minetest.get_node(ppos)
816         local pdef = minetest.registered_items[pnode.name]
817         if def.allow_onpole and signs_lib.check_for_pole(pos, pointed_thing) then
818                 local newparam2
819                 local lookdir = minetest.yaw_to_dir(placer:get_look_horizontal())
820                 if def.paramtype2 == "wallmounted" then
821                         newparam2 = minetest.dir_to_wallmounted(lookdir)
822                 else
823                         newparam2 = minetest.dir_to_facedir(lookdir)
824                 end
825                 local node = minetest.get_node(pos)
826                 minetest.swap_node(pos, {name = itemstack:get_name().."_onpole", param2 = newparam2})
827         elseif def.allow_onpole_horizontal and signs_lib.check_for_horizontal_pole(pos, pointed_thing) then
828                 local newparam2
829                 local lookdir = minetest.yaw_to_dir(placer:get_look_horizontal())
830                 if def.paramtype2 == "wallmounted" then
831                         newparam2 = minetest.dir_to_wallmounted(lookdir)
832                 else
833                         newparam2 = minetest.dir_to_facedir(lookdir)
834                 end
835                 local node = minetest.get_node(pos)
836                 minetest.swap_node(pos, {name = itemstack:get_name().."_onpole_horiz", param2 = newparam2})
837         elseif def.allow_hanging and signs_lib.check_for_ceiling(pointed_thing) then
838                 local newparam2 = minetest.dir_to_facedir(placer:get_look_dir())
839                 local node = minetest.get_node(pos)
840                 minetest.swap_node(pos, {name = itemstack:get_name().."_hanging", param2 = newparam2})
841         elseif def.paramtype2 == "facedir" and signs_lib.check_for_ceiling(pointed_thing) then
842                 minetest.swap_node(pos, {name = itemstack:get_name(), param2 = 6})
843         elseif def.paramtype2 == "facedir" and signs_lib.check_for_floor(pointed_thing) then
844                 minetest.swap_node(pos, {name = itemstack:get_name(), param2 = 4})
845         end
846         if locked then
847                 local meta = minetest.get_meta(pos)
848                 meta:set_string("owner", playername)
849                 meta:set_string("infotext", S("Locked sign, owned by @1\n", playername))
850         end
851 end
852
853 function signs_lib.register_fence_with_sign()
854         minetest.log("warning", "[signs_lib] ".."Attempt to call no longer used function signs_lib.register_fence_with_sign()")
855 end
856
857 function signs_lib.register_sign(name, rdef)
858         local def = table.copy(rdef)
859
860         if rdef.entity_info == "standard" then
861                 def.entity_info = {
862                         mesh = "signs_lib_standard_wall_sign_entity.obj",
863                         yaw = signs_lib.wallmounted_yaw
864                 }
865         elseif rdef.entity_info then
866                 def.entity_info = rdef.entity_info
867         end
868
869         def.after_place_node = rdef.after_place_node or signs_lib.after_place_node
870
871         if rdef.entity_info then
872                 def.on_rightclick       = rdef.on_rightclick       or signs_lib.construct_sign
873                 def.on_construct        = rdef.on_construct        or signs_lib.construct_sign
874                 def.on_destruct         = rdef.on_destruct         or signs_lib.destruct_sign
875                 def.on_receive_fields   = rdef.on_receive_fields   or signs_lib.receive_fields
876                 def.on_punch            = rdef.on_punch            or signs_lib.update_sign
877                 def.number_of_lines     = rdef.number_of_lines     or signs_lib.standard_lines
878                 def.horiz_scaling       = rdef.horiz_scaling       or signs_lib.standard_hscale
879                 def.vert_scaling        = rdef.vert_scaling        or signs_lib.standard_vscale
880                 def.line_spacing        = rdef.line_spacing        or signs_lib.standard_lspace
881                 def.font_size           = rdef.font_size           or signs_lib.standard_fsize
882                 def.x_offset            = rdef.x_offset            or signs_lib.standard_xoffs
883                 def.y_offset            = rdef.y_offset            or signs_lib.standard_yoffs
884                 def.chars_per_line      = rdef.chars_per_line      or signs_lib.standard_cpl
885                 def.default_color       = rdef.default_color       or "0"
886                 if rdef.locked and not rdef.after_place_node then
887                         def.after_place_node = function(pos, placer, itemstack, pointed_thing)
888                                 signs_lib.after_place_node(pos, placer, itemstack, pointed_thing, true)
889                         end
890                 end
891         end
892
893         def.paramtype           = rdef.paramtype           or "light"
894         def.drawtype            = rdef.drawtype            or "mesh"
895         def.mesh                = rdef.mesh                or "signs_lib_standard_wall_sign.obj"
896         def.wield_image         = rdef.wield_image         or def.inventory_image
897         def.drop                = rdef.drop                or name
898         def.sounds              = rdef.sounds              or signs_lib.standard_wood_sign_sounds
899         def.paramtype2          = rdef.paramtype2          or "wallmounted"
900         def.on_rotate           = rdef.on_rotate           or signs_lib.handle_rotation
901
902         if rdef.groups then
903                 def.groups = rdef.groups
904         else
905                 def.groups = signs_lib.standard_wood_groups
906         end
907
908         local cbox = signs_lib.make_selection_boxes(35, 25)
909
910         def.selection_box = rdef.selection_box or cbox
911         def.node_box      = table.copy(rdef.node_box or rdef.selection_box or cbox)
912
913         if def.sunlight_propagates ~= false then
914                 def.sunlight_propagates = true
915         end
916
917         minetest.register_node(":"..name, def)
918         table.insert(signs_lib.lbm_restore_nodes, name)
919
920         local opdef = table.copy(def)
921
922         if rdef.allow_onpole or rdef.allow_onpole_horizontal then
923
924                 local offset = 0.3125
925                 if opdef.uses_slim_pole_mount then
926                         offset = 0.35
927                 end
928
929                 opdef.selection_box = rdef.onpole_selection_box or opdef.selection_box
930                 opdef.node_box = rdef.onpole_node_box or opdef.selection_box
931
932                 if opdef.paramtype2 == "wallmounted" then
933                         opdef.node_box.wall_side[1] = def.node_box.wall_side[1] - offset
934                         opdef.node_box.wall_side[4] = def.node_box.wall_side[4] - offset
935
936                         opdef.selection_box.wall_side[1] = def.selection_box.wall_side[1] - offset
937                         opdef.selection_box.wall_side[4] = def.selection_box.wall_side[4] - offset
938                 else
939                         opdef.node_box.fixed[3] = def.node_box.fixed[3] + offset
940                         opdef.node_box.fixed[6] = def.node_box.fixed[6] + offset
941
942                         opdef.selection_box.fixed[3] = def.selection_box.fixed[3] + offset
943                         opdef.selection_box.fixed[6] = def.selection_box.fixed[6] + offset
944                 end
945
946                 opdef.groups.not_in_creative_inventory = 1
947                 opdef.mesh = string.gsub(opdef.mesh, ".obj$", "_onpole.obj")
948
949                 if opdef.entity_info then
950                         opdef.entity_info.mesh = string.gsub(opdef.entity_info.mesh, ".obj$", "_onpole.obj")
951                 end
952         end
953
954         -- setting one of item 3 or 4 to a texture and leaving the other "blank",
955         -- reveals either the vertical or horizontal pole mount part of the model
956
957         if rdef.allow_onpole then
958                 opdef.tiles[3] = "signs_lib_pole_mount.png"
959                 opdef.tiles[4] = "signs_lib_blank.png"
960                 minetest.register_node(":"..name.."_onpole", opdef)
961                 table.insert(signs_lib.lbm_restore_nodes, name.."_onpole")
962         end
963
964         local ophdef = table.copy(opdef)
965
966         if rdef.allow_onpole_horizontal then
967                 ophdef.tiles[3] = "signs_lib_blank.png"
968                 ophdef.tiles[4] = "signs_lib_pole_mount.png"
969                 minetest.register_node(":"..name.."_onpole_horiz", ophdef)
970                 table.insert(signs_lib.lbm_restore_nodes, name.."_onpole_horiz")
971         end
972
973         if rdef.allow_hanging then
974
975                 local hdef = table.copy(def)
976                 hdef.paramtype2 = "facedir"
977
978                 local hcbox = signs_lib.make_selection_boxes(35, 32, nil, 0, 3, -18.5, true)
979
980                 hdef.selection_box = rdef.hanging_selection_box or hcbox
981                 hdef.node_box = rdef.hanging_node_box or rdef.hanging_selection_box or hcbox
982
983                 hdef.groups.not_in_creative_inventory = 1
984                 hdef.tiles[3] = "signs_lib_hangers.png"
985                 hdef.mesh = string.gsub(string.gsub(hdef.mesh, "_facedir.obj", ".obj"), ".obj$", "_hanging.obj")
986
987                 if hdef.entity_info then
988                         hdef.entity_info.mesh = string.gsub(string.gsub(hdef.entity_info.mesh, "_facedir.obj", ".obj"), ".obj$", "_hanging.obj")
989                         hdef.entity_info.yaw = signs_lib.standard_yaw
990                 end
991
992                 minetest.register_node(":"..name.."_hanging", hdef)
993                 table.insert(signs_lib.lbm_restore_nodes, name.."_hanging")
994         end
995
996         if rdef.allow_widefont then
997                 table.insert(signs_lib.old_widefont_signs, name.."_widefont")
998                 table.insert(signs_lib.old_widefont_signs, name.."_widefont_onpole")
999                 table.insert(signs_lib.old_widefont_signs, name.."_widefont_hanging")
1000         end
1001 end
1002
1003 -- restore signs' text after /clearobjects and the like, the next time
1004 -- a block is reloaded by the server.
1005
1006 minetest.register_lbm({
1007         nodenames = signs_lib.lbm_restore_nodes,
1008         name = "signs_lib:restore_sign_text",
1009         label = "Restore sign text",
1010         run_at_every_load = true,
1011         action = function(pos, node)
1012                 signs_lib.update_sign(pos,nil,nil,node)
1013         end
1014 })
1015
1016 -- Convert old signs on fenceposts into signs on.. um.. fence posts :P
1017
1018 minetest.register_lbm({
1019         nodenames = signs_lib.old_fenceposts_with_signs,
1020         name = "signs_lib:fix_fencepost_signs",
1021         label = "Change single-node signs on fences into normal",
1022         run_at_every_load = true,
1023         action = function(pos, node)
1024
1025                 local fdir = node.param2 % 8
1026                 local signpos = {
1027                         x = pos.x + signs_lib.fdir_to_back[fdir+1][1],
1028                         y = pos.y,
1029                         z = pos.z + signs_lib.fdir_to_back[fdir+1][2]
1030                 }
1031
1032                 if minetest.get_node(signpos).name == "air" then
1033                         local new_wmdir = minetest.dir_to_wallmounted(minetest.facedir_to_dir(fdir))
1034                         local oldfence =  signs_lib.old_fenceposts[node.name]
1035                         local newsign =   signs_lib.old_fenceposts_replacement_signs[node.name]
1036
1037                         signs_lib.delete_objects(pos)
1038
1039                         local oldmeta = minetest.get_meta(pos):to_table()
1040                         minetest.set_node(pos, {name = oldfence})
1041                         minetest.set_node(signpos, { name = newsign, param2 = new_wmdir })
1042                         local newmeta = minetest.get_meta(signpos)
1043                         newmeta:from_table(oldmeta)
1044                         signs_lib.update_sign(signpos)
1045                 end
1046         end
1047 })
1048
1049 -- Convert widefont sign nodes to use one base node with meta flag to select wide mode
1050
1051 minetest.register_lbm({
1052         nodenames = signs_lib.old_widefont_signs,
1053         name = "signs_lib:convert_widefont_signs",
1054         label = "Convert widefont sign nodes",
1055         run_at_every_load = false,
1056         action = function(pos, node)
1057                 local basename = string.gsub(node.name, "_widefont", "")
1058                 minetest.swap_node(pos, {name = basename, param2 = node.param2})
1059                 local meta = minetest.get_meta(pos)
1060                 meta:set_int("widefont", 1)
1061                 signs_lib.update_sign(pos)
1062         end
1063 })
1064
1065 -- Maintain a list of currently-loaded blocks
1066 minetest.register_lbm({
1067         nodenames = {"group:sign"},
1068         name = "signs_lib:update_block_list",
1069         label = "Update list of loaded blocks, log only those with signs",
1070         run_at_every_load = true,
1071         action = function(pos, node)
1072                 -- yeah, yeah... I know I'm hashing a block pos, but it's still just a set of coords
1073                 local hash = minetest.hash_node_position(vector.floor(vector.divide(pos, core.MAP_BLOCKSIZE)))
1074                 if not signs_lib.block_list[hash] then
1075                         signs_lib.block_list[hash] = true
1076                         signs_lib.totalblocks = signs_lib.totalblocks + 1
1077                 end
1078         end
1079 })
1080
1081 minetest.register_chatcommand("regen_signs", {
1082         params = "",
1083         privs = {server = true},
1084         description = "Skims through all currently-loaded sign-bearing mapblocks, clears away any entities within each sign's node space, and regenerates their text entities, if any.",
1085         func = function(player_name, params)
1086                 local allsigns = {}
1087                 local totalsigns = 0
1088                 for b in pairs(signs_lib.block_list) do
1089                         local blockpos = minetest.get_position_from_hash(b)
1090                         local pos1 = vector.multiply(blockpos, core.MAP_BLOCKSIZE)
1091                         local pos2 = vector.add(pos1, core.MAP_BLOCKSIZE - 1)
1092                         if minetest.get_node_or_nil(vector.add(pos1, core.MAP_BLOCKSIZE/2)) then
1093                                 local signs_in_block = minetest.find_nodes_in_area(pos1, pos2, {"group:sign"})
1094                                 allsigns[#allsigns + 1] = signs_in_block
1095                                 totalsigns = totalsigns + #signs_in_block
1096                         else
1097                                 signs_lib.block_list[b] = nil -- if the block is no longer loaded, remove it from the table
1098                                 signs_lib.totalblocks = signs_lib.totalblocks - 1
1099                         end
1100                 end
1101                 if signs_lib.totalblocks < 0 then signs_lib.totalblocks = 0 end
1102                 if totalsigns == 0 then
1103                         minetest.chat_send_player(player_name, "There are no signs in the currently-loaded terrain.")
1104                         signs_lib.block_list = {}
1105                         return
1106                 end
1107
1108                 minetest.chat_send_player(player_name, "Found a total of "..totalsigns.." sign nodes across "..signs_lib.totalblocks.." blocks.")
1109                 minetest.chat_send_player(player_name, "Regenerating sign entities...")
1110
1111                 for _, b in pairs(allsigns) do
1112                         for _, pos in ipairs(b) do
1113                                 signs_lib.delete_objects(pos)
1114                                 local node = minetest.get_node(pos)
1115                                 local def = minetest.registered_items[node.name]
1116                                 if def and def.entity_info then
1117                                         signs_lib.update_sign(pos)
1118                                 end
1119                         end
1120                 end
1121                 minetest.chat_send_player(player_name, "Finished.")
1122         end
1123 })