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