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