Set placer to nil instead of a non-functional one in item_OnPlace (#6449)
[oweals/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         if type(o) ~= "table" then
124                 return basic_dump(o)
125         end
126         -- Contains table -> true/nil of currently nested tables
127         nested = nested or {}
128         if nested[o] then
129                 return "<circular reference>"
130         end
131         nested[o] = true
132         indent = indent or "\t"
133         level = level or 1
134         local t = {}
135         local dumped_indexes = {}
136         for i, v in ipairs(o) do
137                 t[#t + 1] = dump(v, indent, nested, level + 1)
138                 dumped_indexes[i] = true
139         end
140         for k, v in pairs(o) do
141                 if not dumped_indexes[k] then
142                         if type(k) ~= "string" or not is_valid_identifier(k) then
143                                 k = "["..dump(k, indent, nested, level + 1).."]"
144                         end
145                         v = dump(v, indent, nested, level + 1)
146                         t[#t + 1] = k.." = "..v
147                 end
148         end
149         nested[o] = nil
150         if indent ~= "" then
151                 local indent_str = "\n"..string.rep(indent, level)
152                 local end_indent_str = "\n"..string.rep(indent, level - 1)
153                 return string.format("{%s%s%s}",
154                                 indent_str,
155                                 table.concat(t, ","..indent_str),
156                                 end_indent_str)
157         end
158         return "{"..table.concat(t, ", ").."}"
159 end
160
161 --------------------------------------------------------------------------------
162 function string.split(str, delim, include_empty, max_splits, sep_is_pattern)
163         delim = delim or ","
164         max_splits = max_splits or -1
165         local items = {}
166         local pos, len, seplen = 1, #str, #delim
167         local plain = not sep_is_pattern
168         max_splits = max_splits + 1
169         repeat
170                 local np, npe = string_find(str, delim, pos, plain)
171                 np, npe = (np or (len+1)), (npe or (len+1))
172                 if (not np) or (max_splits == 1) then
173                         np = len + 1
174                         npe = np
175                 end
176                 local s = string_sub(str, pos, np - 1)
177                 if include_empty or (s ~= "") then
178                         max_splits = max_splits - 1
179                         items[#items + 1] = s
180                 end
181                 pos = npe + 1
182         until (max_splits == 0) or (pos > (len + 1))
183         return items
184 end
185
186 --------------------------------------------------------------------------------
187 function table.indexof(list, val)
188         for i, v in ipairs(list) do
189                 if v == val then
190                         return i
191                 end
192         end
193         return -1
194 end
195
196 assert(table.indexof({"foo", "bar"}, "foo") == 1)
197 assert(table.indexof({"foo", "bar"}, "baz") == -1)
198
199 --------------------------------------------------------------------------------
200 if INIT ~= "client" then
201         function file_exists(filename)
202                 local f = io.open(filename, "r")
203                 if f == nil then
204                         return false
205                 else
206                         f:close()
207                         return true
208                 end
209         end
210 end
211 --------------------------------------------------------------------------------
212 function string:trim()
213         return (self:gsub("^%s*(.-)%s*$", "%1"))
214 end
215
216 assert(string.trim("\n \t\tfoo bar\t ") == "foo bar")
217
218 --------------------------------------------------------------------------------
219 function math.hypot(x, y)
220         local t
221         x = math.abs(x)
222         y = math.abs(y)
223         t = math.min(x, y)
224         x = math.max(x, y)
225         if x == 0 then return 0 end
226         t = t / x
227         return x * math.sqrt(1 + t * t)
228 end
229
230 --------------------------------------------------------------------------------
231 function math.sign(x, tolerance)
232         tolerance = tolerance or 0
233         if x > tolerance then
234                 return 1
235         elseif x < -tolerance then
236                 return -1
237         end
238         return 0
239 end
240
241 --------------------------------------------------------------------------------
242 function get_last_folder(text,count)
243         local parts = text:split(DIR_DELIM)
244
245         if count == nil then
246                 return parts[#parts]
247         end
248
249         local retval = ""
250         for i=1,count,1 do
251                 retval = retval .. parts[#parts - (count-i)] .. DIR_DELIM
252         end
253
254         return retval
255 end
256
257 --------------------------------------------------------------------------------
258 function cleanup_path(temppath)
259
260         local parts = temppath:split("-")
261         temppath = ""
262         for i=1,#parts,1 do
263                 if temppath ~= "" then
264                         temppath = temppath .. "_"
265                 end
266                 temppath = temppath .. parts[i]
267         end
268
269         parts = temppath:split(".")
270         temppath = ""
271         for i=1,#parts,1 do
272                 if temppath ~= "" then
273                         temppath = temppath .. "_"
274                 end
275                 temppath = temppath .. parts[i]
276         end
277
278         parts = temppath:split("'")
279         temppath = ""
280         for i=1,#parts,1 do
281                 if temppath ~= "" then
282                         temppath = temppath .. ""
283                 end
284                 temppath = temppath .. parts[i]
285         end
286
287         parts = temppath:split(" ")
288         temppath = ""
289         for i=1,#parts,1 do
290                 if temppath ~= "" then
291                         temppath = temppath
292                 end
293                 temppath = temppath .. parts[i]
294         end
295
296         return temppath
297 end
298
299 function core.formspec_escape(text)
300         if text ~= nil then
301                 text = string.gsub(text,"\\","\\\\")
302                 text = string.gsub(text,"%]","\\]")
303                 text = string.gsub(text,"%[","\\[")
304                 text = string.gsub(text,";","\\;")
305                 text = string.gsub(text,",","\\,")
306         end
307         return text
308 end
309
310
311 function core.wrap_text(text, max_length, as_table)
312         local result = {}
313         local line = {}
314         if #text <= max_length then
315                 return as_table and {text} or text
316         end
317
318         for word in text:gmatch('%S+') do
319                 local cur_length = #table.concat(line, ' ')
320                 if cur_length > 0 and cur_length + #word + 1 >= max_length then
321                         -- word wouldn't fit on current line, move to next line
322                         table.insert(result, table.concat(line, ' '))
323                         line = {}
324                 end
325                 table.insert(line, word)
326         end
327
328         table.insert(result, table.concat(line, ' '))
329         return as_table and result or table.concat(result, '\n')
330 end
331
332 --------------------------------------------------------------------------------
333
334 if INIT == "game" then
335         local dirs1 = {9, 18, 7, 12}
336         local dirs2 = {20, 23, 22, 21}
337
338         function core.rotate_and_place(itemstack, placer, pointed_thing,
339                                 infinitestacks, orient_flags)
340                 orient_flags = orient_flags or {}
341
342                 local unode = core.get_node_or_nil(pointed_thing.under)
343                 if not unode then
344                         return
345                 end
346                 local undef = core.registered_nodes[unode.name]
347                 if undef and undef.on_rightclick then
348                         undef.on_rightclick(pointed_thing.under, unode, placer,
349                                         itemstack, pointed_thing)
350                         return
351                 end
352                 local fdir = placer and core.dir_to_facedir(placer:get_look_dir()) or 0
353                 local wield_name = itemstack:get_name()
354
355                 local above = pointed_thing.above
356                 local under = pointed_thing.under
357                 local iswall = (above.y == under.y)
358                 local isceiling = not iswall and (above.y < under.y)
359                 local anode = core.get_node_or_nil(above)
360                 if not anode then
361                         return
362                 end
363                 local pos = pointed_thing.above
364                 local node = anode
365
366                 if undef and undef.buildable_to then
367                         pos = pointed_thing.under
368                         node = unode
369                         iswall = false
370                 end
371
372                 local name = placer and placer:get_player_name() or ""
373                 if core.is_protected(pos, name) then
374                         core.record_protection_violation(pos, name)
375                         return
376                 end
377
378                 local ndef = core.registered_nodes[node.name]
379                 if not ndef or not ndef.buildable_to then
380                         return
381                 end
382
383                 if orient_flags.force_floor then
384                         iswall = false
385                         isceiling = false
386                 elseif orient_flags.force_ceiling then
387                         iswall = false
388                         isceiling = true
389                 elseif orient_flags.force_wall then
390                         iswall = true
391                         isceiling = false
392                 elseif orient_flags.invert_wall then
393                         iswall = not iswall
394                 end
395
396                 if iswall then
397                         core.set_node(pos, {name = wield_name,
398                                         param2 = dirs1[fdir + 1]})
399                 elseif isceiling then
400                         if orient_flags.force_facedir then
401                                 core.set_node(pos, {name = wield_name,
402                                                 param2 = 20})
403                         else
404                                 core.set_node(pos, {name = wield_name,
405                                                 param2 = dirs2[fdir + 1]})
406                         end
407                 else -- place right side up
408                         if orient_flags.force_facedir then
409                                 core.set_node(pos, {name = wield_name,
410                                                 param2 = 0})
411                         else
412                                 core.set_node(pos, {name = wield_name,
413                                                 param2 = fdir})
414                         end
415                 end
416
417                 if not infinitestacks then
418                         itemstack:take_item()
419                         return itemstack
420                 end
421         end
422
423
424 --------------------------------------------------------------------------------
425 --Wrapper for rotate_and_place() to check for sneak and assume Creative mode
426 --implies infinite stacks when performing a 6d rotation.
427 --------------------------------------------------------------------------------
428         local creative_mode_cache = core.settings:get_bool("creative_mode")
429         local function is_creative(name)
430                 return creative_mode_cache or
431                                 core.check_player_privs(name, {creative = true})
432         end
433
434         core.rotate_node = function(itemstack, placer, pointed_thing)
435                 local name = placer and placer:get_player_name() or ""
436                 local invert_wall = placer and placer:get_player_control().sneak or false
437                 core.rotate_and_place(itemstack, placer, pointed_thing,
438                                 is_creative(name),
439                                 {invert_wall = invert_wall})
440                 return itemstack
441         end
442 end
443
444 --------------------------------------------------------------------------------
445 function core.explode_table_event(evt)
446         if evt ~= nil then
447                 local parts = evt:split(":")
448                 if #parts == 3 then
449                         local t = parts[1]:trim()
450                         local r = tonumber(parts[2]:trim())
451                         local c = tonumber(parts[3]:trim())
452                         if type(r) == "number" and type(c) == "number"
453                                         and t ~= "INV" then
454                                 return {type=t, row=r, column=c}
455                         end
456                 end
457         end
458         return {type="INV", row=0, column=0}
459 end
460
461 --------------------------------------------------------------------------------
462 function core.explode_textlist_event(evt)
463         if evt ~= nil then
464                 local parts = evt:split(":")
465                 if #parts == 2 then
466                         local t = parts[1]:trim()
467                         local r = tonumber(parts[2]:trim())
468                         if type(r) == "number" and t ~= "INV" then
469                                 return {type=t, index=r}
470                         end
471                 end
472         end
473         return {type="INV", index=0}
474 end
475
476 --------------------------------------------------------------------------------
477 function core.explode_scrollbar_event(evt)
478         local retval = core.explode_textlist_event(evt)
479
480         retval.value = retval.index
481         retval.index = nil
482
483         return retval
484 end
485
486 --------------------------------------------------------------------------------
487 function core.rgba(r, g, b, a)
488         return a and string.format("#%02X%02X%02X%02X", r, g, b, a) or
489                         string.format("#%02X%02X%02X", r, g, b)
490 end
491
492 --------------------------------------------------------------------------------
493 function core.pos_to_string(pos, decimal_places)
494         local x = pos.x
495         local y = pos.y
496         local z = pos.z
497         if decimal_places ~= nil then
498                 x = string.format("%." .. decimal_places .. "f", x)
499                 y = string.format("%." .. decimal_places .. "f", y)
500                 z = string.format("%." .. decimal_places .. "f", z)
501         end
502         return "(" .. x .. "," .. y .. "," .. z .. ")"
503 end
504
505 --------------------------------------------------------------------------------
506 function core.string_to_pos(value)
507         if value == nil then
508                 return nil
509         end
510
511         local p = {}
512         p.x, p.y, p.z = string.match(value, "^([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+)$")
513         if p.x and p.y and p.z then
514                 p.x = tonumber(p.x)
515                 p.y = tonumber(p.y)
516                 p.z = tonumber(p.z)
517                 return p
518         end
519         local p = {}
520         p.x, p.y, p.z = string.match(value, "^%( *([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+) *%)$")
521         if p.x and p.y and p.z then
522                 p.x = tonumber(p.x)
523                 p.y = tonumber(p.y)
524                 p.z = tonumber(p.z)
525                 return p
526         end
527         return nil
528 end
529
530 assert(core.string_to_pos("10.0, 5, -2").x == 10)
531 assert(core.string_to_pos("( 10.0, 5, -2)").z == -2)
532 assert(core.string_to_pos("asd, 5, -2)") == nil)
533
534 --------------------------------------------------------------------------------
535 function core.string_to_area(value)
536         local p1, p2 = unpack(value:split(") ("))
537         if p1 == nil or p2 == nil then
538                 return nil
539         end
540
541         p1 = core.string_to_pos(p1 .. ")")
542         p2 = core.string_to_pos("(" .. p2)
543         if p1 == nil or p2 == nil then
544                 return nil
545         end
546
547         return p1, p2
548 end
549
550 local function test_string_to_area()
551         local p1, p2 = core.string_to_area("(10.0, 5, -2) (  30.2,   4, -12.53)")
552         assert(p1.x == 10.0 and p1.y == 5 and p1.z == -2)
553         assert(p2.x == 30.2 and p2.y == 4 and p2.z == -12.53)
554
555         p1, p2 = core.string_to_area("(10.0, 5, -2  30.2,   4, -12.53")
556         assert(p1 == nil and p2 == nil)
557
558         p1, p2 = core.string_to_area("(10.0, 5,) -2  fgdf2,   4, -12.53")
559         assert(p1 == nil and p2 == nil)
560 end
561
562 test_string_to_area()
563
564 --------------------------------------------------------------------------------
565 function table.copy(t, seen)
566         local n = {}
567         seen = seen or {}
568         seen[t] = n
569         for k, v in pairs(t) do
570                 n[(type(k) == "table" and (seen[k] or table.copy(k, seen))) or k] =
571                         (type(v) == "table" and (seen[v] or table.copy(v, seen))) or v
572         end
573         return n
574 end
575 --------------------------------------------------------------------------------
576 -- mainmenu only functions
577 --------------------------------------------------------------------------------
578 if INIT == "mainmenu" then
579         function core.get_game(index)
580                 local games = game.get_games()
581
582                 if index > 0 and index <= #games then
583                         return games[index]
584                 end
585
586                 return nil
587         end
588 end
589
590 if INIT == "client" or INIT == "mainmenu" then
591         function fgettext_ne(text, ...)
592                 text = core.gettext(text)
593                 local arg = {n=select('#', ...), ...}
594                 if arg.n >= 1 then
595                         -- Insert positional parameters ($1, $2, ...)
596                         local result = ''
597                         local pos = 1
598                         while pos <= text:len() do
599                                 local newpos = text:find('[$]', pos)
600                                 if newpos == nil then
601                                         result = result .. text:sub(pos)
602                                         pos = text:len() + 1
603                                 else
604                                         local paramindex =
605                                                 tonumber(text:sub(newpos+1, newpos+1))
606                                         result = result .. text:sub(pos, newpos-1)
607                                                 .. tostring(arg[paramindex])
608                                         pos = newpos + 2
609                                 end
610                         end
611                         text = result
612                 end
613                 return text
614         end
615
616         function fgettext(text, ...)
617                 return core.formspec_escape(fgettext_ne(text, ...))
618         end
619 end
620
621 local ESCAPE_CHAR = string.char(0x1b)
622
623 function core.get_color_escape_sequence(color)
624         return ESCAPE_CHAR .. "(c@" .. color .. ")"
625 end
626
627 function core.get_background_escape_sequence(color)
628         return ESCAPE_CHAR .. "(b@" .. color .. ")"
629 end
630
631 function core.colorize(color, message)
632         local lines = tostring(message):split("\n", true)
633         local color_code = core.get_color_escape_sequence(color)
634
635         for i, line in ipairs(lines) do
636                 lines[i] = color_code .. line
637         end
638
639         return table.concat(lines, "\n") .. core.get_color_escape_sequence("#ffffff")
640 end
641
642
643 function core.strip_foreground_colors(str)
644         return (str:gsub(ESCAPE_CHAR .. "%(c@[^)]+%)", ""))
645 end
646
647 function core.strip_background_colors(str)
648         return (str:gsub(ESCAPE_CHAR .. "%(b@[^)]+%)", ""))
649 end
650
651 function core.strip_colors(str)
652         return (str:gsub(ESCAPE_CHAR .. "%([bc]@[^)]+%)", ""))
653 end
654
655 function core.translate(textdomain, str, ...)
656         local start_seq
657         if textdomain == "" then
658                 start_seq = ESCAPE_CHAR .. "T"
659         else
660                 start_seq = ESCAPE_CHAR .. "(T@" .. textdomain .. ")"
661         end
662         local arg = {n=select('#', ...), ...}
663         local end_seq = ESCAPE_CHAR .. "E"
664         local arg_index = 1
665         local translated = str:gsub("@(.)", function(matched)
666                 local c = string.byte(matched)
667                 if string.byte("1") <= c and c <= string.byte("9") then
668                         local a = c - string.byte("0")
669                         if a ~= arg_index then
670                                 error("Escape sequences in string given to core.translate " ..
671                                         "are not in the correct order: got @" .. matched ..
672                                         "but expected @" .. tostring(arg_index))
673                         end
674                         if a > arg.n then
675                                 error("Not enough arguments provided to core.translate")
676                         end
677                         arg_index = arg_index + 1
678                         return ESCAPE_CHAR .. "F" .. arg[a] .. ESCAPE_CHAR .. "E"
679                 elseif matched == "n" then
680                         return "\n"
681                 else
682                         return matched
683                 end
684         end)
685         if arg_index < arg.n + 1 then
686                 error("Too many arguments provided to core.translate")
687         end
688         return start_seq .. translated .. end_seq
689 end
690
691 function core.get_translator(textdomain)
692         return function(str, ...) return core.translate(textdomain or "", str, ...) end
693 end
694
695 --------------------------------------------------------------------------------
696 -- Returns the exact coordinate of a pointed surface
697 --------------------------------------------------------------------------------
698 function core.pointed_thing_to_face_pos(placer, pointed_thing)
699         local eye_offset_first = placer:get_eye_offset()
700         local node_pos = pointed_thing.under
701         local camera_pos = placer:get_pos()
702         local pos_off = vector.multiply(
703                         vector.subtract(pointed_thing.above, node_pos), 0.5)
704         local look_dir = placer:get_look_dir()
705         local offset, nc
706         local oc = {}
707
708         for c, v in pairs(pos_off) do
709                 if nc or v == 0 then
710                         oc[#oc + 1] = c
711                 else
712                         offset = v
713                         nc = c
714                 end
715         end
716
717         local fine_pos = {[nc] = node_pos[nc] + offset}
718         camera_pos.y = camera_pos.y + 1.625 + eye_offset_first.y / 10
719         local f = (node_pos[nc] + offset - camera_pos[nc]) / look_dir[nc]
720
721         for i = 1, #oc do
722                 fine_pos[oc[i]] = camera_pos[oc[i]] + look_dir[oc[i]] * f
723         end
724         return fine_pos
725 end
726
727 function core.string_to_privs(str, delim)
728         assert(type(str) == "string")
729         delim = delim or ','
730         local privs = {}
731         for _, priv in pairs(string.split(str, delim)) do
732                 privs[priv:trim()] = true
733         end
734         return privs
735 end
736
737 function core.privs_to_string(privs, delim)
738         assert(type(privs) == "table")
739         delim = delim or ','
740         local list = {}
741         for priv, bool in pairs(privs) do
742                 if bool then
743                         list[#list + 1] = priv
744                 end
745         end
746         return table.concat(list, delim)
747 end
748
749 assert(core.string_to_privs("a,b").b == true)
750 assert(core.privs_to_string({a=true,b=true}) == "a,b")