Adding particle blend, glow and animation (#4705)
[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 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 -- Video enums and pack function
242
243 -- E_BLEND_FACTOR
244 minetest.ebf = {                             
245         zero                    = 0, -- src & dest (0, 0, 0, 0)
246         one                     = 1, -- src & dest (1, 1, 1, 1)
247         dst_color               = 2, -- src (destR, destG, destB, destA)
248         one_minus_dst_color     = 3, -- src (1-destR, 1-destG, 1-destB, 1-destA)
249         src_color               = 4, -- dest (srcR, srcG, srcB, srcA)
250         one_minus_src_color     = 5, -- dest (1-srcR, 1-srcG, 1-srcB, 1-srcA)
251         src_alpha               = 6, -- src & dest (srcA, srcA, srcA, srcA)
252         one_minus_src_alpha     = 7, -- src & dest (1-srcA, 1-srcA, 1-srcA, 1-srcA)
253         dst_alpha               = 8, -- src & dest (destA, destA, destA, destA)
254         one_minus_dst_alpha     = 9, -- src & dest (1-destA, 1-destA, 1-destA, 1-destA)
255         src_alpha_saturate      = 10,-- src (min(srcA, 1-destA), idem, ...) 
256 }
257
258 -- E_MODULATE_FUNC
259 minetest.emfn = {
260         modulate_1x    = 1,
261         modulate_2x    = 2,
262         modulate_4x    = 4,
263 }
264
265 -- E_ALPHA_SOURCE
266 minetest.eas = {
267         none     = 0,
268         vertex_color = 1,
269         texture  = 2,
270 }
271
272 -- BlendFunc = source * sourceFactor + dest * destFactor
273 function minetest.pack_texture_blend_func(srcFact, dstFact, modulate, alphaSource) 
274         return alphaSource * 4096 + modulate * 256 + srcFact * 16 + dstFact
275 end
276
277 --------------------------------------------------------------------------------
278 function get_last_folder(text,count)
279         local parts = text:split(DIR_DELIM)
280
281         if count == nil then
282                 return parts[#parts]
283         end
284
285         local retval = ""
286         for i=1,count,1 do
287                 retval = retval .. parts[#parts - (count-i)] .. DIR_DELIM
288         end
289
290         return retval
291 end
292
293 --------------------------------------------------------------------------------
294 function cleanup_path(temppath)
295
296         local parts = temppath:split("-")
297         temppath = ""
298         for i=1,#parts,1 do
299                 if temppath ~= "" then
300                         temppath = temppath .. "_"
301                 end
302                 temppath = temppath .. parts[i]
303         end
304
305         parts = temppath:split(".")
306         temppath = ""
307         for i=1,#parts,1 do
308                 if temppath ~= "" then
309                         temppath = temppath .. "_"
310                 end
311                 temppath = temppath .. parts[i]
312         end
313
314         parts = temppath:split("'")
315         temppath = ""
316         for i=1,#parts,1 do
317                 if temppath ~= "" then
318                         temppath = temppath .. ""
319                 end
320                 temppath = temppath .. parts[i]
321         end
322
323         parts = temppath:split(" ")
324         temppath = ""
325         for i=1,#parts,1 do
326                 if temppath ~= "" then
327                         temppath = temppath
328                 end
329                 temppath = temppath .. parts[i]
330         end
331
332         return temppath
333 end
334
335 function core.formspec_escape(text)
336         if text ~= nil then
337                 text = string.gsub(text,"\\","\\\\")
338                 text = string.gsub(text,"%]","\\]")
339                 text = string.gsub(text,"%[","\\[")
340                 text = string.gsub(text,";","\\;")
341                 text = string.gsub(text,",","\\,")
342         end
343         return text
344 end
345
346
347 function core.splittext(text,charlimit)
348         local retval = {}
349
350         local current_idx = 1
351
352         local start,stop = string_find(text, " ", current_idx)
353         local nl_start,nl_stop = string_find(text, "\n", current_idx)
354         local gotnewline = false
355         if nl_start ~= nil and (start == nil or nl_start < start) then
356                 start = nl_start
357                 stop = nl_stop
358                 gotnewline = true
359         end
360         local last_line = ""
361         while start ~= nil do
362                 if string.len(last_line) + (stop-start) > charlimit then
363                         retval[#retval + 1] = last_line
364                         last_line = ""
365                 end
366
367                 if last_line ~= "" then
368                         last_line = last_line .. " "
369                 end
370
371                 last_line = last_line .. string_sub(text, current_idx, stop - 1)
372
373                 if gotnewline then
374                         retval[#retval + 1] = last_line
375                         last_line = ""
376                         gotnewline = false
377                 end
378                 current_idx = stop+1
379
380                 start,stop = string_find(text, " ", current_idx)
381                 nl_start,nl_stop = string_find(text, "\n", current_idx)
382
383                 if nl_start ~= nil and (start == nil or nl_start < start) then
384                         start = nl_start
385                         stop = nl_stop
386                         gotnewline = true
387                 end
388         end
389
390         --add last part of text
391         if string.len(last_line) + (string.len(text) - current_idx) > charlimit then
392                         retval[#retval + 1] = last_line
393                         retval[#retval + 1] = string_sub(text, current_idx)
394         else
395                 last_line = last_line .. " " .. string_sub(text, current_idx)
396                 retval[#retval + 1] = last_line
397         end
398
399         return retval
400 end
401
402 --------------------------------------------------------------------------------
403
404 if INIT == "game" then
405         local dirs1 = {9, 18, 7, 12}
406         local dirs2 = {20, 23, 22, 21}
407
408         function core.rotate_and_place(itemstack, placer, pointed_thing,
409                                 infinitestacks, orient_flags)
410                 orient_flags = orient_flags or {}
411
412                 local unode = core.get_node_or_nil(pointed_thing.under)
413                 if not unode then
414                         return
415                 end
416                 local undef = core.registered_nodes[unode.name]
417                 if undef and undef.on_rightclick then
418                         undef.on_rightclick(pointed_thing.under, unode, placer,
419                                         itemstack, pointed_thing)
420                         return
421                 end
422                 local fdir = core.dir_to_facedir(placer:get_look_dir())
423                 local wield_name = itemstack:get_name()
424
425                 local above = pointed_thing.above
426                 local under = pointed_thing.under
427                 local iswall = (above.y == under.y)
428                 local isceiling = not iswall and (above.y < under.y)
429                 local anode = core.get_node_or_nil(above)
430                 if not anode then
431                         return
432                 end
433                 local pos = pointed_thing.above
434                 local node = anode
435
436                 if undef and undef.buildable_to then
437                         pos = pointed_thing.under
438                         node = unode
439                         iswall = false
440                 end
441
442                 if core.is_protected(pos, placer:get_player_name()) then
443                         core.record_protection_violation(pos,
444                                         placer:get_player_name())
445                         return
446                 end
447
448                 local ndef = core.registered_nodes[node.name]
449                 if not ndef or not ndef.buildable_to then
450                         return
451                 end
452
453                 if orient_flags.force_floor then
454                         iswall = false
455                         isceiling = false
456                 elseif orient_flags.force_ceiling then
457                         iswall = false
458                         isceiling = true
459                 elseif orient_flags.force_wall then
460                         iswall = true
461                         isceiling = false
462                 elseif orient_flags.invert_wall then
463                         iswall = not iswall
464                 end
465
466                 if iswall then
467                         core.set_node(pos, {name = wield_name,
468                                         param2 = dirs1[fdir + 1]})
469                 elseif isceiling then
470                         if orient_flags.force_facedir then
471                                 core.set_node(pos, {name = wield_name,
472                                                 param2 = 20})
473                         else
474                                 core.set_node(pos, {name = wield_name,
475                                                 param2 = dirs2[fdir + 1]})
476                         end
477                 else -- place right side up
478                         if orient_flags.force_facedir then
479                                 core.set_node(pos, {name = wield_name,
480                                                 param2 = 0})
481                         else
482                                 core.set_node(pos, {name = wield_name,
483                                                 param2 = fdir})
484                         end
485                 end
486
487                 if not infinitestacks then
488                         itemstack:take_item()
489                         return itemstack
490                 end
491         end
492
493
494 --------------------------------------------------------------------------------
495 --Wrapper for rotate_and_place() to check for sneak and assume Creative mode
496 --implies infinite stacks when performing a 6d rotation.
497 --------------------------------------------------------------------------------
498
499
500         core.rotate_node = function(itemstack, placer, pointed_thing)
501                 core.rotate_and_place(itemstack, placer, pointed_thing,
502                                 core.setting_getbool("creative_mode"),
503                                 {invert_wall = placer:get_player_control().sneak})
504                 return itemstack
505         end
506 end
507
508 --------------------------------------------------------------------------------
509 function core.explode_table_event(evt)
510         if evt ~= nil then
511                 local parts = evt:split(":")
512                 if #parts == 3 then
513                         local t = parts[1]:trim()
514                         local r = tonumber(parts[2]:trim())
515                         local c = tonumber(parts[3]:trim())
516                         if type(r) == "number" and type(c) == "number"
517                                         and t ~= "INV" then
518                                 return {type=t, row=r, column=c}
519                         end
520                 end
521         end
522         return {type="INV", row=0, column=0}
523 end
524
525 --------------------------------------------------------------------------------
526 function core.explode_textlist_event(evt)
527         if evt ~= nil then
528                 local parts = evt:split(":")
529                 if #parts == 2 then
530                         local t = parts[1]:trim()
531                         local r = tonumber(parts[2]:trim())
532                         if type(r) == "number" and t ~= "INV" then
533                                 return {type=t, index=r}
534                         end
535                 end
536         end
537         return {type="INV", index=0}
538 end
539
540 --------------------------------------------------------------------------------
541 function core.explode_scrollbar_event(evt)
542         local retval = core.explode_textlist_event(evt)
543
544         retval.value = retval.index
545         retval.index = nil
546
547         return retval
548 end
549
550 --------------------------------------------------------------------------------
551 function core.pos_to_string(pos, decimal_places)
552         local x = pos.x
553         local y = pos.y
554         local z = pos.z
555         if decimal_places ~= nil then
556                 x = string.format("%." .. decimal_places .. "f", x)
557                 y = string.format("%." .. decimal_places .. "f", y)
558                 z = string.format("%." .. decimal_places .. "f", z)
559         end
560         return "(" .. x .. "," .. y .. "," .. z .. ")"
561 end
562
563 --------------------------------------------------------------------------------
564 function core.string_to_pos(value)
565         if value == nil then
566                 return nil
567         end
568
569         local p = {}
570         p.x, p.y, p.z = string.match(value, "^([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+)$")
571         if p.x and p.y and p.z then
572                 p.x = tonumber(p.x)
573                 p.y = tonumber(p.y)
574                 p.z = tonumber(p.z)
575                 return p
576         end
577         local p = {}
578         p.x, p.y, p.z = string.match(value, "^%( *([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+) *%)$")
579         if p.x and p.y and p.z then
580                 p.x = tonumber(p.x)
581                 p.y = tonumber(p.y)
582                 p.z = tonumber(p.z)
583                 return p
584         end
585         return nil
586 end
587
588 assert(core.string_to_pos("10.0, 5, -2").x == 10)
589 assert(core.string_to_pos("( 10.0, 5, -2)").z == -2)
590 assert(core.string_to_pos("asd, 5, -2)") == nil)
591
592 --------------------------------------------------------------------------------
593 function core.string_to_area(value)
594         local p1, p2 = unpack(value:split(") ("))
595         if p1 == nil or p2 == nil then
596                 return nil
597         end
598
599         p1 = core.string_to_pos(p1 .. ")")
600         p2 = core.string_to_pos("(" .. p2)
601         if p1 == nil or p2 == nil then
602                 return nil
603         end
604
605         return p1, p2
606 end
607
608 local function test_string_to_area()
609         local p1, p2 = core.string_to_area("(10.0, 5, -2) (  30.2,   4, -12.53)")
610         assert(p1.x == 10.0 and p1.y == 5 and p1.z == -2)
611         assert(p2.x == 30.2 and p2.y == 4 and p2.z == -12.53)
612
613         p1, p2 = core.string_to_area("(10.0, 5, -2  30.2,   4, -12.53")
614         assert(p1 == nil and p2 == nil)
615
616         p1, p2 = core.string_to_area("(10.0, 5,) -2  fgdf2,   4, -12.53")
617         assert(p1 == nil and p2 == nil)
618 end
619
620 test_string_to_area()
621
622 --------------------------------------------------------------------------------
623 function table.copy(t, seen)
624         local n = {}
625         seen = seen or {}
626         seen[t] = n
627         for k, v in pairs(t) do
628                 n[(type(k) == "table" and (seen[k] or table.copy(k, seen))) or k] =
629                         (type(v) == "table" and (seen[v] or table.copy(v, seen))) or v
630         end
631         return n
632 end
633 --------------------------------------------------------------------------------
634 -- mainmenu only functions
635 --------------------------------------------------------------------------------
636 if INIT == "mainmenu" then
637         function core.get_game(index)
638                 local games = game.get_games()
639
640                 if index > 0 and index <= #games then
641                         return games[index]
642                 end
643
644                 return nil
645         end
646
647         function fgettext_ne(text, ...)
648                 text = core.gettext(text)
649                 local arg = {n=select('#', ...), ...}
650                 if arg.n >= 1 then
651                         -- Insert positional parameters ($1, $2, ...)
652                         local result = ''
653                         local pos = 1
654                         while pos <= text:len() do
655                                 local newpos = text:find('[$]', pos)
656                                 if newpos == nil then
657                                         result = result .. text:sub(pos)
658                                         pos = text:len() + 1
659                                 else
660                                         local paramindex =
661                                                 tonumber(text:sub(newpos+1, newpos+1))
662                                         result = result .. text:sub(pos, newpos-1)
663                                                 .. tostring(arg[paramindex])
664                                         pos = newpos + 2
665                                 end
666                         end
667                         text = result
668                 end
669                 return text
670         end
671
672         function fgettext(text, ...)
673                 return core.formspec_escape(fgettext_ne(text, ...))
674         end
675 end
676