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