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