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