]> git.lizzy.rs Git - signs_lib.git/blob - api.lua
Fix missing offsets on wallmount selboxes
[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.7
14 signs_lib.standard_vscale = 1.75
15 signs_lib.standard_lspace = 1
16 signs_lib.standard_fsize = 15
17 signs_lib.standard_xoffs = 5
18 signs_lib.standard_yoffs = 38
19 signs_lib.standard_cpl = 25
20
21 signs_lib.standard_wood_groups =  {choppy = 2, flammable = 2, oddly_breakable_by_hand = 3}
22 signs_lib.standard_steel_groups = {cracky = 2, oddly_breakable_by_hand = 3} 
23
24 signs_lib.standard_yaw = {
25         0,
26         math.pi / -2,
27         math.pi,
28         math.pi / 2,
29 }
30
31 signs_lib.wallmounted_yaw = {
32         nil,
33         nil,
34         math.pi / -2,
35         math.pi / 2,
36         0,
37         math.pi,
38 }
39
40 local wall_dir_change = {
41         [0] = 2,
42         2,
43         5,
44         4,
45         2,
46         3,
47 }
48
49 signs_lib.fdir_to_back = {
50         {  0, -1 },
51         { -1,  0 },
52         {  0,  1 },
53         {  1,  0 },
54 }
55
56 signs_lib.wall_fdir_to_back = {
57         nil,
58         nil,
59         {  0,  1 },
60         {  0, -1 },
61         { -1,  0 },
62         {  1,  0 },
63 }
64
65 -- Initialize character texture cache
66 local ctexcache = {}
67
68 signs_lib.wallmounted_rotate = function(pos, node, user, mode)
69         if not signs_lib.can_modify(pos, user) then return false end
70
71         if mode ~= screwdriver.ROTATE_FACE or string.match(node.name, "_onpole") then
72                 return false
73         end
74         minetest.swap_node(pos, { name = node.name, param2 = wall_dir_change[node.param2 % 6] })
75         for _, v in ipairs(minetest.get_objects_inside_radius(pos, 0.5)) do
76                 local e = v:get_luaentity()
77                 if e and e.name == "signs_lib:text" then
78                         v:remove()
79                 end
80         end
81         signs_lib.update_sign(pos)
82         return true
83 end
84
85 signs_lib.facedir_rotate = function(pos, node, user, mode)
86         if not signs_lib.can_modify(pos, user) then return false end
87
88         if mode ~= screwdriver.ROTATE_FACE or string.match(node.name, "_onpole") then
89                 return false
90         end
91
92         local newparam2 = node.param2 + 1
93         if newparam2 > 3 then newparam2 = 0 end
94
95         minetest.swap_node(pos, { name = node.name, param2 = newparam2 })
96         for _, v in ipairs(minetest.get_objects_inside_radius(pos, 0.5)) do
97                 local e = v:get_luaentity()
98                 if e and e.name == "signs_lib:text" then
99                         v:remove()
100                 end
101         end
102         signs_lib.update_sign(pos)
103         return true
104 end
105
106 local DEFAULT_TEXT_SCALE = {x=10, y=10}
107
108 -- infinite stacks
109
110 if not minetest.settings:get_bool("creative_mode") then
111         signs_lib.expect_infinite_stacks = false
112 else
113         signs_lib.expect_infinite_stacks = true
114 end
115
116 -- CONSTANTS
117
118 -- Path to the textures.
119 local TP = signs_lib.path .. "/textures"
120 -- Font file formatter
121 local CHAR_FILE = "%s_%02x.png"
122 -- Fonts path
123 local CHAR_PATH = TP .. "/" .. CHAR_FILE
124
125 -- Lots of overkill here. KISS advocates, go away, shoo! ;) -- kaeza
126
127 local PNG_HDR = string.char(0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A)
128
129 -- check if a file does exist
130 -- to avoid reopening file after checking again
131 -- pass TRUE as second argument
132 local function file_exists(name, return_handle, mode)
133         mode = mode or "r";
134         local f = io.open(name, mode)
135         if f ~= nil then
136                 if (return_handle) then
137                         return f
138                 end
139                 io.close(f) 
140                 return true 
141         else 
142                 return false 
143         end
144 end
145
146 -- Read the image size from a PNG file.
147 -- Returns image_w, image_h.
148 -- Only the LSB is read from each field!
149 function signs_lib.read_image_size(filename)
150         local f = file_exists(filename, true, "rb")
151         -- file might not exist (don't crash the game)
152         if (not f) then
153                 return 0, 0
154         end
155         f:seek("set", 0x0)
156         local hdr = f:read(string.len(PNG_HDR))
157         if hdr ~= PNG_HDR then
158                 f:close()
159                 return
160         end
161         f:seek("set", 0x13)
162         local ws = f:read(1)
163         f:seek("set", 0x17)
164         local hs = f:read(1)
165         f:close()
166         return ws:byte(), hs:byte()
167 end
168
169 -- 4 rows, max 80 chars per, plus a bit of fudge to
170 -- avoid excess trimming (e.g. due to color codes)
171
172 local MAX_INPUT_CHARS = 400
173
174 -- helper functions to trim sign text input/output
175
176 local function trim_input(text)
177         return text:sub(1, math.min(MAX_INPUT_CHARS, text:len()))
178 end
179
180 local function build_char_db(font_size)
181
182         local cw = {}
183
184         -- To calculate average char width.
185         local total_width = 0
186         local char_count = 0
187
188         for c = 32, 255 do
189                 local w, h = signs_lib.read_image_size(CHAR_PATH:format("signs_lib_font_"..font_size.."px", c))
190                 if w and h then
191                         local ch = string.char(c)
192                         cw[ch] = w
193                         total_width = total_width + w
194                         char_count = char_count + 1
195                 end
196         end
197
198         local cbw, cbh = signs_lib.read_image_size(TP.."/signs_lib_color_"..font_size.."px_n.png")
199         assert(cbw and cbh, "error reading bg dimensions")
200         return cw, cbw, cbh, (total_width / char_count)
201 end
202
203 signs_lib.charwidth15,
204 signs_lib.colorbgw15,
205 signs_lib.lineheight15,
206 signs_lib.avgwidth15 = build_char_db(15)
207
208 signs_lib.charwidth31,
209 signs_lib.colorbgw31,
210 signs_lib.lineheight31,
211 signs_lib.avgwidth31 = build_char_db(31)
212
213 local sign_groups = {choppy=2, dig_immediate=2}
214 local fences_with_sign = { }
215
216 -- some local helper functions
217
218 local function split_lines_and_words(text)
219         if not text then return end
220         local lines = { }
221         for _, line in ipairs(text:split("\n")) do
222                 table.insert(lines, line:split(" "))
223         end
224         return lines
225 end
226
227 local math_max = math.max
228
229 local function fill_line(x, y, w, c, font_size, colorbgw)
230         c = c or "0"
231         local tex = { }
232         for xx = 0, math.max(0, w), colorbgw do
233                 table.insert(tex, (":%d,%d=signs_lib_color_"..font_size.."px_%s.png"):format(x + xx, y, c))
234         end
235         return table.concat(tex)
236 end
237
238 -- make char texture file name
239 -- if texture file does not exist use fallback texture instead
240 local function char_tex(font_name, ch)
241         if ctexcache[font_name..ch] then
242                 return ctexcache[font_name..ch], true
243         else
244                 local c = ch:byte()
245                 local exists, tex = file_exists(CHAR_PATH:format(font_name, c))
246                 if exists and c ~= 14 then
247                         tex = CHAR_FILE:format(font_name, c)
248                 else
249                         tex = CHAR_FILE:format(font_name, 0x0)
250                 end
251                 ctexcache[font_name..ch] = tex
252                 return tex, exists
253         end
254 end
255
256 local function make_line_texture(line, lineno, pos, line_width, line_height, cwidth_tab, font_size, colorbgw)
257         local width = 0
258         local maxw = 0
259         local font_name = "signs_lib_font_"..font_size.."px"
260
261         local words = { }
262         local node = minetest.get_node(pos)
263         local def = minetest.registered_items[node.name]
264         local default_color = def.default_color or 0
265
266         local cur_color = tonumber(default_color, 16)
267
268         -- We check which chars are available here.
269         for word_i, word in ipairs(line) do
270                 local chars = { }
271                 local ch_offs = 0
272                 word = string.gsub(word, "%^[12345678abcdefgh]", {
273                         ["^1"] = string.char(0x81),
274                         ["^2"] = string.char(0x82),
275                         ["^3"] = string.char(0x83),
276                         ["^4"] = string.char(0x84),
277                         ["^5"] = string.char(0x85),
278                         ["^6"] = string.char(0x86),
279                         ["^7"] = string.char(0x87),
280                         ["^8"] = string.char(0x88),
281                         ["^a"] = string.char(0x8a),
282                         ["^b"] = string.char(0x8b),
283                         ["^c"] = string.char(0x8c),
284                         ["^d"] = string.char(0x8d),
285                         ["^e"] = string.char(0x8e),
286                         ["^f"] = string.char(0x8f),
287                         ["^g"] = string.char(0x90),
288                         ["^h"] = string.char(0x91)
289                 })
290                 local word_l = #word
291                 local i = 1
292                 while i <= word_l  do
293                         local c = word:sub(i, i)
294                         if c == "#" then
295                                 local cc = tonumber(word:sub(i+1, i+1), 16)
296                                 if cc then
297                                         i = i + 1
298                                         cur_color = cc
299                                 end
300                         else
301                                 local w = cwidth_tab[c]
302                                 if w then
303                                         width = width + w + 1
304                                         if width >= (line_width - cwidth_tab[" "]) then
305                                                 width = 0
306                                         else
307                                                 maxw = math_max(width, maxw)
308                                         end
309                                         if #chars < MAX_INPUT_CHARS then
310                                                 table.insert(chars, {
311                                                         off = ch_offs,
312                                                         tex = char_tex(font_name, c),
313                                                         col = ("%X"):format(cur_color),
314                                                 })
315                                         end
316                                         ch_offs = ch_offs + w
317                                 end
318                         end
319                         i = i + 1
320                 end
321                 width = width + cwidth_tab[" "] + 1
322                 maxw = math_max(width, maxw)
323                 table.insert(words, { chars=chars, w=ch_offs })
324         end
325
326         -- Okay, we actually build the "line texture" here.
327
328         local texture = { }
329
330         local start_xpos = math.floor((line_width - maxw) / 2) + def.x_offset
331
332         local xpos = start_xpos
333         local ypos = (line_height + def.line_spacing)* lineno + def.y_offset
334
335         cur_color = nil
336
337         for word_i, word in ipairs(words) do
338                 local xoffs = (xpos - start_xpos)
339                 if (xoffs > 0) and ((xoffs + word.w) > maxw) then
340                         table.insert(texture, fill_line(xpos, ypos, maxw, "n", font_size, colorbgw))
341                         xpos = start_xpos
342                         ypos = ypos + line_height + def.line_spacing
343                         lineno = lineno + 1
344                         if lineno >= def.number_of_lines then break end
345                         table.insert(texture, fill_line(xpos, ypos, maxw, cur_color, font_size, colorbgw))
346                 end
347                 for ch_i, ch in ipairs(word.chars) do
348                         if ch.col ~= cur_color then
349                                 cur_color = ch.col
350                                 table.insert(texture, fill_line(xpos + ch.off, ypos, maxw, cur_color, font_size, colorbgw))
351                         end
352                         table.insert(texture, (":%d,%d=%s"):format(xpos + ch.off, ypos, ch.tex))
353                 end
354                 table.insert(
355                         texture, 
356                         (":%d,%d="):format(xpos + word.w, ypos) .. char_tex(font_name, " ")
357                 )
358                 xpos = xpos + word.w + cwidth_tab[" "]
359                 if xpos >= (line_width + cwidth_tab[" "]) then break end
360         end
361
362         table.insert(texture, fill_line(xpos, ypos, maxw, "n", font_size, colorbgw))
363         table.insert(texture, fill_line(start_xpos, ypos + line_height, maxw, "n", font_size, colorbgw))
364
365         return table.concat(texture), lineno
366 end
367
368 local function make_sign_texture(lines, pos)
369         local node = minetest.get_node(pos)
370         local def = minetest.registered_items[node.name]
371
372         local font_size
373         local line_width
374         local line_height
375         local char_width
376         local colorbgw
377
378         if def.font_size and def.font_size == 31 then
379                 font_size = 31
380                 line_width = math.floor(signs_lib.avgwidth31 * def.chars_per_line) * def.horiz_scaling
381                 line_height = signs_lib.lineheight31
382                 char_width = signs_lib.charwidth31
383                 colorbgw = signs_lib.colorbgw31
384         else
385                 font_size = 15
386                 line_width = math.floor(signs_lib.avgwidth15 * def.chars_per_line) * def.horiz_scaling
387                 line_height = signs_lib.lineheight15
388                 char_width = signs_lib.charwidth15
389                 colorbgw = signs_lib.colorbgw15
390         end
391
392         local texture = { ("[combine:%dx%d"):format(line_width, (line_height + def.line_spacing) * def.number_of_lines * def.vert_scaling) }
393
394         local lineno = 0
395         for i = 1, #lines do
396                 if lineno >= def.number_of_lines then break end
397                 local linetex, ln = make_line_texture(lines[i], lineno, pos, line_width, line_height, char_width, font_size, colorbgw)
398                 table.insert(texture, linetex)
399                 lineno = ln + 1
400         end
401         table.insert(texture, "^[makealpha:0,0,0")
402         return table.concat(texture, "")
403 end
404
405 local function set_obj_text(obj, text, x, pos)
406         local split = split_lines_and_words
407         local text_ansi = Utf8ToAnsi(text)
408         local n = minetest.registered_nodes[minetest.get_node(pos).name]
409         local text_scale = (n and n.text_scale) or DEFAULT_TEXT_SCALE
410         local texture = make_sign_texture(split(text_ansi), pos)
411         obj:set_properties({
412                 textures={texture},
413                 visual_size = text_scale,
414         })
415 end
416
417 signs_lib.construct_sign = function(pos)
418         local meta = minetest.get_meta(pos)
419         meta:set_string(
420                 "formspec",
421                 "size[6,4]"..
422                 "textarea[0,-0.3;6.5,3;text;;${text}]"..
423                 "button_exit[2,3.4;2,1;ok;"..S("Write").."]"..
424                 "background[-0.5,-0.5;7,5;signs_lib_sign_bg.jpg]")
425         meta:set_string("infotext", "")
426 end
427
428 function signs_lib.destruct_sign(pos)
429         local objects = minetest.get_objects_inside_radius(pos, 0.5)
430         for _, v in ipairs(objects) do
431                 local e = v:get_luaentity()
432                 if e and e.name == "signs_lib:text" then
433                         v:remove()
434                 end
435         end
436 end
437
438 local function make_infotext(text)
439         text = trim_input(text)
440         local lines = split_lines_and_words(text) or {}
441         local lines2 = { }
442         for _, line in ipairs(lines) do
443                 table.insert(lines2, (table.concat(line, " "):gsub("#[0-9a-fA-F]", ""):gsub("##", "#")))
444         end
445         return table.concat(lines2, "\n")
446 end
447
448 function signs_lib.update_sign(pos, fields)
449         local meta = minetest.get_meta(pos)
450
451         local text = fields and fields.text or meta:get_string("text")
452         text = trim_input(text)
453
454         local owner = meta:get_string("owner")
455         ownstr = ""
456         if owner ~= "" then ownstr = S("Locked sign, owned by @1\n", owner) end
457
458         meta:set_string("text", text)
459         meta:set_string("infotext", ownstr..make_infotext(text).." ")
460
461         local objects = minetest.get_objects_inside_radius(pos, 0.5)
462         local found
463         for _, v in ipairs(objects) do
464                 local e = v:get_luaentity()
465                 if e and e.name == "signs_lib:text" then
466                         if found then
467                                 v:remove()
468                         else
469                                 set_obj_text(v, text, nil, pos)
470                                 found = true
471                         end
472                 end
473         end
474         if found then
475                 return
476         end
477
478         -- if there is no entity
479         local signnode = minetest.get_node(pos)
480         local signname = signnode.name
481         local def = minetest.registered_items[signname]
482         if not def.entity_info or not def.entity_info.yaw[signnode.param2 + 1] then return end
483         local obj = minetest.add_entity(pos, "signs_lib:text")
484
485         obj:setyaw(def.entity_info.yaw[signnode.param2 + 1])
486         obj:set_properties({
487                 mesh = def.entity_info.mesh,
488         })
489 end
490
491 function signs_lib.receive_fields(pos, formname, fields, sender)
492         if fields and fields.text and fields.ok and signs_lib.can_modify(pos, sender) then
493                 minetest.log("action", S("@1 wrote \"@2\" to sign at @3",
494                         (sender:get_player_name() or ""),
495                         fields.text:gsub('\\', '\\\\'):gsub("\n", "\\n"),
496                         minetest.pos_to_string(pos)
497                 ))
498                 signs_lib.update_sign(pos, fields)
499         end
500 end
501
502 function signs_lib.can_modify(pos, player)
503         local meta = minetest.get_meta(pos)
504         local owner = meta:get_string("owner")
505         local playername = player:get_player_name()
506
507         if minetest.is_protected(pos, playername) then 
508                 minetest.record_protection_violation(pos, playername)
509                 return false
510         end
511
512         if owner == ""
513           or playername == owner
514           or (minetest.check_player_privs(playername, {sign_editor=true}))
515           or (playername == minetest.settings:get("name")) then
516                 return true
517         end
518         minetest.record_protection_violation(pos, playername)
519         return false
520 end
521
522 local signs_text_on_activate = function(self)
523         local pos = self.object:getpos()
524         local meta = minetest.get_meta(pos)
525         local signnode = minetest.get_node(pos)
526         local signname = signnode.name
527         local def = minetest.registered_items[signname]
528         local text = meta:get_string("text")
529         if text and def and def.entity_info then
530                 text = trim_input(text)
531                 set_obj_text(self.object, text, nil, pos)
532                 self.object:set_properties({
533                         mesh = def.entity_info.mesh,
534                 })
535         end
536 end
537
538 minetest.register_entity("signs_lib:text", {
539         collisionbox = { 0, 0, 0, 0, 0, 0 },
540         visual = "mesh",
541         mesh = "signs_lib_basic_entity.obj",
542         textures = {},
543         on_activate = signs_text_on_activate,
544 })
545
546 -- make selection boxes
547 -- sizex/sizey specified in inches because that's what MUTCD uses.
548
549 function signs_lib.make_selection_boxes(sizex, sizey, onpole, xoffs, yoffs, zoffs, fdir)
550
551         local tx = (sizex * 0.0254 ) / 2
552         local ty = (sizey * 0.0254 ) / 2
553         local xo = xoffs and xoffs * 0.0254 or 0
554         local yo = yoffs and yoffs * 0.0254 or 0
555         local zo = zoffs and zoffs * 0.0254 or 0
556
557         if onpole == "_onpole" then
558                 if not fdir then
559                         return {
560                                 type = "wallmounted",
561                                 wall_side =   { -0.5 - 0.3125 + zo, -ty + yo, -tx + xo, -0.4375 - 0.3125 + zo, ty + yo , tx + xo },
562                                 wall_top =    {-0.5, -0.5, -0.5, 0.5, 0.5, 0.5 },
563                                 wall_bottom = {-0.5, -0.5, -0.5, 0.5, 0.5, 0.5 },
564                         }
565                 else
566                         return {
567                                 type = "fixed",
568                                 fixed = { -tx + xo, -ty + yo, 0.5 + 0.3125 + zo, tx + xo, ty + yo, 0.4375 + 0.3125 + zo }
569                         }
570                 end
571         else
572                 if not fdir then
573                         return {
574                                 type = "wallmounted",
575                                 wall_side =   { -0.5 + zo, -ty + yo, -tx + xo, -0.4375 + zo, ty + yo, tx + xo },
576                                 wall_top =    { -tx - xo, 0.5 + zo, -ty + yo, tx - xo, 0.4375 + zo, ty + yo},
577                                 wall_bottom = { -tx - xo, -0.5 + zo, -ty + yo, tx - xo, -0.4375 + zo, ty + yo }
578                         }
579                 else
580                         return {
581                                 type = "fixed",
582                                 fixed = { -tx + xo, -ty + yo, 0.5 + zo, tx + xo, ty + yo, 0.4375 + zo}
583                         }
584                 end
585         end
586 end
587
588 function signs_lib.check_for_pole(pos, pointed_thing)
589         local ppos = minetest.get_pointed_thing_position(pointed_thing)
590         local pnode = minetest.get_node(ppos)
591         local pdef = minetest.registered_items[pnode.name]
592
593         print(dump(pos))
594         print(dump(ppos))
595
596         if (signs_lib.allowed_poles[pnode.name]
597                   or (pdef and pdef.drawtype == "fencelike")
598                   or string.find(pnode.name, "default:fence_")
599                   or string.find(pnode.name, "_post")
600                   or string.find(pnode.name, "fencepost")
601                   or (pnode.name == "streets:bigpole" and pnode.param2 < 4)
602                   or (pnode.name == "streets:bigpole" and pnode.param2 > 19 and pnode.param2 < 24)
603                 )
604           and
605                 (pos.x ~= ppos.x or pos.z ~= ppos.z) then
606                 print("signs_lib.check_for_pole returned true")
607                 return true
608         end
609 end
610
611 function signs_lib.after_place_node(pos, placer, itemstack, pointed_thing, locked)
612         local ppos = minetest.get_pointed_thing_position(pointed_thing)
613         local pnode = minetest.get_node(ppos)
614         local pdef = minetest.registered_items[pnode.name]
615         local playername = placer:get_player_name()
616
617         if signs_lib.check_for_pole(pos, pointed_thing) then
618                 local node = minetest.get_node(pos)
619                 minetest.swap_node(pos, {name = itemstack:get_name().."_onpole", param2 = node.param2})
620         end
621         if locked then
622                 local meta = minetest.get_meta(pos)
623                 meta:set_string("owner", playername)
624                 meta:set_string("infotext", S("Locked sign, owned by @1\n", playername))
625         end
626 end
627
628 function signs_lib.register_fence_with_sign()
629         minetest.log("warning", "[signs_lib] ".."Attempt to call no longer used function signs_lib.register_fence_with_sign()")
630 end
631
632 -- restore signs' text after /clearobjects and the like, the next time
633 -- a block is reloaded by the server.
634
635 minetest.register_lbm({
636         nodenames = signs_lib.lbm_restore_nodes,
637         name = "signs_lib:restore_sign_text",
638         label = "Restore sign text",
639         run_at_every_load = true,
640         action = function(pos, node)
641                 signs_lib.update_sign(pos,nil,nil,node)
642         end
643 })
644
645 -- Convert old signs on fenceposts into signs on.. um.. fence posts :P
646
647 minetest.register_lbm({
648         nodenames = signs_lib.old_fenceposts_with_signs,
649         name = "signs_lib:fix_fencepost_signs",
650         label = "Change single-node signs on fences into normal",
651         run_at_every_load = true,
652         action = function(pos, node)
653
654                 local fdir = node.param2 % 8
655                 local signpos = {
656                         x = pos.x + signs_lib.fdir_to_back[fdir+1][1],
657                         y = pos.y,
658                         z = pos.z + signs_lib.fdir_to_back[fdir+1][2]
659                 }
660
661                 if minetest.get_node(signpos).name == "air" then
662                         local new_wmdir = minetest.dir_to_wallmounted(minetest.facedir_to_dir(fdir))
663                         local oldfence =  signs_lib.old_fenceposts[node.name]
664                         local newsign =   signs_lib.old_fenceposts_replacement_signs[node.name]
665
666                         for _, v in ipairs(minetest.get_objects_inside_radius(pos, 0.5)) do
667                                 local e = v:get_luaentity()
668                                 if e and e.name == "signs_lib:text" then
669                                         v:remove()
670                                 end
671                         end
672
673                         local oldmeta = minetest.get_meta(pos):to_table()
674                         minetest.set_node(pos, {name = oldfence})
675                         minetest.set_node(signpos, { name = newsign, param2 = new_wmdir })
676                         local newmeta = minetest.get_meta(signpos)
677                         newmeta:from_table(oldmeta)
678                         signs_lib.update_sign(signpos)
679                 end
680         end
681 })