]> git.lizzy.rs Git - dragonfireclient.git/blob - builtin/common/misc_helpers.lua
Fix wrong replace from previous commit
[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 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                         table_insert(items, 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 file_exists(filename)
188         local f = io.open(filename, "r")
189         if f==nil then
190                 return false
191         else
192                 f:close()
193                 return true
194         end
195 end
196
197 --------------------------------------------------------------------------------
198 function string:trim()
199         return (self:gsub("^%s*(.-)%s*$", "%1"))
200 end
201
202 assert(string.trim("\n \t\tfoo bar\t ") == "foo bar")
203
204 --------------------------------------------------------------------------------
205 function math.hypot(x, y)
206         local t
207         x = math.abs(x)
208         y = math.abs(y)
209         t = math.min(x, y)
210         x = math.max(x, y)
211         if x == 0 then return 0 end
212         t = t / x
213         return x * math.sqrt(1 + t * t)
214 end
215
216 --------------------------------------------------------------------------------
217 function math.sign(x, tolerance)
218         tolerance = tolerance or 0
219         if x > tolerance then
220                 return 1
221         elseif x < -tolerance then
222                 return -1
223         end
224         return 0
225 end
226
227 --------------------------------------------------------------------------------
228 function get_last_folder(text,count)
229         local parts = text:split(DIR_DELIM)
230
231         if count == nil then
232                 return parts[#parts]
233         end
234
235         local retval = ""
236         for i=1,count,1 do
237                 retval = retval .. parts[#parts - (count-i)] .. DIR_DELIM
238         end
239
240         return retval
241 end
242
243 --------------------------------------------------------------------------------
244 function cleanup_path(temppath)
245
246         local parts = temppath:split("-")
247         temppath = ""
248         for i=1,#parts,1 do
249                 if temppath ~= "" then
250                         temppath = temppath .. "_"
251                 end
252                 temppath = temppath .. parts[i]
253         end
254
255         parts = temppath:split(".")
256         temppath = ""
257         for i=1,#parts,1 do
258                 if temppath ~= "" then
259                         temppath = temppath .. "_"
260                 end
261                 temppath = temppath .. parts[i]
262         end
263
264         parts = temppath:split("'")
265         temppath = ""
266         for i=1,#parts,1 do
267                 if temppath ~= "" then
268                         temppath = temppath .. ""
269                 end
270                 temppath = temppath .. parts[i]
271         end
272
273         parts = temppath:split(" ")
274         temppath = ""
275         for i=1,#parts,1 do
276                 if temppath ~= "" then
277                         temppath = temppath
278                 end
279                 temppath = temppath .. parts[i]
280         end
281
282         return temppath
283 end
284
285 function core.formspec_escape(text)
286         if text ~= nil then
287                 text = string.gsub(text,"\\","\\\\")
288                 text = string.gsub(text,"%]","\\]")
289                 text = string.gsub(text,"%[","\\[")
290                 text = string.gsub(text,";","\\;")
291                 text = string.gsub(text,",","\\,")
292         end
293         return text
294 end
295
296
297 function core.splittext(text,charlimit)
298         local retval = {}
299
300         local current_idx = 1
301
302         local start,stop = string_find(text, " ", current_idx)
303         local nl_start,nl_stop = string_find(text, "\n", current_idx)
304         local gotnewline = false
305         if nl_start ~= nil and (start == nil or nl_start < start) then
306                 start = nl_start
307                 stop = nl_stop
308                 gotnewline = true
309         end
310         local last_line = ""
311         while start ~= nil do
312                 if string.len(last_line) + (stop-start) > charlimit then
313                         table_insert(retval, last_line)
314                         last_line = ""
315                 end
316
317                 if last_line ~= "" then
318                         last_line = last_line .. " "
319                 end
320
321                 last_line = last_line .. string_sub(text, current_idx, stop - 1)
322
323                 if gotnewline then
324                         table_insert(retval, last_line)
325                         last_line = ""
326                         gotnewline = false
327                 end
328                 current_idx = stop+1
329
330                 start,stop = string_find(text, " ", current_idx)
331                 nl_start,nl_stop = string_find(text, "\n", current_idx)
332
333                 if nl_start ~= nil and (start == nil or nl_start < start) then
334                         start = nl_start
335                         stop = nl_stop
336                         gotnewline = true
337                 end
338         end
339
340         --add last part of text
341         if string.len(last_line) + (string.len(text) - current_idx) > charlimit then
342                         table_insert(retval, last_line)
343                         table_insert(retval, string_sub(text, current_idx))
344         else
345                 last_line = last_line .. " " .. string_sub(text, current_idx)
346                 table_insert(retval, last_line)
347         end
348
349         return retval
350 end
351
352 --------------------------------------------------------------------------------
353
354 if INIT == "game" then
355         local dirs1 = {9, 18, 7, 12}
356         local dirs2 = {20, 23, 22, 21}
357
358         function core.rotate_and_place(itemstack, placer, pointed_thing,
359                                 infinitestacks, orient_flags)
360                 orient_flags = orient_flags or {}
361
362                 local unode = core.get_node_or_nil(pointed_thing.under)
363                 if not unode then
364                         return
365                 end
366                 local undef = core.registered_nodes[unode.name]
367                 if undef and undef.on_rightclick then
368                         undef.on_rightclick(pointed_thing.under, unode, placer,
369                                         itemstack, pointed_thing)
370                         return
371                 end
372                 local pitch = placer:get_look_pitch()
373                 local fdir = core.dir_to_facedir(placer:get_look_dir())
374                 local wield_name = itemstack:get_name()
375
376                 local above = pointed_thing.above
377                 local under = pointed_thing.under
378                 local iswall = (above.y == under.y)
379                 local isceiling = not iswall and (above.y < under.y)
380                 local anode = core.get_node_or_nil(above)
381                 if not anode then
382                         return
383                 end
384                 local pos = pointed_thing.above
385                 local node = anode
386
387                 if undef and undef.buildable_to then
388                         pos = pointed_thing.under
389                         node = unode
390                         iswall = false
391                 end
392
393                 if core.is_protected(pos, placer:get_player_name()) then
394                         core.record_protection_violation(pos,
395                                         placer:get_player_name())
396                         return
397                 end
398
399                 local ndef = core.registered_nodes[node.name]
400                 if not ndef or not ndef.buildable_to then
401                         return
402                 end
403
404                 if orient_flags.force_floor then
405                         iswall = false
406                         isceiling = false
407                 elseif orient_flags.force_ceiling then
408                         iswall = false
409                         isceiling = true
410                 elseif orient_flags.force_wall then
411                         iswall = true
412                         isceiling = false
413                 elseif orient_flags.invert_wall then
414                         iswall = not iswall
415                 end
416
417                 if iswall then
418                         core.set_node(pos, {name = wield_name,
419                                         param2 = dirs1[fdir+1]})
420                 elseif isceiling then
421                         if orient_flags.force_facedir then
422                                 core.set_node(pos, {name = wield_name,
423                                                 param2 = 20})
424                         else
425                                 core.set_node(pos, {name = wield_name,
426                                                 param2 = dirs2[fdir+1]})
427                         end
428                 else -- place right side up
429                         if orient_flags.force_facedir then
430                                 core.set_node(pos, {name = wield_name,
431                                                 param2 = 0})
432                         else
433                                 core.set_node(pos, {name = wield_name,
434                                                 param2 = fdir})
435                         end
436                 end
437
438                 if not infinitestacks then
439                         itemstack:take_item()
440                         return itemstack
441                 end
442         end
443
444
445 --------------------------------------------------------------------------------
446 --Wrapper for rotate_and_place() to check for sneak and assume Creative mode
447 --implies infinite stacks when performing a 6d rotation.
448 --------------------------------------------------------------------------------
449
450
451         core.rotate_node = function(itemstack, placer, pointed_thing)
452                 core.rotate_and_place(itemstack, placer, pointed_thing,
453                                 core.setting_getbool("creative_mode"),
454                                 {invert_wall = placer:get_player_control().sneak})
455                 return itemstack
456         end
457 end
458
459 --------------------------------------------------------------------------------
460 function core.explode_table_event(evt)
461         if evt ~= nil then
462                 local parts = evt:split(":")
463                 if #parts == 3 then
464                         local t = parts[1]:trim()
465                         local r = tonumber(parts[2]:trim())
466                         local c = tonumber(parts[3]:trim())
467                         if type(r) == "number" and type(c) == "number"
468                                         and t ~= "INV" then
469                                 return {type=t, row=r, column=c}
470                         end
471                 end
472         end
473         return {type="INV", row=0, column=0}
474 end
475
476 --------------------------------------------------------------------------------
477 function core.explode_textlist_event(evt)
478         if evt ~= nil then
479                 local parts = evt:split(":")
480                 if #parts == 2 then
481                         local t = parts[1]:trim()
482                         local r = tonumber(parts[2]:trim())
483                         if type(r) == "number" and t ~= "INV" then
484                                 return {type=t, index=r}
485                         end
486                 end
487         end
488         return {type="INV", index=0}
489 end
490
491 --------------------------------------------------------------------------------
492 function core.explode_scrollbar_event(evt)
493         local retval = core.explode_textlist_event(evt)
494
495         retval.value = retval.index
496         retval.index = nil
497
498         return retval
499 end
500
501 --------------------------------------------------------------------------------
502 function core.pos_to_string(pos, decimal_places)
503         local x = pos.x
504         local y = pos.y
505         local z = pos.z
506         if decimal_places ~= nil then
507                 x = string.format("%." .. decimal_places .. "f", x)
508                 y = string.format("%." .. decimal_places .. "f", y)
509                 z = string.format("%." .. decimal_places .. "f", z)
510         end
511         return "(" .. x .. "," .. y .. "," .. z .. ")"
512 end
513
514 --------------------------------------------------------------------------------
515 function core.string_to_pos(value)
516         if value == nil then
517                 return nil
518         end
519
520         local p = {}
521         p.x, p.y, p.z = string.match(value, "^([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+)$")
522         if p.x and p.y and p.z then
523                 p.x = tonumber(p.x)
524                 p.y = tonumber(p.y)
525                 p.z = tonumber(p.z)
526                 return p
527         end
528         local p = {}
529         p.x, p.y, p.z = string.match(value, "^%( *([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+) *%)$")
530         if p.x and p.y and p.z then
531                 p.x = tonumber(p.x)
532                 p.y = tonumber(p.y)
533                 p.z = tonumber(p.z)
534                 return p
535         end
536         return nil
537 end
538
539 assert(core.string_to_pos("10.0, 5, -2").x == 10)
540 assert(core.string_to_pos("( 10.0, 5, -2)").z == -2)
541 assert(core.string_to_pos("asd, 5, -2)") == nil)
542
543 --------------------------------------------------------------------------------
544 function table.copy(t, seen)
545         local n = {}
546         seen = seen or {}
547         seen[t] = n
548         for k, v in pairs(t) do
549                 n[(type(k) == "table" and (seen[k] or table.copy(k, seen))) or k] =
550                         (type(v) == "table" and (seen[v] or table.copy(v, seen))) or v
551         end
552         return n
553 end
554 --------------------------------------------------------------------------------
555 -- mainmenu only functions
556 --------------------------------------------------------------------------------
557 if INIT == "mainmenu" then
558         function core.get_game(index)
559                 local games = game.get_games()
560
561                 if index > 0 and index <= #games then
562                         return games[index]
563                 end
564
565                 return nil
566         end
567
568         function fgettext_ne(text, ...)
569                 text = core.gettext(text)
570                 local arg = {n=select('#', ...), ...}
571                 if arg.n >= 1 then
572                         -- Insert positional parameters ($1, $2, ...)
573                         local result = ''
574                         local pos = 1
575                         while pos <= text:len() do
576                                 local newpos = text:find('[$]', pos)
577                                 if newpos == nil then
578                                         result = result .. text:sub(pos)
579                                         pos = text:len() + 1
580                                 else
581                                         local paramindex =
582                                                 tonumber(text:sub(newpos+1, newpos+1))
583                                         result = result .. text:sub(pos, newpos-1)
584                                                 .. tostring(arg[paramindex])
585                                         pos = newpos + 2
586                                 end
587                         end
588                         text = result
589                 end
590                 return text
591         end
592
593         function fgettext(text, ...)
594                 return core.formspec_escape(fgettext_ne(text, ...))
595         end
596 end
597