misc_helpers.lua 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  1. -- Minetest: builtin/misc_helpers.lua
  2. --------------------------------------------------------------------------------
  3. -- Localize functions to avoid table lookups (better performance).
  4. local string_sub, string_find = string.sub, string.find
  5. --------------------------------------------------------------------------------
  6. local function basic_dump(o)
  7. local tp = type(o)
  8. if tp == "number" then
  9. return tostring(o)
  10. elseif tp == "string" then
  11. return string.format("%q", o)
  12. elseif tp == "boolean" then
  13. return tostring(o)
  14. elseif tp == "nil" then
  15. return "nil"
  16. -- Uncomment for full function dumping support.
  17. -- Not currently enabled because bytecode isn't very human-readable and
  18. -- dump's output is intended for humans.
  19. --elseif tp == "function" then
  20. -- return string.format("loadstring(%q)", string.dump(o))
  21. elseif tp == "userdata" then
  22. return tostring(o)
  23. else
  24. return string.format("<%s>", tp)
  25. end
  26. end
  27. local keywords = {
  28. ["and"] = true,
  29. ["break"] = true,
  30. ["do"] = true,
  31. ["else"] = true,
  32. ["elseif"] = true,
  33. ["end"] = true,
  34. ["false"] = true,
  35. ["for"] = true,
  36. ["function"] = true,
  37. ["goto"] = true, -- Lua 5.2
  38. ["if"] = true,
  39. ["in"] = true,
  40. ["local"] = true,
  41. ["nil"] = true,
  42. ["not"] = true,
  43. ["or"] = true,
  44. ["repeat"] = true,
  45. ["return"] = true,
  46. ["then"] = true,
  47. ["true"] = true,
  48. ["until"] = true,
  49. ["while"] = true,
  50. }
  51. local function is_valid_identifier(str)
  52. if not str:find("^[a-zA-Z_][a-zA-Z0-9_]*$") or keywords[str] then
  53. return false
  54. end
  55. return true
  56. end
  57. --------------------------------------------------------------------------------
  58. -- Dumps values in a line-per-value format.
  59. -- For example, {test = {"Testing..."}} becomes:
  60. -- _["test"] = {}
  61. -- _["test"][1] = "Testing..."
  62. -- This handles tables as keys and circular references properly.
  63. -- It also handles multiple references well, writing the table only once.
  64. -- The dumped argument is internal-only.
  65. function dump2(o, name, dumped)
  66. name = name or "_"
  67. -- "dumped" is used to keep track of serialized tables to handle
  68. -- multiple references and circular tables properly.
  69. -- It only contains tables as keys. The value is the name that
  70. -- the table has in the dump, eg:
  71. -- {x = {"y"}} -> dumped[{"y"}] = '_["x"]'
  72. dumped = dumped or {}
  73. if type(o) ~= "table" then
  74. return string.format("%s = %s\n", name, basic_dump(o))
  75. end
  76. if dumped[o] then
  77. return string.format("%s = %s\n", name, dumped[o])
  78. end
  79. dumped[o] = name
  80. -- This contains a list of strings to be concatenated later (because
  81. -- Lua is slow at individual concatenation).
  82. local t = {}
  83. for k, v in pairs(o) do
  84. local keyStr
  85. if type(k) == "table" then
  86. if dumped[k] then
  87. keyStr = dumped[k]
  88. else
  89. -- Key tables don't have a name, so use one of
  90. -- the form _G["table: 0xFFFFFFF"]
  91. keyStr = string.format("_G[%q]", tostring(k))
  92. -- Dump key table
  93. t[#t + 1] = dump2(k, keyStr, dumped)
  94. end
  95. else
  96. keyStr = basic_dump(k)
  97. end
  98. local vname = string.format("%s[%s]", name, keyStr)
  99. t[#t + 1] = dump2(v, vname, dumped)
  100. end
  101. return string.format("%s = {}\n%s", name, table.concat(t))
  102. end
  103. --------------------------------------------------------------------------------
  104. -- This dumps values in a one-statement format.
  105. -- For example, {test = {"Testing..."}} becomes:
  106. -- [[{
  107. -- test = {
  108. -- "Testing..."
  109. -- }
  110. -- }]]
  111. -- This supports tables as keys, but not circular references.
  112. -- It performs poorly with multiple references as it writes out the full
  113. -- table each time.
  114. -- The indent field specifies a indentation string, it defaults to a tab.
  115. -- Use the empty string to disable indentation.
  116. -- The dumped and level arguments are internal-only.
  117. function dump(o, indent, nested, level)
  118. local t = type(o)
  119. if not level and t == "userdata" then
  120. -- when userdata (e.g. player) is passed directly, print its metatable:
  121. return "userdata metatable: " .. dump(getmetatable(o))
  122. end
  123. if t ~= "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 ret = {}
  135. local dumped_indexes = {}
  136. for i, v in ipairs(o) do
  137. ret[#ret + 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. ret[#ret + 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(ret, ","..indent_str),
  156. end_indent_str)
  157. end
  158. return "{"..table.concat(ret, ", ").."}"
  159. end
  160. --------------------------------------------------------------------------------
  161. function string.split(str, delim, include_empty, max_splits, sep_is_pattern)
  162. delim = delim or ","
  163. max_splits = max_splits or -2
  164. local items = {}
  165. local pos, len = 1, #str
  166. local plain = not sep_is_pattern
  167. max_splits = max_splits + 1
  168. repeat
  169. local np, npe = string_find(str, delim, pos, plain)
  170. np, npe = (np or (len+1)), (npe or (len+1))
  171. if (not np) or (max_splits == 1) then
  172. np = len + 1
  173. npe = np
  174. end
  175. local s = string_sub(str, pos, np - 1)
  176. if include_empty or (s ~= "") then
  177. max_splits = max_splits - 1
  178. items[#items + 1] = s
  179. end
  180. pos = npe + 1
  181. until (max_splits == 0) or (pos > (len + 1))
  182. return items
  183. end
  184. --------------------------------------------------------------------------------
  185. function table.indexof(list, val)
  186. for i, v in ipairs(list) do
  187. if v == val then
  188. return i
  189. end
  190. end
  191. return -1
  192. end
  193. --------------------------------------------------------------------------------
  194. function string:trim()
  195. return (self:gsub("^%s*(.-)%s*$", "%1"))
  196. end
  197. --------------------------------------------------------------------------------
  198. function math.hypot(x, y)
  199. local t
  200. x = math.abs(x)
  201. y = math.abs(y)
  202. t = math.min(x, y)
  203. x = math.max(x, y)
  204. if x == 0 then return 0 end
  205. t = t / x
  206. return x * math.sqrt(1 + t * t)
  207. end
  208. --------------------------------------------------------------------------------
  209. function math.sign(x, tolerance)
  210. tolerance = tolerance or 0
  211. if x > tolerance then
  212. return 1
  213. elseif x < -tolerance then
  214. return -1
  215. end
  216. return 0
  217. end
  218. --------------------------------------------------------------------------------
  219. function math.factorial(x)
  220. assert(x % 1 == 0 and x >= 0, "factorial expects a non-negative integer")
  221. if x >= 171 then
  222. -- 171! is greater than the biggest double, no need to calculate
  223. return math.huge
  224. end
  225. local v = 1
  226. for k = 2, x do
  227. v = v * k
  228. end
  229. return v
  230. end
  231. function core.formspec_escape(text)
  232. if text ~= nil then
  233. text = string.gsub(text,"\\","\\\\")
  234. text = string.gsub(text,"%]","\\]")
  235. text = string.gsub(text,"%[","\\[")
  236. text = string.gsub(text,";","\\;")
  237. text = string.gsub(text,",","\\,")
  238. end
  239. return text
  240. end
  241. function core.wrap_text(text, max_length, as_table)
  242. local result = {}
  243. local line = {}
  244. if #text <= max_length then
  245. return as_table and {text} or text
  246. end
  247. for word in text:gmatch('%S+') do
  248. local cur_length = #table.concat(line, ' ')
  249. if cur_length > 0 and cur_length + #word + 1 >= max_length then
  250. -- word wouldn't fit on current line, move to next line
  251. table.insert(result, table.concat(line, ' '))
  252. line = {}
  253. end
  254. table.insert(line, word)
  255. end
  256. table.insert(result, table.concat(line, ' '))
  257. return as_table and result or table.concat(result, '\n')
  258. end
  259. --------------------------------------------------------------------------------
  260. if INIT == "game" then
  261. local dirs1 = {9, 18, 7, 12}
  262. local dirs2 = {20, 23, 22, 21}
  263. function core.rotate_and_place(itemstack, placer, pointed_thing,
  264. infinitestacks, orient_flags, prevent_after_place)
  265. orient_flags = orient_flags or {}
  266. local unode = core.get_node_or_nil(pointed_thing.under)
  267. if not unode then
  268. return
  269. end
  270. local undef = core.registered_nodes[unode.name]
  271. local sneaking = placer and placer:get_player_control().sneak
  272. if undef and undef.on_rightclick and not sneaking then
  273. return undef.on_rightclick(pointed_thing.under, unode, placer,
  274. itemstack, pointed_thing)
  275. end
  276. local fdir = placer and core.dir_to_facedir(placer:get_look_dir()) or 0
  277. local above = pointed_thing.above
  278. local under = pointed_thing.under
  279. local iswall = (above.y == under.y)
  280. local isceiling = not iswall and (above.y < under.y)
  281. if undef and undef.buildable_to then
  282. iswall = false
  283. end
  284. if orient_flags.force_floor then
  285. iswall = false
  286. isceiling = false
  287. elseif orient_flags.force_ceiling then
  288. iswall = false
  289. isceiling = true
  290. elseif orient_flags.force_wall then
  291. iswall = true
  292. isceiling = false
  293. elseif orient_flags.invert_wall then
  294. iswall = not iswall
  295. end
  296. local param2 = fdir
  297. if iswall then
  298. param2 = dirs1[fdir + 1]
  299. elseif isceiling then
  300. if orient_flags.force_facedir then
  301. param2 = 20
  302. else
  303. param2 = dirs2[fdir + 1]
  304. end
  305. else -- place right side up
  306. if orient_flags.force_facedir then
  307. param2 = 0
  308. end
  309. end
  310. local old_itemstack = ItemStack(itemstack)
  311. local new_itemstack = core.item_place_node(itemstack, placer,
  312. pointed_thing, param2, prevent_after_place)
  313. return infinitestacks and old_itemstack or new_itemstack
  314. end
  315. --------------------------------------------------------------------------------
  316. --Wrapper for rotate_and_place() to check for sneak and assume Creative mode
  317. --implies infinite stacks when performing a 6d rotation.
  318. --------------------------------------------------------------------------------
  319. core.rotate_node = function(itemstack, placer, pointed_thing)
  320. local name = placer and placer:get_player_name() or ""
  321. local invert_wall = placer and placer:get_player_control().sneak or false
  322. return core.rotate_and_place(itemstack, placer, pointed_thing,
  323. core.is_creative_enabled(name),
  324. {invert_wall = invert_wall}, true)
  325. end
  326. end
  327. --------------------------------------------------------------------------------
  328. function core.explode_table_event(evt)
  329. if evt ~= nil then
  330. local parts = evt:split(":")
  331. if #parts == 3 then
  332. local t = parts[1]:trim()
  333. local r = tonumber(parts[2]:trim())
  334. local c = tonumber(parts[3]:trim())
  335. if type(r) == "number" and type(c) == "number"
  336. and t ~= "INV" then
  337. return {type=t, row=r, column=c}
  338. end
  339. end
  340. end
  341. return {type="INV", row=0, column=0}
  342. end
  343. --------------------------------------------------------------------------------
  344. function core.explode_textlist_event(evt)
  345. if evt ~= nil then
  346. local parts = evt:split(":")
  347. if #parts == 2 then
  348. local t = parts[1]:trim()
  349. local r = tonumber(parts[2]:trim())
  350. if type(r) == "number" and t ~= "INV" then
  351. return {type=t, index=r}
  352. end
  353. end
  354. end
  355. return {type="INV", index=0}
  356. end
  357. --------------------------------------------------------------------------------
  358. function core.explode_scrollbar_event(evt)
  359. local retval = core.explode_textlist_event(evt)
  360. retval.value = retval.index
  361. retval.index = nil
  362. return retval
  363. end
  364. --------------------------------------------------------------------------------
  365. function core.rgba(r, g, b, a)
  366. return a and string.format("#%02X%02X%02X%02X", r, g, b, a) or
  367. string.format("#%02X%02X%02X", r, g, b)
  368. end
  369. --------------------------------------------------------------------------------
  370. function core.pos_to_string(pos, decimal_places)
  371. local x = pos.x
  372. local y = pos.y
  373. local z = pos.z
  374. if decimal_places ~= nil then
  375. x = string.format("%." .. decimal_places .. "f", x)
  376. y = string.format("%." .. decimal_places .. "f", y)
  377. z = string.format("%." .. decimal_places .. "f", z)
  378. end
  379. return "(" .. x .. "," .. y .. "," .. z .. ")"
  380. end
  381. --------------------------------------------------------------------------------
  382. function core.string_to_pos(value)
  383. if value == nil then
  384. return nil
  385. end
  386. local p = {}
  387. p.x, p.y, p.z = string.match(value, "^([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+)$")
  388. if p.x and p.y and p.z then
  389. p.x = tonumber(p.x)
  390. p.y = tonumber(p.y)
  391. p.z = tonumber(p.z)
  392. return p
  393. end
  394. p = {}
  395. p.x, p.y, p.z = string.match(value, "^%( *([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+) *%)$")
  396. if p.x and p.y and p.z then
  397. p.x = tonumber(p.x)
  398. p.y = tonumber(p.y)
  399. p.z = tonumber(p.z)
  400. return p
  401. end
  402. return nil
  403. end
  404. --------------------------------------------------------------------------------
  405. function core.string_to_area(value)
  406. local p1, p2 = unpack(value:split(") ("))
  407. if p1 == nil or p2 == nil then
  408. return nil
  409. end
  410. p1 = core.string_to_pos(p1 .. ")")
  411. p2 = core.string_to_pos("(" .. p2)
  412. if p1 == nil or p2 == nil then
  413. return nil
  414. end
  415. return p1, p2
  416. end
  417. local function test_string_to_area()
  418. local p1, p2 = core.string_to_area("(10.0, 5, -2) ( 30.2, 4, -12.53)")
  419. assert(p1.x == 10.0 and p1.y == 5 and p1.z == -2)
  420. assert(p2.x == 30.2 and p2.y == 4 and p2.z == -12.53)
  421. p1, p2 = core.string_to_area("(10.0, 5, -2 30.2, 4, -12.53")
  422. assert(p1 == nil and p2 == nil)
  423. p1, p2 = core.string_to_area("(10.0, 5,) -2 fgdf2, 4, -12.53")
  424. assert(p1 == nil and p2 == nil)
  425. end
  426. test_string_to_area()
  427. --------------------------------------------------------------------------------
  428. function table.copy(t, seen)
  429. local n = {}
  430. seen = seen or {}
  431. seen[t] = n
  432. for k, v in pairs(t) do
  433. n[(type(k) == "table" and (seen[k] or table.copy(k, seen))) or k] =
  434. (type(v) == "table" and (seen[v] or table.copy(v, seen))) or v
  435. end
  436. return n
  437. end
  438. function table.insert_all(t, other)
  439. for i=1, #other do
  440. t[#t + 1] = other[i]
  441. end
  442. return t
  443. end
  444. function table.key_value_swap(t)
  445. local ti = {}
  446. for k,v in pairs(t) do
  447. ti[v] = k
  448. end
  449. return ti
  450. end
  451. function table.shuffle(t, from, to, random)
  452. from = from or 1
  453. to = to or #t
  454. random = random or math.random
  455. local n = to - from + 1
  456. while n > 1 do
  457. local r = from + n-1
  458. local l = from + random(0, n-1)
  459. t[l], t[r] = t[r], t[l]
  460. n = n-1
  461. end
  462. end
  463. --------------------------------------------------------------------------------
  464. -- mainmenu only functions
  465. --------------------------------------------------------------------------------
  466. if INIT == "mainmenu" then
  467. function core.get_game(index)
  468. local games = core.get_games()
  469. if index > 0 and index <= #games then
  470. return games[index]
  471. end
  472. return nil
  473. end
  474. end
  475. if INIT == "client" or INIT == "mainmenu" then
  476. function fgettext_ne(text, ...)
  477. text = core.gettext(text)
  478. local arg = {n=select('#', ...), ...}
  479. if arg.n >= 1 then
  480. -- Insert positional parameters ($1, $2, ...)
  481. local result = ''
  482. local pos = 1
  483. while pos <= text:len() do
  484. local newpos = text:find('[$]', pos)
  485. if newpos == nil then
  486. result = result .. text:sub(pos)
  487. pos = text:len() + 1
  488. else
  489. local paramindex =
  490. tonumber(text:sub(newpos+1, newpos+1))
  491. result = result .. text:sub(pos, newpos-1)
  492. .. tostring(arg[paramindex])
  493. pos = newpos + 2
  494. end
  495. end
  496. text = result
  497. end
  498. return text
  499. end
  500. function fgettext(text, ...)
  501. return core.formspec_escape(fgettext_ne(text, ...))
  502. end
  503. end
  504. local ESCAPE_CHAR = string.char(0x1b)
  505. function core.get_color_escape_sequence(color)
  506. return ESCAPE_CHAR .. "(c@" .. color .. ")"
  507. end
  508. function core.get_background_escape_sequence(color)
  509. return ESCAPE_CHAR .. "(b@" .. color .. ")"
  510. end
  511. function core.colorize(color, message)
  512. local lines = tostring(message):split("\n", true)
  513. local color_code = core.get_color_escape_sequence(color)
  514. for i, line in ipairs(lines) do
  515. lines[i] = color_code .. line
  516. end
  517. return table.concat(lines, "\n") .. core.get_color_escape_sequence("#ffffff")
  518. end
  519. function core.strip_foreground_colors(str)
  520. return (str:gsub(ESCAPE_CHAR .. "%(c@[^)]+%)", ""))
  521. end
  522. function core.strip_background_colors(str)
  523. return (str:gsub(ESCAPE_CHAR .. "%(b@[^)]+%)", ""))
  524. end
  525. function core.strip_colors(str)
  526. return (str:gsub(ESCAPE_CHAR .. "%([bc]@[^)]+%)", ""))
  527. end
  528. function core.translate(textdomain, str, ...)
  529. local start_seq
  530. if textdomain == "" then
  531. start_seq = ESCAPE_CHAR .. "T"
  532. else
  533. start_seq = ESCAPE_CHAR .. "(T@" .. textdomain .. ")"
  534. end
  535. local arg = {n=select('#', ...), ...}
  536. local end_seq = ESCAPE_CHAR .. "E"
  537. local arg_index = 1
  538. local translated = str:gsub("@(.)", function(matched)
  539. local c = string.byte(matched)
  540. if string.byte("1") <= c and c <= string.byte("9") then
  541. local a = c - string.byte("0")
  542. if a ~= arg_index then
  543. error("Escape sequences in string given to core.translate " ..
  544. "are not in the correct order: got @" .. matched ..
  545. "but expected @" .. tostring(arg_index))
  546. end
  547. if a > arg.n then
  548. error("Not enough arguments provided to core.translate")
  549. end
  550. arg_index = arg_index + 1
  551. return ESCAPE_CHAR .. "F" .. arg[a] .. ESCAPE_CHAR .. "E"
  552. elseif matched == "n" then
  553. return "\n"
  554. else
  555. return matched
  556. end
  557. end)
  558. if arg_index < arg.n + 1 then
  559. error("Too many arguments provided to core.translate")
  560. end
  561. return start_seq .. translated .. end_seq
  562. end
  563. function core.get_translator(textdomain)
  564. return function(str, ...) return core.translate(textdomain or "", str, ...) end
  565. end
  566. --------------------------------------------------------------------------------
  567. -- Returns the exact coordinate of a pointed surface
  568. --------------------------------------------------------------------------------
  569. function core.pointed_thing_to_face_pos(placer, pointed_thing)
  570. -- Avoid crash in some situations when player is inside a node, causing
  571. -- 'above' to equal 'under'.
  572. if vector.equals(pointed_thing.above, pointed_thing.under) then
  573. return pointed_thing.under
  574. end
  575. local eye_height = placer:get_properties().eye_height
  576. local eye_offset_first = placer:get_eye_offset()
  577. local node_pos = pointed_thing.under
  578. local camera_pos = placer:get_pos()
  579. local pos_off = vector.multiply(
  580. vector.subtract(pointed_thing.above, node_pos), 0.5)
  581. local look_dir = placer:get_look_dir()
  582. local offset, nc
  583. local oc = {}
  584. for c, v in pairs(pos_off) do
  585. if nc or v == 0 then
  586. oc[#oc + 1] = c
  587. else
  588. offset = v
  589. nc = c
  590. end
  591. end
  592. local fine_pos = {[nc] = node_pos[nc] + offset}
  593. camera_pos.y = camera_pos.y + eye_height + eye_offset_first.y / 10
  594. local f = (node_pos[nc] + offset - camera_pos[nc]) / look_dir[nc]
  595. for i = 1, #oc do
  596. fine_pos[oc[i]] = camera_pos[oc[i]] + look_dir[oc[i]] * f
  597. end
  598. return fine_pos
  599. end
  600. function core.string_to_privs(str, delim)
  601. assert(type(str) == "string")
  602. delim = delim or ','
  603. local privs = {}
  604. for _, priv in pairs(string.split(str, delim)) do
  605. privs[priv:trim()] = true
  606. end
  607. return privs
  608. end
  609. function core.privs_to_string(privs, delim)
  610. assert(type(privs) == "table")
  611. delim = delim or ','
  612. local list = {}
  613. for priv, bool in pairs(privs) do
  614. if bool then
  615. list[#list + 1] = priv
  616. end
  617. end
  618. return table.concat(list, delim)
  619. end
  620. function core.is_nan(number)
  621. return number ~= number
  622. end