1 -- signs_lib api, backported from street_signs
3 local S = signs_lib.gettext
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 = {}
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 = 2
19 signs_lib.standard_cpl = 35
21 signs_lib.standard_wood_groups = table.copy(minetest.registered_items["default:sign_wall_wood"].groups)
22 signs_lib.standard_wood_groups.sign = 1
24 signs_lib.standard_steel_groups = table.copy(minetest.registered_items["default:sign_wall_steel"].groups)
25 signs_lib.standard_steel_groups.sign = 1
27 signs_lib.standard_yaw = {
34 signs_lib.wallmounted_yaw = {
43 signs_lib.fdir_to_back = {
50 signs_lib.wall_fdir_to_back = {
59 signs_lib.rotate_facedir = {
69 signs_lib.rotate_walldir = {
78 -- Initialize character texture cache
81 signs_lib.wallmounted_rotate = function(pos, node, user, mode)
82 if not signs_lib.can_modify(pos, user) then return false end
84 if mode ~= screwdriver.ROTATE_FACE or string.match(node.name, "_onpole") then
88 local newparam2 = signs_lib.rotate_walldir[node.param2] or 0
90 minetest.swap_node(pos, { name = node.name, param2 = newparam2 })
91 for _, v in ipairs(minetest.get_objects_inside_radius(pos, 0.5)) do
92 local e = v:get_luaentity()
93 if e and e.name == "signs_lib:text" then
97 signs_lib.update_sign(pos)
101 signs_lib.facedir_rotate = function(pos, node, user, mode)
102 if not signs_lib.can_modify(pos, user) then return false end
104 if mode ~= screwdriver.ROTATE_FACE or string.match(node.name, "_onpole") then
108 local newparam2 = signs_lib.rotate_facedir[node.param2] or 0
110 minetest.swap_node(pos, { name = node.name, param2 = newparam2 })
111 for _, v in ipairs(minetest.get_objects_inside_radius(pos, 0.5)) do
112 local e = v:get_luaentity()
113 if e and e.name == "signs_lib:text" then
117 signs_lib.update_sign(pos)
121 local DEFAULT_TEXT_SCALE = {x=10, y=10}
125 if not minetest.settings:get_bool("creative_mode") then
126 signs_lib.expect_infinite_stacks = false
128 signs_lib.expect_infinite_stacks = true
133 -- Path to the textures.
134 local TP = signs_lib.path .. "/textures"
135 -- Font file formatter
136 local CHAR_FILE = "%s_%02x.png"
138 local CHAR_PATH = TP .. "/" .. CHAR_FILE
140 -- Lots of overkill here. KISS advocates, go away, shoo! ;) -- kaeza
142 local PNG_HDR = string.char(0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A)
144 -- check if a file does exist
145 -- to avoid reopening file after checking again
146 -- pass TRUE as second argument
147 local function file_exists(name, return_handle, mode)
149 local f = io.open(name, mode)
151 if (return_handle) then
161 -- Read the image size from a PNG file.
162 -- Returns image_w, image_h.
163 -- Only the LSB is read from each field!
164 function signs_lib.read_image_size(filename)
165 local f = file_exists(filename, true, "rb")
166 -- file might not exist (don't crash the game)
171 local hdr = f:read(string.len(PNG_HDR))
172 if hdr ~= PNG_HDR then
181 return ws:byte(), hs:byte()
184 -- 4 rows, max 80 chars per, plus a bit of fudge to
185 -- avoid excess trimming (e.g. due to color codes)
187 local MAX_INPUT_CHARS = 400
189 -- helper functions to trim sign text input/output
191 local function trim_input(text)
192 return text:sub(1, math.min(MAX_INPUT_CHARS, text:len()))
195 local function build_char_db(font_size)
199 -- To calculate average char width.
200 local total_width = 0
204 local w, h = signs_lib.read_image_size(CHAR_PATH:format("signs_lib_font_"..font_size.."px", c))
206 local ch = string.char(c)
208 total_width = total_width + w
209 char_count = char_count + 1
213 local cbw, cbh = signs_lib.read_image_size(TP.."/signs_lib_color_"..font_size.."px_n.png")
214 assert(cbw and cbh, "error reading bg dimensions")
215 return cw, cbw, cbh, (total_width / char_count)
218 signs_lib.charwidth15,
219 signs_lib.colorbgw15,
220 signs_lib.lineheight15,
221 signs_lib.avgwidth15 = build_char_db(15)
223 signs_lib.charwidth31,
224 signs_lib.colorbgw31,
225 signs_lib.lineheight31,
226 signs_lib.avgwidth31 = build_char_db(31)
228 local sign_groups = {choppy=2, dig_immediate=2}
229 local fences_with_sign = { }
231 -- some local helper functions
233 local function split_lines_and_words(text)
234 if not text then return end
236 for _, line in ipairs(text:split("\n")) do
237 table.insert(lines, line:split(" "))
242 local math_max = math.max
244 local function fill_line(x, y, w, c, font_size, colorbgw)
247 for xx = 0, math.max(0, w), colorbgw do
248 table.insert(tex, (":%d,%d=signs_lib_color_"..font_size.."px_%s.png"):format(x + xx, y, c))
250 return table.concat(tex)
253 -- make char texture file name
254 -- if texture file does not exist use fallback texture instead
255 local function char_tex(font_name, ch)
256 if ctexcache[font_name..ch] then
257 return ctexcache[font_name..ch], true
260 local exists, tex = file_exists(CHAR_PATH:format(font_name, c))
261 if exists and c ~= 14 then
262 tex = CHAR_FILE:format(font_name, c)
264 tex = CHAR_FILE:format(font_name, 0x0)
266 ctexcache[font_name..ch] = tex
271 local function make_line_texture(line, lineno, pos, line_width, line_height, cwidth_tab, font_size, colorbgw)
274 local font_name = "signs_lib_font_"..font_size.."px"
277 local node = minetest.get_node(pos)
278 local def = minetest.registered_items[node.name]
279 local default_color = def.default_color or 0
281 local cur_color = tonumber(default_color, 16)
283 -- We check which chars are available here.
284 for word_i, word in ipairs(line) do
287 word = string.gsub(word, "%^[12345678abcdefgh]", {
288 ["^1"] = string.char(0x81),
289 ["^2"] = string.char(0x82),
290 ["^3"] = string.char(0x83),
291 ["^4"] = string.char(0x84),
292 ["^5"] = string.char(0x85),
293 ["^6"] = string.char(0x86),
294 ["^7"] = string.char(0x87),
295 ["^8"] = string.char(0x88),
296 ["^a"] = string.char(0x8a),
297 ["^b"] = string.char(0x8b),
298 ["^c"] = string.char(0x8c),
299 ["^d"] = string.char(0x8d),
300 ["^e"] = string.char(0x8e),
301 ["^f"] = string.char(0x8f),
302 ["^g"] = string.char(0x90),
303 ["^h"] = string.char(0x91)
308 local c = word:sub(i, i)
310 local cc = tonumber(word:sub(i+1, i+1), 16)
316 local w = cwidth_tab[c]
318 width = width + w + 1
319 if width >= (line_width - cwidth_tab[" "]) then
322 maxw = math_max(width, maxw)
324 if #chars < MAX_INPUT_CHARS then
325 table.insert(chars, {
327 tex = char_tex(font_name, c),
328 col = ("%X"):format(cur_color),
331 ch_offs = ch_offs + w
336 width = width + cwidth_tab[" "] + 1
337 maxw = math_max(width, maxw)
338 table.insert(words, { chars=chars, w=ch_offs })
341 -- Okay, we actually build the "line texture" here.
345 local start_xpos = math.floor((line_width - maxw) / 2) + def.x_offset
347 local xpos = start_xpos
348 local ypos = (line_height + def.line_spacing)* lineno + def.y_offset
352 for word_i, word in ipairs(words) do
353 local xoffs = (xpos - start_xpos)
354 if (xoffs > 0) and ((xoffs + word.w) > maxw) then
355 table.insert(texture, fill_line(xpos, ypos, maxw, "n", font_size, colorbgw))
357 ypos = ypos + line_height + def.line_spacing
359 if lineno >= def.number_of_lines then break end
360 table.insert(texture, fill_line(xpos, ypos, maxw, cur_color, font_size, colorbgw))
362 for ch_i, ch in ipairs(word.chars) do
363 if ch.col ~= cur_color then
365 table.insert(texture, fill_line(xpos + ch.off, ypos, maxw, cur_color, font_size, colorbgw))
367 table.insert(texture, (":%d,%d=%s"):format(xpos + ch.off, ypos, ch.tex))
371 (":%d,%d="):format(xpos + word.w, ypos) .. char_tex(font_name, " ")
373 xpos = xpos + word.w + cwidth_tab[" "]
374 if xpos >= (line_width + cwidth_tab[" "]) then break end
377 table.insert(texture, fill_line(xpos, ypos, maxw, "n", font_size, colorbgw))
378 table.insert(texture, fill_line(start_xpos, ypos + line_height, maxw, "n", font_size, colorbgw))
380 return table.concat(texture), lineno
383 local function make_sign_texture(lines, pos)
384 local node = minetest.get_node(pos)
385 local def = minetest.registered_items[node.name]
393 if def.font_size and def.font_size == 31 then
395 line_width = math.floor(signs_lib.avgwidth31 * def.chars_per_line) * def.horiz_scaling
396 line_height = signs_lib.lineheight31
397 char_width = signs_lib.charwidth31
398 colorbgw = signs_lib.colorbgw31
401 line_width = math.floor(signs_lib.avgwidth15 * def.chars_per_line) * def.horiz_scaling
402 line_height = signs_lib.lineheight15
403 char_width = signs_lib.charwidth15
404 colorbgw = signs_lib.colorbgw15
407 local texture = { ("[combine:%dx%d"):format(line_width, (line_height + def.line_spacing) * def.number_of_lines * def.vert_scaling) }
411 if lineno >= def.number_of_lines then break end
412 local linetex, ln = make_line_texture(lines[i], lineno, pos, line_width, line_height, char_width, font_size, colorbgw)
413 table.insert(texture, linetex)
416 table.insert(texture, "^[makealpha:0,0,0")
417 return table.concat(texture, "")
420 local function set_obj_text(obj, text, x, pos)
421 local split = split_lines_and_words
422 local text_ansi = Utf8ToAnsi(text)
423 local n = minetest.registered_nodes[minetest.get_node(pos).name]
424 local text_scale = (n and n.text_scale) or DEFAULT_TEXT_SCALE
425 local texture = make_sign_texture(split(text_ansi), pos)
428 visual_size = text_scale,
432 signs_lib.construct_sign = function(pos)
433 local meta = minetest.get_meta(pos)
437 "textarea[0,-0.3;6.5,3;text;;${text}]"..
438 "button_exit[2,3.4;2,1;ok;"..S("Write").."]"..
439 "background[-0.5,-0.5;7,5;signs_lib_sign_bg.jpg]")
440 local i = meta:get_string("infotext")
441 if i == "" then -- it wasn't even set, so set it.
442 meta:set_string("infotext", "")
446 function signs_lib.destruct_sign(pos)
447 local objects = minetest.get_objects_inside_radius(pos, 0.5)
448 for _, v in ipairs(objects) do
449 local e = v:get_luaentity()
450 if e and e.name == "signs_lib:text" then
456 local function make_infotext(text)
457 text = trim_input(text)
458 local lines = split_lines_and_words(text) or {}
460 for _, line in ipairs(lines) do
461 table.insert(lines2, (table.concat(line, " "):gsub("#[0-9a-fA-F]", ""):gsub("##", "#")))
463 return table.concat(lines2, "\n")
466 function signs_lib.update_sign(pos, fields)
467 local meta = minetest.get_meta(pos)
469 local text = fields and fields.text or meta:get_string("text")
470 text = trim_input(text)
472 local owner = meta:get_string("owner")
474 if owner ~= "" then ownstr = S("Locked sign, owned by @1\n", owner) end
476 meta:set_string("text", text)
477 meta:set_string("infotext", ownstr..make_infotext(text).." ")
479 local objects = minetest.get_objects_inside_radius(pos, 0.5)
481 for _, v in ipairs(objects) do
482 local e = v:get_luaentity()
483 if e and e.name == "signs_lib:text" then
487 set_obj_text(v, text, nil, pos)
496 -- if there is no entity
497 local signnode = minetest.get_node(pos)
498 local signname = signnode.name
499 local def = minetest.registered_items[signname]
500 if not def.entity_info or not def.entity_info.yaw[signnode.param2 + 1] then return end
501 local obj = minetest.add_entity(pos, "signs_lib:text")
503 obj:setyaw(def.entity_info.yaw[signnode.param2 + 1])
505 mesh = def.entity_info.mesh,
509 function signs_lib.receive_fields(pos, formname, fields, sender)
510 if fields and fields.text and fields.ok and signs_lib.can_modify(pos, sender) then
511 minetest.log("action", S("@1 wrote \"@2\" to sign at @3",
512 (sender:get_player_name() or ""),
513 fields.text:gsub('\\', '\\\\'):gsub("\n", "\\n"),
514 minetest.pos_to_string(pos)
516 signs_lib.update_sign(pos, fields)
520 function signs_lib.can_modify(pos, player)
521 local meta = minetest.get_meta(pos)
522 local owner = meta:get_string("owner")
523 local playername = player:get_player_name()
525 if minetest.is_protected(pos, playername) then
526 minetest.record_protection_violation(pos, playername)
531 or playername == owner
532 or (minetest.check_player_privs(playername, {sign_editor=true}))
533 or (playername == minetest.settings:get("name")) then
536 minetest.record_protection_violation(pos, playername)
540 local signs_text_on_activate = function(self)
541 local pos = self.object:getpos()
542 local meta = minetest.get_meta(pos)
543 local signnode = minetest.get_node(pos)
544 local signname = signnode.name
545 local def = minetest.registered_items[signname]
546 local text = meta:get_string("text")
547 if text and def and def.entity_info then
548 text = trim_input(text)
549 set_obj_text(self.object, text, nil, pos)
550 self.object:set_properties({
551 mesh = def.entity_info.mesh,
556 minetest.register_entity("signs_lib:text", {
557 collisionbox = { 0, 0, 0, 0, 0, 0 },
559 mesh = "signs_lib_standard_wall_sign_entity.obj",
561 on_activate = signs_text_on_activate,
564 -- make selection boxes
565 -- sizex/sizey specified in inches because that's what MUTCD uses.
567 function signs_lib.make_selection_boxes(sizex, sizey, onpole, xoffs, yoffs, zoffs, fdir)
569 local tx = (sizex * 0.0254 ) / 2
570 local ty = (sizey * 0.0254 ) / 2
571 local xo = xoffs and xoffs * 0.0254 or 0
572 local yo = yoffs and yoffs * 0.0254 or 0
573 local zo = zoffs and zoffs * 0.0254 or 0
575 if onpole == "_onpole" then
578 type = "wallmounted",
579 wall_side = { -0.5 - 0.3125 + zo, -ty + yo, -tx + xo, -0.4375 - 0.3125 + zo, ty + yo , tx + xo },
580 wall_top = {-0.5, -0.5, -0.5, 0.5, 0.5, 0.5 },
581 wall_bottom = {-0.5, -0.5, -0.5, 0.5, 0.5, 0.5 },
586 fixed = { -tx + xo, -ty + yo, 0.5 + 0.3125 + zo, tx + xo, ty + yo, 0.4375 + 0.3125 + zo }
592 type = "wallmounted",
593 wall_side = { -0.5 + zo, -ty + yo, -tx + xo, -0.4375 + zo, ty + yo, tx + xo },
594 wall_top = { -tx - xo, 0.5 + zo, -ty + yo, tx - xo, 0.4375 + zo, ty + yo},
595 wall_bottom = { -tx - xo, -0.5 + zo, -ty + yo, tx - xo, -0.4375 + zo, ty + yo }
600 fixed = { -tx + xo, -ty + yo, 0.5 + zo, tx + xo, ty + yo, 0.4375 + zo}
606 function signs_lib.check_for_pole(pos, pointed_thing)
607 local ppos = minetest.get_pointed_thing_position(pointed_thing)
608 local pnode = minetest.get_node(ppos)
609 local pdef = minetest.registered_items[pnode.name]
614 if (signs_lib.allowed_poles[pnode.name]
615 or (pdef and pdef.drawtype == "fencelike")
616 or string.find(pnode.name, "default:fence_")
617 or string.find(pnode.name, "_post")
618 or string.find(pnode.name, "fencepost")
619 or (pnode.name == "streets:bigpole" and pnode.param2 < 4)
620 or (pnode.name == "streets:bigpole" and pnode.param2 > 19 and pnode.param2 < 24)
623 (pos.x ~= ppos.x or pos.z ~= ppos.z) then
624 print("signs_lib.check_for_pole returned true")
629 function signs_lib.after_place_node(pos, placer, itemstack, pointed_thing, locked)
630 local ppos = minetest.get_pointed_thing_position(pointed_thing)
631 local pnode = minetest.get_node(ppos)
632 local pdef = minetest.registered_items[pnode.name]
633 local playername = placer:get_player_name()
635 if signs_lib.check_for_pole(pos, pointed_thing) then
636 local node = minetest.get_node(pos)
637 minetest.swap_node(pos, {name = itemstack:get_name().."_onpole", param2 = node.param2})
640 local meta = minetest.get_meta(pos)
641 meta:set_string("owner", playername)
642 meta:set_string("infotext", S("Locked sign, owned by @1\n", playername))
646 function signs_lib.register_fence_with_sign()
647 minetest.log("warning", "[signs_lib] ".."Attempt to call no longer used function signs_lib.register_fence_with_sign()")
650 -- restore signs' text after /clearobjects and the like, the next time
651 -- a block is reloaded by the server.
653 minetest.register_lbm({
654 nodenames = signs_lib.lbm_restore_nodes,
655 name = "signs_lib:restore_sign_text",
656 label = "Restore sign text",
657 run_at_every_load = true,
658 action = function(pos, node)
659 signs_lib.update_sign(pos,nil,nil,node)
663 -- Convert old signs on fenceposts into signs on.. um.. fence posts :P
665 minetest.register_lbm({
666 nodenames = signs_lib.old_fenceposts_with_signs,
667 name = "signs_lib:fix_fencepost_signs",
668 label = "Change single-node signs on fences into normal",
669 run_at_every_load = true,
670 action = function(pos, node)
672 local fdir = node.param2 % 8
674 x = pos.x + signs_lib.fdir_to_back[fdir+1][1],
676 z = pos.z + signs_lib.fdir_to_back[fdir+1][2]
679 if minetest.get_node(signpos).name == "air" then
680 local new_wmdir = minetest.dir_to_wallmounted(minetest.facedir_to_dir(fdir))
681 local oldfence = signs_lib.old_fenceposts[node.name]
682 local newsign = signs_lib.old_fenceposts_replacement_signs[node.name]
684 for _, v in ipairs(minetest.get_objects_inside_radius(pos, 0.5)) do
685 local e = v:get_luaentity()
686 if e and e.name == "signs_lib:text" then
691 local oldmeta = minetest.get_meta(pos):to_table()
692 minetest.set_node(pos, {name = oldfence})
693 minetest.set_node(signpos, { name = newsign, param2 = new_wmdir })
694 local newmeta = minetest.get_meta(signpos)
695 newmeta:from_table(oldmeta)
696 signs_lib.update_sign(signpos)
701 signs_lib.block_list = {}
702 signs_lib.totalblocks = 0
704 -- Maintain a list of currently-loaded blocks
705 minetest.register_lbm({
706 nodenames = {"group:sign"},
707 name = "signs_lib:update_block_list",
708 label = "Update list of loaded blocks, log only those with signs",
709 run_at_every_load = true,
710 action = function(pos, node)
711 -- yeah, yeah... I know I'm hashing a block pos, but it's still just a set of coords
712 local hash = minetest.hash_node_position(vector.floor(vector.divide(pos, core.MAP_BLOCKSIZE)))
713 if not signs_lib.block_list[hash] then
714 signs_lib.block_list[hash] = true
715 signs_lib.totalblocks = signs_lib.totalblocks + 1
720 minetest.register_chatcommand("regen_signs", {
722 privs = {server = true},
723 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.",
724 func = function(player_name, params)
727 for b in pairs(signs_lib.block_list) do
728 local blockpos = minetest.get_position_from_hash(b)
729 local pos1 = vector.multiply(blockpos, core.MAP_BLOCKSIZE)
730 local pos2 = vector.add(pos1, core.MAP_BLOCKSIZE - 1)
731 if minetest.get_node_or_nil(vector.add(pos1, core.MAP_BLOCKSIZE/2)) then
732 local signs_in_block = minetest.find_nodes_in_area(pos1, pos2, {"group:sign"})
733 allsigns[#allsigns + 1] = signs_in_block
734 totalsigns = totalsigns + #signs_in_block
736 signs_lib.block_list[b] = nil -- if the block is no longer loaded, remove it from the table
737 signs_lib.totalblocks = signs_lib.totalblocks - 1
740 if signs_lib.totalblocks < 0 then signs_lib.totalblocks = 0 end
741 if totalsigns == 0 then
742 minetest.chat_send_player(player_name, "There are no signs in the currently-loaded terrain.")
743 signs_lib.block_list = {}
747 minetest.chat_send_player(player_name, "Found a total of "..totalsigns.." sign nodes across "..signs_lib.totalblocks.." blocks.")
748 minetest.chat_send_player(player_name, "Regenerating sign entities...")
750 for _, b in pairs(allsigns) do
751 for _, pos in ipairs(b) do
752 local objects = minetest.get_objects_inside_radius(pos, 0.5)
754 for _, v in ipairs(objects) do
758 local node = minetest.get_node(pos)
759 local def = minetest.registered_items[node.name]
760 if def and def.entity_info then
761 signs_lib.update_sign(pos)
765 minetest.chat_send_player(player_name, "Finished.")