]> git.lizzy.rs Git - minetest.git/blob - builtin/common/misc_helpers.lua
1e9a08851fe9a2a653a125f68e760365549eced1
[minetest.git] / builtin / common / misc_helpers.lua
1 -- Minetest: builtin/misc_helpers.lua
2
3 --------------------------------------------------------------------------------
4 -- Localize functions to avoid table lookups (better performance).
5 local string_sub, string_find = string.sub, string.find
6
7 --------------------------------------------------------------------------------
8 function basic_dump(o)
9         local tp = type(o)
10         if tp == "number" then
11                 return tostring(o)
12         elseif tp == "string" then
13                 return string.format("%q", o)
14         elseif tp == "boolean" then
15                 return tostring(o)
16         elseif tp == "nil" then
17                 return "nil"
18         -- Uncomment for full function dumping support.
19         -- Not currently enabled because bytecode isn't very human-readable and
20         -- dump's output is intended for humans.
21         --elseif tp == "function" then
22         --      return string.format("loadstring(%q)", string.dump(o))
23         else
24                 return string.format("<%s>", tp)
25         end
26 end
27
28 local keywords = {
29         ["and"] = true,
30         ["break"] = true,
31         ["do"] = true,
32         ["else"] = true,
33         ["elseif"] = true,
34         ["end"] = true,
35         ["false"] = true,
36         ["for"] = true,
37         ["function"] = true,
38         ["goto"] = true,  -- Lua 5.2
39         ["if"] = true,
40         ["in"] = true,
41         ["local"] = true,
42         ["nil"] = true,
43         ["not"] = true,
44         ["or"] = true,
45         ["repeat"] = true,
46         ["return"] = true,
47         ["then"] = true,
48         ["true"] = true,
49         ["until"] = true,
50         ["while"] = true,
51 }
52 local function is_valid_identifier(str)
53         if not str:find("^[a-zA-Z_][a-zA-Z0-9_]*$") or keywords[str] then
54                 return false
55         end
56         return true
57 end
58
59 --------------------------------------------------------------------------------
60 -- Dumps values in a line-per-value format.
61 -- For example, {test = {"Testing..."}} becomes:
62 --   _["test"] = {}
63 --   _["test"][1] = "Testing..."
64 -- This handles tables as keys and circular references properly.
65 -- It also handles multiple references well, writing the table only once.
66 -- The dumped argument is internal-only.
67
68 function dump2(o, name, dumped)
69         name = name or "_"
70         -- "dumped" is used to keep track of serialized tables to handle
71         -- multiple references and circular tables properly.
72         -- It only contains tables as keys.  The value is the name that
73         -- the table has in the dump, eg:
74         -- {x = {"y"}} -> dumped[{"y"}] = '_["x"]'
75         dumped = dumped or {}
76         if type(o) ~= "table" then
77                 return string.format("%s = %s\n", name, basic_dump(o))
78         end
79         if dumped[o] then
80                 return string.format("%s = %s\n", name, dumped[o])
81         end
82         dumped[o] = name
83         -- This contains a list of strings to be concatenated later (because
84         -- Lua is slow at individual concatenation).
85         local t = {}
86         for k, v in pairs(o) do
87                 local keyStr
88                 if type(k) == "table" then
89                         if dumped[k] then
90                                 keyStr = dumped[k]
91                         else
92                                 -- Key tables don't have a name, so use one of
93                                 -- the form _G["table: 0xFFFFFFF"]
94                                 keyStr = string.format("_G[%q]", tostring(k))
95                                 -- Dump key table
96                                 t[#t + 1] = dump2(k, keyStr, dumped)
97                         end
98                 else
99                         keyStr = basic_dump(k)
100                 end
101                 local vname = string.format("%s[%s]", name, keyStr)
102                 t[#t + 1] = dump2(v, vname, dumped)
103         end
104         return string.format("%s = {}\n%s", name, table.concat(t))
105 end
106
107 --------------------------------------------------------------------------------
108 -- This dumps values in a one-statement format.
109 -- For example, {test = {"Testing..."}} becomes:
110 -- [[{
111 --      test = {
112 --              "Testing..."
113 --      }
114 -- }]]
115 -- This supports tables as keys, but not circular references.
116 -- It performs poorly with multiple references as it writes out the full
117 -- table each time.
118 -- The indent field specifies a indentation string, it defaults to a tab.
119 -- Use the empty string to disable indentation.
120 -- The dumped and level arguments are internal-only.
121
122 function dump(o, indent, nested, level)
123         local t = type(o)
124         if not level and t == "userdata" then
125                 -- when userdata (e.g. player) is passed directly, print its metatable:
126                 return "userdata metatable: " .. dump(getmetatable(o))
127         end
128         if t ~= "table" then
129                 return basic_dump(o)
130         end
131
132         -- Contains table -> true/nil of currently nested tables
133         nested = nested or {}
134         if nested[o] then
135                 return "<circular reference>"
136         end
137         nested[o] = true
138         indent = indent or "\t"
139         level = level or 1
140
141         local ret = {}
142         local dumped_indexes = {}
143         for i, v in ipairs(o) do
144                 ret[#ret + 1] = dump(v, indent, nested, level + 1)
145                 dumped_indexes[i] = true
146         end
147         for k, v in pairs(o) do
148                 if not dumped_indexes[k] then
149                         if type(k) ~= "string" or not is_valid_identifier(k) then
150                                 k = "["..dump(k, indent, nested, level + 1).."]"
151                         end
152                         v = dump(v, indent, nested, level + 1)
153                         ret[#ret + 1] = k.." = "..v
154                 end
155         end
156         nested[o] = nil
157         if indent ~= "" then
158                 local indent_str = "\n"..string.rep(indent, level)
159                 local end_indent_str = "\n"..string.rep(indent, level - 1)
160                 return string.format("{%s%s%s}",
161                                 indent_str,
162                                 table.concat(ret, ","..indent_str),
163                                 end_indent_str)
164         end
165         return "{"..table.concat(ret, ", ").."}"
166 end
167
168 --------------------------------------------------------------------------------
169 function string.split(str, delim, include_empty, max_splits, sep_is_pattern)
170         delim = delim or ","
171         max_splits = max_splits or -2
172         local items = {}
173         local pos, len = 1, #str
174         local plain = not sep_is_pattern
175         max_splits = max_splits + 1
176         repeat
177                 local np, npe = string_find(str, delim, pos, plain)
178                 np, npe = (np or (len+1)), (npe or (len+1))
179                 if (not np) or (max_splits == 1) then
180                         np = len + 1
181                         npe = np
182                 end
183                 local s = string_sub(str, pos, np - 1)
184                 if include_empty or (s ~= "") then
185                         max_splits = max_splits - 1
186                         items[#items + 1] = s
187                 end
188                 pos = npe + 1
189         until (max_splits == 0) or (pos > (len + 1))
190         return items
191 end
192
193 --------------------------------------------------------------------------------
194 function table.indexof(list, val)
195         for i, v in ipairs(list) do
196                 if v == val then
197                         return i
198                 end
199         end
200         return -1
201 end
202
203 --------------------------------------------------------------------------------
204 if INIT ~= "client" then
205         function file_exists(filename)
206                 local f = io.open(filename, "r")
207                 if f == nil then
208                         return false
209                 else
210                         f:close()
211                         return true
212                 end
213         end
214 end
215 --------------------------------------------------------------------------------
216 function string:trim()
217         return (self:gsub("^%s*(.-)%s*$", "%1"))
218 end
219
220 --------------------------------------------------------------------------------
221 function math.hypot(x, y)
222         local t
223         x = math.abs(x)
224         y = math.abs(y)
225         t = math.min(x, y)
226         x = math.max(x, y)
227         if x == 0 then return 0 end
228         t = t / x
229         return x * math.sqrt(1 + t * t)
230 end
231
232 --------------------------------------------------------------------------------
233 function math.sign(x, tolerance)
234         tolerance = tolerance or 0
235         if x > tolerance then
236                 return 1
237         elseif x < -tolerance then
238                 return -1
239         end
240         return 0
241 end
242
243 --------------------------------------------------------------------------------
244 function math.factorial(x)
245         assert(x % 1 == 0 and x >= 0, "factorial expects a non-negative integer")
246         if x >= 171 then
247                 -- 171! is greater than the biggest double, no need to calculate
248                 return math.huge
249         end
250         local v = 1
251         for k = 2, x do
252                 v = v * k
253         end
254         return v
255 end
256
257 --------------------------------------------------------------------------------
258 function get_last_folder(text,count)
259         local parts = text:split(DIR_DELIM)
260
261         if count == nil then
262                 return parts[#parts]
263         end
264
265         local retval = ""
266         for i=1,count,1 do
267                 retval = retval .. parts[#parts - (count-i)] .. DIR_DELIM
268         end
269
270         return retval
271 end
272
273 --------------------------------------------------------------------------------
274 function cleanup_path(temppath)
275
276         local parts = temppath:split("-")
277         temppath = ""
278         for i=1,#parts,1 do
279                 if temppath ~= "" then
280                         temppath = temppath .. "_"
281                 end
282                 temppath = temppath .. parts[i]
283         end
284
285         parts = temppath:split(".")
286         temppath = ""
287         for i=1,#parts,1 do
288                 if temppath ~= "" then
289                         temppath = temppath .. "_"
290                 end
291                 temppath = temppath .. parts[i]
292         end
293
294         parts = temppath:split("'")
295         temppath = ""
296         for i=1,#parts,1 do
297                 if temppath ~= "" then
298                         temppath = temppath .. ""
299                 end
300                 temppath = temppath .. parts[i]
301         end
302
303         parts = temppath:split(" ")
304         temppath = ""
305         for i=1,#parts,1 do
306                 if temppath ~= "" then
307                         temppath = temppath
308                 end
309                 temppath = temppath .. parts[i]
310         end
311
312         return temppath
313 end
314
315 function core.formspec_escape(text)
316         if text ~= nil then
317                 text = string.gsub(text,"\\","\\\\")
318                 text = string.gsub(text,"%]","\\]")
319                 text = string.gsub(text,"%[","\\[")
320                 text = string.gsub(text,";","\\;")
321                 text = string.gsub(text,",","\\,")
322         end
323         return text
324 end
325
326
327 function core.wrap_text(text, max_length, as_table)
328         local result = {}
329         local line = {}
330         if #text <= max_length then
331                 return as_table and {text} or text
332         end
333
334         for word in text:gmatch('%S+') do
335                 local cur_length = #table.concat(line, ' ')
336                 if cur_length > 0 and cur_length + #word + 1 >= max_length then
337                         -- word wouldn't fit on current line, move to next line
338                         table.insert(result, table.concat(line, ' '))
339                         line = {}
340                 end
341                 table.insert(line, word)
342         end
343
344         table.insert(result, table.concat(line, ' '))
345         return as_table and result or table.concat(result, '\n')
346 end
347
348 --------------------------------------------------------------------------------
349
350 if INIT == "game" then
351         local dirs1 = {9, 18, 7, 12}
352         local dirs2 = {20, 23, 22, 21}
353
354         function core.rotate_and_place(itemstack, placer, pointed_thing,
355                         infinitestacks, orient_flags, prevent_after_place)
356                 orient_flags = orient_flags or {}
357
358                 local unode = core.get_node_or_nil(pointed_thing.under)
359                 if not unode then
360                         return
361                 end
362                 local undef = core.registered_nodes[unode.name]
363                 if undef and undef.on_rightclick then
364                         return undef.on_rightclick(pointed_thing.under, unode, placer,
365                                         itemstack, pointed_thing)
366                 end
367                 local fdir = placer and core.dir_to_facedir(placer:get_look_dir()) or 0
368
369                 local above = pointed_thing.above
370                 local under = pointed_thing.under
371                 local iswall = (above.y == under.y)
372                 local isceiling = not iswall and (above.y < under.y)
373
374                 if undef and undef.buildable_to then
375                         iswall = false
376                 end
377
378                 if orient_flags.force_floor then
379                         iswall = false
380                         isceiling = false
381                 elseif orient_flags.force_ceiling then
382                         iswall = false
383                         isceiling = true
384                 elseif orient_flags.force_wall then
385                         iswall = true
386                         isceiling = false
387                 elseif orient_flags.invert_wall then
388                         iswall = not iswall
389                 end
390
391                 local param2 = fdir
392                 if iswall then
393                         param2 = dirs1[fdir + 1]
394                 elseif isceiling then
395                         if orient_flags.force_facedir then
396                                 param2 = 20
397                         else
398                                 param2 = dirs2[fdir + 1]
399                         end
400                 else -- place right side up
401                         if orient_flags.force_facedir then
402                                 param2 = 0
403                         end
404                 end
405
406                 local old_itemstack = ItemStack(itemstack)
407                 local new_itemstack = core.item_place_node(itemstack, placer,
408                                 pointed_thing, param2, prevent_after_place)
409                 return infinitestacks and old_itemstack or new_itemstack
410         end
411
412
413 --------------------------------------------------------------------------------
414 --Wrapper for rotate_and_place() to check for sneak and assume Creative mode
415 --implies infinite stacks when performing a 6d rotation.
416 --------------------------------------------------------------------------------
417         local creative_mode_cache = core.settings:get_bool("creative_mode")
418         local function is_creative(name)
419                 return creative_mode_cache or
420                                 core.check_player_privs(name, {creative = true})
421         end
422
423         core.rotate_node = function(itemstack, placer, pointed_thing)
424                 local name = placer and placer:get_player_name() or ""
425                 local invert_wall = placer and placer:get_player_control().sneak or false
426                 return core.rotate_and_place(itemstack, placer, pointed_thing,
427                                 is_creative(name),
428                                 {invert_wall = invert_wall}, true)
429         end
430 end
431
432 --------------------------------------------------------------------------------
433 function core.explode_table_event(evt)
434         if evt ~= nil then
435                 local parts = evt:split(":")
436                 if #parts == 3 then
437                         local t = parts[1]:trim()
438                         local r = tonumber(parts[2]:trim())
439                         local c = tonumber(parts[3]:trim())
440                         if type(r) == "number" and type(c) == "number"
441                                         and t ~= "INV" then
442                                 return {type=t, row=r, column=c}
443                         end
444                 end
445         end
446         return {type="INV", row=0, column=0}
447 end
448
449 --------------------------------------------------------------------------------
450 function core.explode_textlist_event(evt)
451         if evt ~= nil then
452                 local parts = evt:split(":")
453                 if #parts == 2 then
454                         local t = parts[1]:trim()
455                         local r = tonumber(parts[2]:trim())
456                         if type(r) == "number" and t ~= "INV" then
457                                 return {type=t, index=r}
458                         end
459                 end
460         end
461         return {type="INV", index=0}
462 end
463
464 --------------------------------------------------------------------------------
465 function core.explode_scrollbar_event(evt)
466         local retval = core.explode_textlist_event(evt)
467
468         retval.value = retval.index
469         retval.index = nil
470
471         return retval
472 end
473
474 --------------------------------------------------------------------------------
475 function core.rgba(r, g, b, a)
476         return a and string.format("#%02X%02X%02X%02X", r, g, b, a) or
477                         string.format("#%02X%02X%02X", r, g, b)
478 end
479
480 --------------------------------------------------------------------------------
481 function core.pos_to_string(pos, decimal_places)
482         local x = pos.x
483         local y = pos.y
484         local z = pos.z
485         if decimal_places ~= nil then
486                 x = string.format("%." .. decimal_places .. "f", x)
487                 y = string.format("%." .. decimal_places .. "f", y)
488                 z = string.format("%." .. decimal_places .. "f", z)
489         end
490         return "(" .. x .. "," .. y .. "," .. z .. ")"
491 end
492
493 --------------------------------------------------------------------------------
494 function core.string_to_pos(value)
495         if value == nil then
496                 return nil
497         end
498
499         local p = {}
500         p.x, p.y, p.z = string.match(value, "^([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+)$")
501         if p.x and p.y and p.z then
502                 p.x = tonumber(p.x)
503                 p.y = tonumber(p.y)
504                 p.z = tonumber(p.z)
505                 return p
506         end
507         p = {}
508         p.x, p.y, p.z = string.match(value, "^%( *([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+) *%)$")
509         if p.x and p.y and p.z then
510                 p.x = tonumber(p.x)
511                 p.y = tonumber(p.y)
512                 p.z = tonumber(p.z)
513                 return p
514         end
515         return nil
516 end
517
518
519 --------------------------------------------------------------------------------
520 function core.string_to_area(value)
521         local p1, p2 = unpack(value:split(") ("))
522         if p1 == nil or p2 == nil then
523                 return nil
524         end
525
526         p1 = core.string_to_pos(p1 .. ")")
527         p2 = core.string_to_pos("(" .. p2)
528         if p1 == nil or p2 == nil then
529                 return nil
530         end
531
532         return p1, p2
533 end
534
535 local function test_string_to_area()
536         local p1, p2 = core.string_to_area("(10.0, 5, -2) (  30.2,   4, -12.53)")
537         assert(p1.x == 10.0 and p1.y == 5 and p1.z == -2)
538         assert(p2.x == 30.2 and p2.y == 4 and p2.z == -12.53)
539
540         p1, p2 = core.string_to_area("(10.0, 5, -2  30.2,   4, -12.53")
541         assert(p1 == nil and p2 == nil)
542
543         p1, p2 = core.string_to_area("(10.0, 5,) -2  fgdf2,   4, -12.53")
544         assert(p1 == nil and p2 == nil)
545 end
546
547 test_string_to_area()
548
549 --------------------------------------------------------------------------------
550 function table.copy(t, seen)
551         local n = {}
552         seen = seen or {}
553         seen[t] = n
554         for k, v in pairs(t) do
555                 n[(type(k) == "table" and (seen[k] or table.copy(k, seen))) or k] =
556                         (type(v) == "table" and (seen[v] or table.copy(v, seen))) or v
557         end
558         return n
559 end
560
561
562 function table.insert_all(t, other)
563         for i=1, #other do
564                 t[#t + 1] = other[i]
565         end
566         return t
567 end
568
569
570 function table.key_value_swap(t)
571         local ti = {}
572         for k,v in pairs(t) do
573                 ti[v] = k
574         end
575         return ti
576 end
577
578
579 function table.shuffle(t, from, to, random)
580         from = from or 1
581         to = to or #t
582         random = random or math.random
583         local n = to - from + 1
584         while n > 1 do
585                 local r = from + n-1
586                 local l = from + random(0, n-1)
587                 t[l], t[r] = t[r], t[l]
588                 n = n-1
589         end
590 end
591
592
593 --------------------------------------------------------------------------------
594 -- mainmenu only functions
595 --------------------------------------------------------------------------------
596 if INIT == "mainmenu" then
597         function core.get_game(index)
598                 local games = core.get_games()
599
600                 if index > 0 and index <= #games then
601                         return games[index]
602                 end
603
604                 return nil
605         end
606 end
607
608 if INIT == "client" or INIT == "mainmenu" then
609         function fgettext_ne(text, ...)
610                 text = core.gettext(text)
611                 local arg = {n=select('#', ...), ...}
612                 if arg.n >= 1 then
613                         -- Insert positional parameters ($1, $2, ...)
614                         local result = ''
615                         local pos = 1
616                         while pos <= text:len() do
617                                 local newpos = text:find('[$]', pos)
618                                 if newpos == nil then
619                                         result = result .. text:sub(pos)
620                                         pos = text:len() + 1
621                                 else
622                                         local paramindex =
623                                                 tonumber(text:sub(newpos+1, newpos+1))
624                                         result = result .. text:sub(pos, newpos-1)
625                                                 .. tostring(arg[paramindex])
626                                         pos = newpos + 2
627                                 end
628                         end
629                         text = result
630                 end
631                 return text
632         end
633
634         function fgettext(text, ...)
635                 return core.formspec_escape(fgettext_ne(text, ...))
636         end
637 end
638
639 local ESCAPE_CHAR = string.char(0x1b)
640
641 function core.get_color_escape_sequence(color)
642         return ESCAPE_CHAR .. "(c@" .. color .. ")"
643 end
644
645 function core.get_background_escape_sequence(color)
646         return ESCAPE_CHAR .. "(b@" .. color .. ")"
647 end
648
649 function core.colorize(color, message)
650         local lines = tostring(message):split("\n", true)
651         local color_code = core.get_color_escape_sequence(color)
652
653         for i, line in ipairs(lines) do
654                 lines[i] = color_code .. line
655         end
656
657         return table.concat(lines, "\n") .. core.get_color_escape_sequence("#ffffff")
658 end
659
660
661 function core.strip_foreground_colors(str)
662         return (str:gsub(ESCAPE_CHAR .. "%(c@[^)]+%)", ""))
663 end
664
665 function core.strip_background_colors(str)
666         return (str:gsub(ESCAPE_CHAR .. "%(b@[^)]+%)", ""))
667 end
668
669 function core.strip_colors(str)
670         return (str:gsub(ESCAPE_CHAR .. "%([bc]@[^)]+%)", ""))
671 end
672
673 function core.translate(textdomain, str, ...)
674         local start_seq
675         if textdomain == "" then
676                 start_seq = ESCAPE_CHAR .. "T"
677         else
678                 start_seq = ESCAPE_CHAR .. "(T@" .. textdomain .. ")"
679         end
680         local arg = {n=select('#', ...), ...}
681         local end_seq = ESCAPE_CHAR .. "E"
682         local arg_index = 1
683         local translated = str:gsub("@(.)", function(matched)
684                 local c = string.byte(matched)
685                 if string.byte("1") <= c and c <= string.byte("9") then
686                         local a = c - string.byte("0")
687                         if a ~= arg_index then
688                                 error("Escape sequences in string given to core.translate " ..
689                                         "are not in the correct order: got @" .. matched ..
690                                         "but expected @" .. tostring(arg_index))
691                         end
692                         if a > arg.n then
693                                 error("Not enough arguments provided to core.translate")
694                         end
695                         arg_index = arg_index + 1
696                         return ESCAPE_CHAR .. "F" .. arg[a] .. ESCAPE_CHAR .. "E"
697                 elseif matched == "n" then
698                         return "\n"
699                 else
700                         return matched
701                 end
702         end)
703         if arg_index < arg.n + 1 then
704                 error("Too many arguments provided to core.translate")
705         end
706         return start_seq .. translated .. end_seq
707 end
708
709 function core.get_translator(textdomain)
710         return function(str, ...) return core.translate(textdomain or "", str, ...) end
711 end
712
713 --------------------------------------------------------------------------------
714 -- Returns the exact coordinate of a pointed surface
715 --------------------------------------------------------------------------------
716 function core.pointed_thing_to_face_pos(placer, pointed_thing)
717         -- Avoid crash in some situations when player is inside a node, causing
718         -- 'above' to equal 'under'.
719         if vector.equals(pointed_thing.above, pointed_thing.under) then
720                 return pointed_thing.under
721         end
722
723         local eye_height = placer:get_properties().eye_height
724         local eye_offset_first = placer:get_eye_offset()
725         local node_pos = pointed_thing.under
726         local camera_pos = placer:get_pos()
727         local pos_off = vector.multiply(
728                         vector.subtract(pointed_thing.above, node_pos), 0.5)
729         local look_dir = placer:get_look_dir()
730         local offset, nc
731         local oc = {}
732
733         for c, v in pairs(pos_off) do
734                 if nc or v == 0 then
735                         oc[#oc + 1] = c
736                 else
737                         offset = v
738                         nc = c
739                 end
740         end
741
742         local fine_pos = {[nc] = node_pos[nc] + offset}
743         camera_pos.y = camera_pos.y + eye_height + eye_offset_first.y / 10
744         local f = (node_pos[nc] + offset - camera_pos[nc]) / look_dir[nc]
745
746         for i = 1, #oc do
747                 fine_pos[oc[i]] = camera_pos[oc[i]] + look_dir[oc[i]] * f
748         end
749         return fine_pos
750 end
751
752 function core.string_to_privs(str, delim)
753         assert(type(str) == "string")
754         delim = delim or ','
755         local privs = {}
756         for _, priv in pairs(string.split(str, delim)) do
757                 privs[priv:trim()] = true
758         end
759         return privs
760 end
761
762 function core.privs_to_string(privs, delim)
763         assert(type(privs) == "table")
764         delim = delim or ','
765         local list = {}
766         for priv, bool in pairs(privs) do
767                 if bool then
768                         list[#list + 1] = priv
769                 end
770         end
771         return table.concat(list, delim)
772 end