]> git.lizzy.rs Git - dragonfireclient.git/blob - builtin/common/misc_helpers.lua
Allow random menu images for subgames
[dragonfireclient.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 table_insert = table.insert
6 local string_sub, string_find = string.sub, string.find
7
8 --------------------------------------------------------------------------------
9 function basic_dump(o)
10         local tp = type(o)
11         if tp == "number" then
12                 return tostring(o)
13         elseif tp == "string" then
14                 return string.format("%q", o)
15         elseif tp == "boolean" then
16                 return tostring(o)
17         elseif tp == "nil" then
18                 return "nil"
19         -- Uncomment for full function dumping support.
20         -- Not currently enabled because bytecode isn't very human-readable and
21         -- dump's output is intended for humans.
22         --elseif tp == "function" then
23         --      return string.format("loadstring(%q)", string.dump(o))
24         else
25                 return string.format("<%s>", tp)
26         end
27 end
28
29 local keywords = {
30         ["and"] = true,
31         ["break"] = true,
32         ["do"] = true,
33         ["else"] = true,
34         ["elseif"] = true,
35         ["end"] = true,
36         ["false"] = true,
37         ["for"] = true,
38         ["function"] = true,
39         ["goto"] = true,  -- Lua 5.2
40         ["if"] = true,
41         ["in"] = true,
42         ["local"] = true,
43         ["nil"] = true,
44         ["not"] = true,
45         ["or"] = true,
46         ["repeat"] = true,
47         ["return"] = true,
48         ["then"] = true,
49         ["true"] = true,
50         ["until"] = true,
51         ["while"] = true,
52 }
53 local function is_valid_identifier(str)
54         if not str:find("^[a-zA-Z_][a-zA-Z0-9_]*$") or keywords[str] then
55                 return false
56         end
57         return true
58 end
59
60 --------------------------------------------------------------------------------
61 -- Dumps values in a line-per-value format.
62 -- For example, {test = {"Testing..."}} becomes:
63 --   _["test"] = {}
64 --   _["test"][1] = "Testing..."
65 -- This handles tables as keys and circular references properly.
66 -- It also handles multiple references well, writing the table only once.
67 -- The dumped argument is internal-only.
68
69 function dump2(o, name, dumped)
70         name = name or "_"
71         -- "dumped" is used to keep track of serialized tables to handle
72         -- multiple references and circular tables properly.
73         -- It only contains tables as keys.  The value is the name that
74         -- the table has in the dump, eg:
75         -- {x = {"y"}} -> dumped[{"y"}] = '_["x"]'
76         dumped = dumped or {}
77         if type(o) ~= "table" then
78                 return string.format("%s = %s\n", name, basic_dump(o))
79         end
80         if dumped[o] then
81                 return string.format("%s = %s\n", name, dumped[o])
82         end
83         dumped[o] = name
84         -- This contains a list of strings to be concatenated later (because
85         -- Lua is slow at individual concatenation).
86         local t = {}
87         for k, v in pairs(o) do
88                 local keyStr
89                 if type(k) == "table" then
90                         if dumped[k] then
91                                 keyStr = dumped[k]
92                         else
93                                 -- Key tables don't have a name, so use one of
94                                 -- the form _G["table: 0xFFFFFFF"]
95                                 keyStr = string.format("_G[%q]", tostring(k))
96                                 -- Dump key table
97                                 table_insert(t, dump2(k, keyStr, dumped))
98                         end
99                 else
100                         keyStr = basic_dump(k)
101                 end
102                 local vname = string.format("%s[%s]", name, keyStr)
103                 table_insert(t, dump2(v, vname, dumped))
104         end
105         return string.format("%s = {}\n%s", name, table.concat(t))
106 end
107
108 --------------------------------------------------------------------------------
109 -- This dumps values in a one-statement format.
110 -- For example, {test = {"Testing..."}} becomes:
111 -- [[{
112 --      test = {
113 --              "Testing..."
114 --      }
115 -- }]]
116 -- This supports tables as keys, but not circular references.
117 -- It performs poorly with multiple references as it writes out the full
118 -- table each time.
119 -- The indent field specifies a indentation string, it defaults to a tab.
120 -- Use the empty string to disable indentation.
121 -- The dumped and level arguments are internal-only.
122
123 function dump(o, indent, nested, level)
124         if type(o) ~= "table" then
125                 return basic_dump(o)
126         end
127         -- Contains table -> true/nil of currently nested tables
128         nested = nested or {}
129         if nested[o] then
130                 return "<circular reference>"
131         end
132         nested[o] = true
133         indent = indent or "\t"
134         level = level or 1
135         local t = {}
136         local dumped_indexes = {}
137         for i, v in ipairs(o) do
138                 table_insert(t, dump(v, indent, nested, level + 1))
139                 dumped_indexes[i] = true
140         end
141         for k, v in pairs(o) do
142                 if not dumped_indexes[k] then
143                         if type(k) ~= "string" or not is_valid_identifier(k) then
144                                 k = "["..dump(k, indent, nested, level + 1).."]"
145                         end
146                         v = dump(v, indent, nested, level + 1)
147                         table_insert(t, k.." = "..v)
148                 end
149         end
150         nested[o] = nil
151         if indent ~= "" then
152                 local indent_str = "\n"..string.rep(indent, level)
153                 local end_indent_str = "\n"..string.rep(indent, level - 1)
154                 return string.format("{%s%s%s}",
155                                 indent_str,
156                                 table.concat(t, ","..indent_str),
157                                 end_indent_str)
158         end
159         return "{"..table.concat(t, ", ").."}"
160 end
161
162 --------------------------------------------------------------------------------
163 function string.split(str, delim, include_empty, max_splits, sep_is_pattern)
164         delim = delim or ","
165         max_splits = max_splits or -1
166         local items = {}
167         local pos, len, seplen = 1, #str, #delim
168         local plain = not sep_is_pattern
169         max_splits = max_splits + 1
170         repeat
171                 local np, npe = string_find(str, delim, pos, plain)
172                 np, npe = (np or (len+1)), (npe or (len+1))
173                 if (not np) or (max_splits == 1) then
174                         np = len + 1
175                         npe = np
176                 end
177                 local s = string_sub(str, pos, np - 1)
178                 if include_empty or (s ~= "") then
179                         max_splits = max_splits - 1
180                         table_insert(items, s)
181                 end
182                 pos = npe + 1
183         until (max_splits == 0) or (pos > (len + 1))
184         return items
185 end
186
187 --------------------------------------------------------------------------------
188 function table.indexof(list, val)
189         for i = 1, #list do
190                 if list[i] == val then
191                         return i
192                 end
193         end
194         return -1
195 end
196
197 assert(table.indexof({"foo", "bar"}, "foo") == 1)
198 assert(table.indexof({"foo", "bar"}, "baz") == -1)
199
200 --------------------------------------------------------------------------------
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
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.splittext(text,charlimit)
312         local retval = {}
313
314         local current_idx = 1
315
316         local start,stop = string_find(text, " ", current_idx)
317         local nl_start,nl_stop = string_find(text, "\n", current_idx)
318         local gotnewline = false
319         if nl_start ~= nil and (start == nil or nl_start < start) then
320                 start = nl_start
321                 stop = nl_stop
322                 gotnewline = true
323         end
324         local last_line = ""
325         while start ~= nil do
326                 if string.len(last_line) + (stop-start) > charlimit then
327                         table_insert(retval, last_line)
328                         last_line = ""
329                 end
330
331                 if last_line ~= "" then
332                         last_line = last_line .. " "
333                 end
334
335                 last_line = last_line .. string_sub(text, current_idx, stop - 1)
336
337                 if gotnewline then
338                         table_insert(retval, last_line)
339                         last_line = ""
340                         gotnewline = false
341                 end
342                 current_idx = stop+1
343
344                 start,stop = string_find(text, " ", current_idx)
345                 nl_start,nl_stop = string_find(text, "\n", current_idx)
346
347                 if nl_start ~= nil and (start == nil or nl_start < start) then
348                         start = nl_start
349                         stop = nl_stop
350                         gotnewline = true
351                 end
352         end
353
354         --add last part of text
355         if string.len(last_line) + (string.len(text) - current_idx) > charlimit then
356                         table_insert(retval, last_line)
357                         table_insert(retval, string_sub(text, current_idx))
358         else
359                 last_line = last_line .. " " .. string_sub(text, current_idx)
360                 table_insert(retval, last_line)
361         end
362
363         return retval
364 end
365
366 --------------------------------------------------------------------------------
367
368 if INIT == "game" then
369         local dirs1 = {9, 18, 7, 12}
370         local dirs2 = {20, 23, 22, 21}
371
372         function core.rotate_and_place(itemstack, placer, pointed_thing,
373                                 infinitestacks, orient_flags)
374                 orient_flags = orient_flags or {}
375
376                 local unode = core.get_node_or_nil(pointed_thing.under)
377                 if not unode then
378                         return
379                 end
380                 local undef = core.registered_nodes[unode.name]
381                 if undef and undef.on_rightclick then
382                         undef.on_rightclick(pointed_thing.under, unode, placer,
383                                         itemstack, pointed_thing)
384                         return
385                 end
386                 local pitch = placer:get_look_pitch()
387                 local fdir = core.dir_to_facedir(placer:get_look_dir())
388                 local wield_name = itemstack:get_name()
389
390                 local above = pointed_thing.above
391                 local under = pointed_thing.under
392                 local iswall = (above.y == under.y)
393                 local isceiling = not iswall and (above.y < under.y)
394                 local anode = core.get_node_or_nil(above)
395                 if not anode then
396                         return
397                 end
398                 local pos = pointed_thing.above
399                 local node = anode
400
401                 if undef and undef.buildable_to then
402                         pos = pointed_thing.under
403                         node = unode
404                         iswall = false
405                 end
406
407                 if core.is_protected(pos, placer:get_player_name()) then
408                         core.record_protection_violation(pos,
409                                         placer:get_player_name())
410                         return
411                 end
412
413                 local ndef = core.registered_nodes[node.name]
414                 if not ndef or not ndef.buildable_to then
415                         return
416                 end
417
418                 if orient_flags.force_floor then
419                         iswall = false
420                         isceiling = false
421                 elseif orient_flags.force_ceiling then
422                         iswall = false
423                         isceiling = true
424                 elseif orient_flags.force_wall then
425                         iswall = true
426                         isceiling = false
427                 elseif orient_flags.invert_wall then
428                         iswall = not iswall
429                 end
430
431                 if iswall then
432                         core.set_node(pos, {name = wield_name,
433                                         param2 = dirs1[fdir+1]})
434                 elseif isceiling then
435                         if orient_flags.force_facedir then
436                                 core.set_node(pos, {name = wield_name,
437                                                 param2 = 20})
438                         else
439                                 core.set_node(pos, {name = wield_name,
440                                                 param2 = dirs2[fdir+1]})
441                         end
442                 else -- place right side up
443                         if orient_flags.force_facedir then
444                                 core.set_node(pos, {name = wield_name,
445                                                 param2 = 0})
446                         else
447                                 core.set_node(pos, {name = wield_name,
448                                                 param2 = fdir})
449                         end
450                 end
451
452                 if not infinitestacks then
453                         itemstack:take_item()
454                         return itemstack
455                 end
456         end
457
458
459 --------------------------------------------------------------------------------
460 --Wrapper for rotate_and_place() to check for sneak and assume Creative mode
461 --implies infinite stacks when performing a 6d rotation.
462 --------------------------------------------------------------------------------
463
464
465         core.rotate_node = function(itemstack, placer, pointed_thing)
466                 core.rotate_and_place(itemstack, placer, pointed_thing,
467                                 core.setting_getbool("creative_mode"),
468                                 {invert_wall = placer:get_player_control().sneak})
469                 return itemstack
470         end
471 end
472
473 --------------------------------------------------------------------------------
474 function core.explode_table_event(evt)
475         if evt ~= nil then
476                 local parts = evt:split(":")
477                 if #parts == 3 then
478                         local t = parts[1]:trim()
479                         local r = tonumber(parts[2]:trim())
480                         local c = tonumber(parts[3]:trim())
481                         if type(r) == "number" and type(c) == "number"
482                                         and t ~= "INV" then
483                                 return {type=t, row=r, column=c}
484                         end
485                 end
486         end
487         return {type="INV", row=0, column=0}
488 end
489
490 --------------------------------------------------------------------------------
491 function core.explode_textlist_event(evt)
492         if evt ~= nil then
493                 local parts = evt:split(":")
494                 if #parts == 2 then
495                         local t = parts[1]:trim()
496                         local r = tonumber(parts[2]:trim())
497                         if type(r) == "number" and t ~= "INV" then
498                                 return {type=t, index=r}
499                         end
500                 end
501         end
502         return {type="INV", index=0}
503 end
504
505 --------------------------------------------------------------------------------
506 function core.explode_scrollbar_event(evt)
507         local retval = core.explode_textlist_event(evt)
508
509         retval.value = retval.index
510         retval.index = nil
511
512         return retval
513 end
514
515 --------------------------------------------------------------------------------
516 function core.pos_to_string(pos, decimal_places)
517         local x = pos.x
518         local y = pos.y
519         local z = pos.z
520         if decimal_places ~= nil then
521                 x = string.format("%." .. decimal_places .. "f", x)
522                 y = string.format("%." .. decimal_places .. "f", y)
523                 z = string.format("%." .. decimal_places .. "f", z)
524         end
525         return "(" .. x .. "," .. y .. "," .. z .. ")"
526 end
527
528 --------------------------------------------------------------------------------
529 function core.string_to_pos(value)
530         if value == nil then
531                 return nil
532         end
533
534         local p = {}
535         p.x, p.y, p.z = string.match(value, "^([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+)$")
536         if p.x and p.y and p.z then
537                 p.x = tonumber(p.x)
538                 p.y = tonumber(p.y)
539                 p.z = tonumber(p.z)
540                 return p
541         end
542         local p = {}
543         p.x, p.y, p.z = string.match(value, "^%( *([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+) *%)$")
544         if p.x and p.y and p.z then
545                 p.x = tonumber(p.x)
546                 p.y = tonumber(p.y)
547                 p.z = tonumber(p.z)
548                 return p
549         end
550         return nil
551 end
552
553 assert(core.string_to_pos("10.0, 5, -2").x == 10)
554 assert(core.string_to_pos("( 10.0, 5, -2)").z == -2)
555 assert(core.string_to_pos("asd, 5, -2)") == nil)
556
557 --------------------------------------------------------------------------------
558 function table.copy(t, seen)
559         local n = {}
560         seen = seen or {}
561         seen[t] = n
562         for k, v in pairs(t) do
563                 n[(type(k) == "table" and (seen[k] or table.copy(k, seen))) or k] =
564                         (type(v) == "table" and (seen[v] or table.copy(v, seen))) or v
565         end
566         return n
567 end
568 --------------------------------------------------------------------------------
569 -- mainmenu only functions
570 --------------------------------------------------------------------------------
571 if INIT == "mainmenu" then
572         function core.get_game(index)
573                 local games = game.get_games()
574
575                 if index > 0 and index <= #games then
576                         return games[index]
577                 end
578
579                 return nil
580         end
581
582         function fgettext_ne(text, ...)
583                 text = core.gettext(text)
584                 local arg = {n=select('#', ...), ...}
585                 if arg.n >= 1 then
586                         -- Insert positional parameters ($1, $2, ...)
587                         local result = ''
588                         local pos = 1
589                         while pos <= text:len() do
590                                 local newpos = text:find('[$]', pos)
591                                 if newpos == nil then
592                                         result = result .. text:sub(pos)
593                                         pos = text:len() + 1
594                                 else
595                                         local paramindex =
596                                                 tonumber(text:sub(newpos+1, newpos+1))
597                                         result = result .. text:sub(pos, newpos-1)
598                                                 .. tostring(arg[paramindex])
599                                         pos = newpos + 2
600                                 end
601                         end
602                         text = result
603                 end
604                 return text
605         end
606
607         function fgettext(text, ...)
608                 return core.formspec_escape(fgettext_ne(text, ...))
609         end
610 end
611