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