misc_helpers.lua 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875
  1. --------------------------------------------------------------------------------
  2. -- Localize functions to avoid table lookups (better performance).
  3. local string_sub, string_find = string.sub, string.find
  4. local math = math
  5. --------------------------------------------------------------------------------
  6. local function basic_dump(o)
  7. local tp = type(o)
  8. if tp == "number" then
  9. local s = tostring(o)
  10. if tonumber(s) == o then
  11. return s
  12. end
  13. -- Prefer an exact representation over a compact representation.
  14. -- e.g. basic_dump(0.3) == "0.3",
  15. -- but basic_dump(0.1 + 0.2) == "0.30000000000000004"
  16. -- so the user can see that 0.1 + 0.2 ~= 0.3
  17. return string.format("%.17g", o)
  18. elseif tp == "string" then
  19. return string.format("%q", o)
  20. elseif tp == "boolean" then
  21. return tostring(o)
  22. elseif tp == "nil" then
  23. return "nil"
  24. elseif tp == "userdata" then
  25. return tostring(o)
  26. else
  27. return string.format("<%s>", tp)
  28. end
  29. end
  30. local keywords = {
  31. ["and"] = true,
  32. ["break"] = true,
  33. ["do"] = true,
  34. ["else"] = true,
  35. ["elseif"] = true,
  36. ["end"] = true,
  37. ["false"] = true,
  38. ["for"] = true,
  39. ["function"] = true,
  40. ["goto"] = true, -- Lua 5.2
  41. ["if"] = true,
  42. ["in"] = true,
  43. ["local"] = true,
  44. ["nil"] = true,
  45. ["not"] = true,
  46. ["or"] = true,
  47. ["repeat"] = true,
  48. ["return"] = true,
  49. ["then"] = true,
  50. ["true"] = true,
  51. ["until"] = true,
  52. ["while"] = true,
  53. }
  54. local function is_valid_identifier(str)
  55. if not str:find("^[a-zA-Z_][a-zA-Z0-9_]*$") or keywords[str] then
  56. return false
  57. end
  58. return true
  59. end
  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. 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. -- This dumps values in a human-readable expression format.
  107. -- If possible, the resulting string should evaluate to an equivalent value if loaded and executed.
  108. -- For example, {test = {"Testing..."}} becomes:
  109. -- [[{
  110. -- test = {
  111. -- "Testing..."
  112. -- }
  113. -- }]]
  114. function dump(value, indent)
  115. indent = indent or "\t"
  116. local newline = indent == "" and "" or "\n"
  117. local rope = {}
  118. local write
  119. do
  120. -- Keeping the length of the table as a local variable is *much*
  121. -- faster than invoking the length operator.
  122. -- See https://gitspartv.github.io/LuaJIT-Benchmarks/#test12.
  123. local i = 0
  124. function write(str)
  125. i = i + 1
  126. rope[i] = str
  127. end
  128. end
  129. local n_refs = {}
  130. local function count_refs(val)
  131. if type(val) ~= "table" then
  132. return
  133. end
  134. local tbl = val
  135. if n_refs[tbl] then
  136. n_refs[tbl] = n_refs[tbl] + 1
  137. return
  138. end
  139. n_refs[tbl] = 1
  140. for k, v in pairs(tbl) do
  141. count_refs(k)
  142. count_refs(v)
  143. end
  144. end
  145. count_refs(value)
  146. local refs = {}
  147. local cur_ref = 1
  148. local function write_value(val, level)
  149. if type(val) ~= "table" then
  150. write(basic_dump(val))
  151. return
  152. end
  153. local tbl = val
  154. if refs[tbl] then
  155. write(refs[tbl])
  156. return
  157. end
  158. if n_refs[val] > 1 then
  159. refs[val] = ("getref(%d)"):format(cur_ref)
  160. write(("setref(%d)"):format(cur_ref))
  161. cur_ref = cur_ref + 1
  162. end
  163. write("{")
  164. if next(tbl) == nil then
  165. write("}")
  166. return
  167. end
  168. write(newline)
  169. local function write_entry(k, v)
  170. write(indent:rep(level))
  171. write("[")
  172. write_value(k, level + 1)
  173. write("] = ")
  174. write_value(v, level + 1)
  175. write(",")
  176. write(newline)
  177. end
  178. local keys = {string = {}, number = {}}
  179. for k in pairs(tbl) do
  180. local t = type(k)
  181. if keys[t] then
  182. table.insert(keys[t], k)
  183. end
  184. end
  185. -- Write string-keyed entries
  186. table.sort(keys.string)
  187. for _, k in ipairs(keys.string) do
  188. local v = val[k]
  189. if is_valid_identifier(k) then
  190. write(indent:rep(level))
  191. write(k)
  192. write(" = ")
  193. write_value(v, level + 1)
  194. write(",")
  195. write(newline)
  196. else
  197. write_entry(k, v)
  198. end
  199. end
  200. -- Write number-keyed entries
  201. local len = 0
  202. for i in ipairs(tbl) do
  203. len = i
  204. end
  205. if #keys.number == len then -- table is a list
  206. for _, v in ipairs(tbl) do
  207. write(indent:rep(level))
  208. write_value(v, level + 1)
  209. write(",")
  210. write(newline)
  211. end
  212. else -- table harbors arbitrary number keys
  213. table.sort(keys.number)
  214. for _, k in ipairs(keys.number) do
  215. write_entry(k, tbl[k])
  216. end
  217. end
  218. -- Write all remaining entries
  219. for k, v in pairs(val) do
  220. if not keys[type(k)] then
  221. write_entry(k, v)
  222. end
  223. end
  224. write(indent:rep(level - 1))
  225. write("}")
  226. end
  227. write_value(value, 1)
  228. return table.concat(rope)
  229. end
  230. --------------------------------------------------------------------------------
  231. function string.split(str, delim, include_empty, max_splits, sep_is_pattern)
  232. delim = delim or ","
  233. if delim == "" then
  234. error("string.split separator is empty", 2)
  235. end
  236. max_splits = max_splits or -2
  237. local items = {}
  238. local pos, len = 1, #str
  239. local plain = not sep_is_pattern
  240. max_splits = max_splits + 1
  241. repeat
  242. local np, npe = string_find(str, delim, pos, plain)
  243. np, npe = (np or (len+1)), (npe or (len+1))
  244. if (not np) or (max_splits == 1) then
  245. np = len + 1
  246. npe = np
  247. end
  248. local s = string_sub(str, pos, np - 1)
  249. if include_empty or (s ~= "") then
  250. max_splits = max_splits - 1
  251. items[#items + 1] = s
  252. end
  253. pos = npe + 1
  254. until (max_splits == 0) or (pos > (len + 1))
  255. return items
  256. end
  257. --------------------------------------------------------------------------------
  258. function table.indexof(list, val)
  259. for i, v in ipairs(list) do
  260. if v == val then
  261. return i
  262. end
  263. end
  264. return -1
  265. end
  266. --------------------------------------------------------------------------------
  267. function table.keyof(tb, val)
  268. for k, v in pairs(tb) do
  269. if v == val then
  270. return k
  271. end
  272. end
  273. return nil
  274. end
  275. --------------------------------------------------------------------------------
  276. function string:trim()
  277. return self:match("^%s*(.-)%s*$")
  278. end
  279. local formspec_escapes = {
  280. ["\\"] = "\\\\",
  281. ["["] = "\\[",
  282. ["]"] = "\\]",
  283. [";"] = "\\;",
  284. [","] = "\\,",
  285. ["$"] = "\\$",
  286. }
  287. function core.formspec_escape(text)
  288. -- Use explicit character set instead of dot here because it doubles the performance
  289. return text and string.gsub(text, "[\\%[%];,$]", formspec_escapes)
  290. end
  291. local hypertext_escapes = {
  292. ["\\"] = "\\\\",
  293. ["<"] = "\\<",
  294. [">"] = "\\>",
  295. }
  296. function core.hypertext_escape(text)
  297. return text and text:gsub("[\\<>]", hypertext_escapes)
  298. end
  299. function core.wrap_text(text, max_length, as_table)
  300. local result = {}
  301. local line = {}
  302. if #text <= max_length then
  303. return as_table and {text} or text
  304. end
  305. local line_length = 0
  306. for word in text:gmatch("%S+") do
  307. if line_length > 0 and line_length + #word + 1 >= max_length then
  308. -- word wouldn't fit on current line, move to next line
  309. table.insert(result, table.concat(line, " "))
  310. line = {word}
  311. line_length = #word
  312. else
  313. table.insert(line, word)
  314. line_length = line_length + 1 + #word
  315. end
  316. end
  317. table.insert(result, table.concat(line, " "))
  318. return as_table and result or table.concat(result, "\n")
  319. end
  320. --------------------------------------------------------------------------------
  321. if INIT == "game" then
  322. local dirs1 = {9, 18, 7, 12}
  323. local dirs2 = {20, 23, 22, 21}
  324. function core.rotate_and_place(itemstack, placer, pointed_thing,
  325. infinitestacks, orient_flags, prevent_after_place)
  326. orient_flags = orient_flags or {}
  327. local unode = core.get_node_or_nil(pointed_thing.under)
  328. if not unode then
  329. return
  330. end
  331. local undef = core.registered_nodes[unode.name]
  332. local sneaking = placer and placer:get_player_control().sneak
  333. if undef and undef.on_rightclick and not sneaking then
  334. return undef.on_rightclick(pointed_thing.under, unode, placer,
  335. itemstack, pointed_thing)
  336. end
  337. local fdir = placer and core.dir_to_facedir(placer:get_look_dir()) or 0
  338. local above = pointed_thing.above
  339. local under = pointed_thing.under
  340. local iswall = (above.y == under.y)
  341. local isceiling = not iswall and (above.y < under.y)
  342. if undef and undef.buildable_to then
  343. iswall = false
  344. end
  345. if orient_flags.force_floor then
  346. iswall = false
  347. isceiling = false
  348. elseif orient_flags.force_ceiling then
  349. iswall = false
  350. isceiling = true
  351. elseif orient_flags.force_wall then
  352. iswall = true
  353. isceiling = false
  354. elseif orient_flags.invert_wall then
  355. iswall = not iswall
  356. end
  357. local param2 = fdir
  358. if iswall then
  359. param2 = dirs1[fdir + 1]
  360. elseif isceiling then
  361. if orient_flags.force_facedir then
  362. param2 = 20
  363. else
  364. param2 = dirs2[fdir + 1]
  365. end
  366. else -- place right side up
  367. if orient_flags.force_facedir then
  368. param2 = 0
  369. end
  370. end
  371. local old_itemstack = ItemStack(itemstack)
  372. local new_itemstack = core.item_place_node(itemstack, placer,
  373. pointed_thing, param2, prevent_after_place)
  374. return infinitestacks and old_itemstack or new_itemstack
  375. end
  376. --------------------------------------------------------------------------------
  377. --Wrapper for rotate_and_place() to check for sneak and assume Creative mode
  378. --implies infinite stacks when performing a 6d rotation.
  379. --------------------------------------------------------------------------------
  380. core.rotate_node = function(itemstack, placer, pointed_thing)
  381. local name = placer and placer:get_player_name() or ""
  382. local invert_wall = placer and placer:get_player_control().sneak or false
  383. return core.rotate_and_place(itemstack, placer, pointed_thing,
  384. core.is_creative_enabled(name),
  385. {invert_wall = invert_wall}, true)
  386. end
  387. end
  388. --------------------------------------------------------------------------------
  389. function core.explode_table_event(evt)
  390. if evt ~= nil then
  391. local parts = evt:split(":")
  392. if #parts == 3 then
  393. local t = parts[1]:trim()
  394. local r = tonumber(parts[2]:trim())
  395. local c = tonumber(parts[3]:trim())
  396. if type(r) == "number" and type(c) == "number"
  397. and t ~= "INV" then
  398. return {type=t, row=r, column=c}
  399. end
  400. end
  401. end
  402. return {type="INV", row=0, column=0}
  403. end
  404. --------------------------------------------------------------------------------
  405. function core.explode_textlist_event(evt)
  406. if evt ~= nil then
  407. local parts = evt:split(":")
  408. if #parts == 2 then
  409. local t = parts[1]:trim()
  410. local r = tonumber(parts[2]:trim())
  411. if type(r) == "number" and t ~= "INV" then
  412. return {type=t, index=r}
  413. end
  414. end
  415. end
  416. return {type="INV", index=0}
  417. end
  418. --------------------------------------------------------------------------------
  419. function core.explode_scrollbar_event(evt)
  420. local retval = core.explode_textlist_event(evt)
  421. retval.value = retval.index
  422. retval.index = nil
  423. return retval
  424. end
  425. --------------------------------------------------------------------------------
  426. function core.rgba(r, g, b, a)
  427. return a and string.format("#%02X%02X%02X%02X", r, g, b, a) or
  428. string.format("#%02X%02X%02X", r, g, b)
  429. end
  430. --------------------------------------------------------------------------------
  431. function core.pos_to_string(pos, decimal_places)
  432. local x = pos.x
  433. local y = pos.y
  434. local z = pos.z
  435. if decimal_places ~= nil then
  436. x = string.format("%." .. decimal_places .. "f", x)
  437. y = string.format("%." .. decimal_places .. "f", y)
  438. z = string.format("%." .. decimal_places .. "f", z)
  439. end
  440. return "(" .. x .. "," .. y .. "," .. z .. ")"
  441. end
  442. --------------------------------------------------------------------------------
  443. function core.string_to_pos(value)
  444. if value == nil then
  445. return nil
  446. end
  447. value = value:match("^%((.-)%)$") or value -- strip parentheses
  448. local x, y, z = value:trim():match("^([%d.-]+)[,%s]%s*([%d.-]+)[,%s]%s*([%d.-]+)$")
  449. if x and y and z then
  450. x = tonumber(x)
  451. y = tonumber(y)
  452. z = tonumber(z)
  453. return vector.new(x, y, z)
  454. end
  455. return nil
  456. end
  457. --------------------------------------------------------------------------------
  458. do
  459. local rel_num_cap = "(~?-?%d*%.?%d*)" -- may be overly permissive as this will be tonumber'ed anyways
  460. local num_delim = "[,%s]%s*"
  461. local pattern = "^" .. table.concat({rel_num_cap, rel_num_cap, rel_num_cap}, num_delim) .. "$"
  462. local function parse_area_string(pos, relative_to)
  463. local pp = {}
  464. pp.x, pp.y, pp.z = pos:trim():match(pattern)
  465. return core.parse_coordinates(pp.x, pp.y, pp.z, relative_to)
  466. end
  467. function core.string_to_area(value, relative_to)
  468. local p1, p2 = value:match("^%((.-)%)%s*%((.-)%)$")
  469. if not p1 then
  470. return
  471. end
  472. p1 = parse_area_string(p1, relative_to)
  473. p2 = parse_area_string(p2, relative_to)
  474. if p1 == nil or p2 == nil then
  475. return
  476. end
  477. return p1, p2
  478. end
  479. end
  480. local function table_copy(value, preserve_metatables)
  481. local seen = {}
  482. local function copy(val)
  483. if type(val) ~= "table" then
  484. return val
  485. end
  486. local t = val
  487. if seen[t] then
  488. return seen[t]
  489. end
  490. local res = {}
  491. seen[t] = res
  492. for k, v in pairs(t) do
  493. res[copy(k)] = copy(v)
  494. end
  495. if preserve_metatables then
  496. setmetatable(res, getmetatable(t))
  497. end
  498. return res
  499. end
  500. return copy(value)
  501. end
  502. function table.copy(value)
  503. return table_copy(value, false)
  504. end
  505. function table.copy_with_metatables(value)
  506. return table_copy(value, true)
  507. end
  508. function table.insert_all(t, other)
  509. if table.move then -- LuaJIT
  510. return table.move(other, 1, #other, #t + 1, t)
  511. end
  512. for i=1, #other do
  513. t[#t + 1] = other[i]
  514. end
  515. return t
  516. end
  517. function table.key_value_swap(t)
  518. local ti = {}
  519. for k,v in pairs(t) do
  520. ti[v] = k
  521. end
  522. return ti
  523. end
  524. function table.shuffle(t, from, to, random)
  525. from = from or 1
  526. to = to or #t
  527. random = random or math.random
  528. local n = to - from + 1
  529. while n > 1 do
  530. local r = from + n-1
  531. local l = from + random(0, n-1)
  532. t[l], t[r] = t[r], t[l]
  533. n = n-1
  534. end
  535. end
  536. --------------------------------------------------------------------------------
  537. -- mainmenu only functions
  538. --------------------------------------------------------------------------------
  539. if core.gettext then -- for client and mainmenu
  540. function fgettext_ne(text, ...)
  541. text = core.gettext(text)
  542. local arg = {n=select('#', ...), ...}
  543. if arg.n >= 1 then
  544. -- Insert positional parameters ($1, $2, ...)
  545. local result = ''
  546. local pos = 1
  547. while pos <= text:len() do
  548. local newpos = text:find('[$]', pos)
  549. if newpos == nil then
  550. result = result .. text:sub(pos)
  551. pos = text:len() + 1
  552. else
  553. local paramindex =
  554. tonumber(text:sub(newpos+1, newpos+1))
  555. result = result .. text:sub(pos, newpos-1)
  556. .. tostring(arg[paramindex])
  557. pos = newpos + 2
  558. end
  559. end
  560. text = result
  561. end
  562. return text
  563. end
  564. function fgettext(text, ...)
  565. return core.formspec_escape(fgettext_ne(text, ...))
  566. end
  567. function hgettext(text, ...)
  568. return core.hypertext_escape(fgettext_ne(text, ...))
  569. end
  570. end
  571. local ESCAPE_CHAR = string.char(0x1b)
  572. function core.get_color_escape_sequence(color)
  573. return ESCAPE_CHAR .. "(c@" .. color .. ")"
  574. end
  575. function core.get_background_escape_sequence(color)
  576. return ESCAPE_CHAR .. "(b@" .. color .. ")"
  577. end
  578. function core.colorize(color, message)
  579. local lines = tostring(message):split("\n", true)
  580. local color_code = core.get_color_escape_sequence(color)
  581. for i, line in ipairs(lines) do
  582. lines[i] = color_code .. line
  583. end
  584. return table.concat(lines, "\n") .. core.get_color_escape_sequence("#ffffff")
  585. end
  586. function core.strip_foreground_colors(str)
  587. return (str:gsub(ESCAPE_CHAR .. "%(c@[^)]+%)", ""))
  588. end
  589. function core.strip_background_colors(str)
  590. return (str:gsub(ESCAPE_CHAR .. "%(b@[^)]+%)", ""))
  591. end
  592. function core.strip_colors(str)
  593. return (str:gsub(ESCAPE_CHAR .. "%([bc]@[^)]+%)", ""))
  594. end
  595. local function translate(textdomain, str, num, ...)
  596. local start_seq
  597. if textdomain == "" and num == "" then
  598. start_seq = ESCAPE_CHAR .. "T"
  599. elseif num == "" then
  600. start_seq = ESCAPE_CHAR .. "(T@" .. textdomain .. ")"
  601. else
  602. start_seq = ESCAPE_CHAR .. "(T@" .. textdomain .. "@" .. num .. ")"
  603. end
  604. local arg = {n=select('#', ...), ...}
  605. local end_seq = ESCAPE_CHAR .. "E"
  606. local arg_index = 1
  607. local translated = str:gsub("@(.)", function(matched)
  608. local c = string.byte(matched)
  609. if string.byte("1") <= c and c <= string.byte("9") then
  610. local a = c - string.byte("0")
  611. if a ~= arg_index then
  612. error("Escape sequences in string given to core.translate " ..
  613. "are not in the correct order: got @" .. matched ..
  614. "but expected @" .. tostring(arg_index))
  615. end
  616. if a > arg.n then
  617. error("Not enough arguments provided to core.translate")
  618. end
  619. arg_index = arg_index + 1
  620. return ESCAPE_CHAR .. "F" .. arg[a] .. ESCAPE_CHAR .. "E"
  621. elseif matched == "n" then
  622. return "\n"
  623. else
  624. return matched
  625. end
  626. end)
  627. if arg_index < arg.n + 1 then
  628. error("Too many arguments provided to core.translate")
  629. end
  630. return start_seq .. translated .. end_seq
  631. end
  632. function core.translate(textdomain, str, ...)
  633. return translate(textdomain, str, "", ...)
  634. end
  635. function core.translate_n(textdomain, str, str_plural, n, ...)
  636. assert (type(n) == "number")
  637. assert (n >= 0)
  638. assert (math.floor(n) == n)
  639. -- Truncate n if too large
  640. local max = 1000000
  641. if n >= 2 * max then
  642. n = n % max + max
  643. end
  644. if n == 1 then
  645. return translate(textdomain, str, "1", ...)
  646. else
  647. return translate(textdomain, str_plural, tostring(n), ...)
  648. end
  649. end
  650. function core.get_translator(textdomain)
  651. return
  652. (function(str, ...) return core.translate(textdomain or "", str, ...) end),
  653. (function(str, str_plural, n, ...) return core.translate_n(textdomain or "", str, str_plural, n, ...) end)
  654. end
  655. --------------------------------------------------------------------------------
  656. -- Returns the exact coordinate of a pointed surface
  657. --------------------------------------------------------------------------------
  658. function core.pointed_thing_to_face_pos(placer, pointed_thing)
  659. -- Avoid crash in some situations when player is inside a node, causing
  660. -- 'above' to equal 'under'.
  661. if vector.equals(pointed_thing.above, pointed_thing.under) then
  662. return pointed_thing.under
  663. end
  664. local eye_height = placer:get_properties().eye_height
  665. local eye_offset_first = placer:get_eye_offset()
  666. local node_pos = pointed_thing.under
  667. local camera_pos = placer:get_pos()
  668. local pos_off = vector.multiply(
  669. vector.subtract(pointed_thing.above, node_pos), 0.5)
  670. local look_dir = placer:get_look_dir()
  671. local offset, nc
  672. local oc = {}
  673. for c, v in pairs(pos_off) do
  674. if nc or v == 0 then
  675. oc[#oc + 1] = c
  676. else
  677. offset = v
  678. nc = c
  679. end
  680. end
  681. local fine_pos = {[nc] = node_pos[nc] + offset}
  682. camera_pos.y = camera_pos.y + eye_height + eye_offset_first.y / 10
  683. local f = (node_pos[nc] + offset - camera_pos[nc]) / look_dir[nc]
  684. for i = 1, #oc do
  685. fine_pos[oc[i]] = camera_pos[oc[i]] + look_dir[oc[i]] * f
  686. end
  687. return fine_pos
  688. end
  689. function core.string_to_privs(str, delim)
  690. assert(type(str) == "string")
  691. delim = delim or ','
  692. local privs = {}
  693. for _, priv in pairs(string.split(str, delim)) do
  694. privs[priv:trim()] = true
  695. end
  696. return privs
  697. end
  698. function core.privs_to_string(privs, delim)
  699. assert(type(privs) == "table")
  700. delim = delim or ','
  701. local list = {}
  702. for priv, bool in pairs(privs) do
  703. if bool then
  704. list[#list + 1] = priv
  705. end
  706. end
  707. table.sort(list)
  708. return table.concat(list, delim)
  709. end
  710. function core.is_nan(number)
  711. return number ~= number
  712. end
  713. --[[ Helper function for parsing an optionally relative number
  714. of a chat command parameter, using the chat command tilde notation.
  715. Parameters:
  716. * arg: String snippet containing the number; possible values:
  717. * "<number>": return as number
  718. * "~<number>": return relative_to + <number>
  719. * "~": return relative_to
  720. * Anything else will return `nil`
  721. * relative_to: Number to which the `arg` number might be relative to
  722. Returns:
  723. A number or `nil`, depending on `arg.
  724. Examples:
  725. * `core.parse_relative_number("5", 10)` returns 5
  726. * `core.parse_relative_number("~5", 10)` returns 15
  727. * `core.parse_relative_number("~", 10)` returns 10
  728. ]]
  729. function core.parse_relative_number(arg, relative_to)
  730. if not arg then
  731. return nil
  732. elseif arg == "~" then
  733. return relative_to
  734. elseif string.sub(arg, 1, 1) == "~" then
  735. local number = tonumber(string.sub(arg, 2))
  736. if not number then
  737. return nil
  738. end
  739. if core.is_nan(number) or number == math.huge or number == -math.huge then
  740. return nil
  741. end
  742. return relative_to + number
  743. else
  744. local number = tonumber(arg)
  745. if core.is_nan(number) or number == math.huge or number == -math.huge then
  746. return nil
  747. end
  748. return number
  749. end
  750. end
  751. --[[ Helper function to parse coordinates that might be relative
  752. to another position; supports chat command tilde notation.
  753. Intended to be used in chat command parameter parsing.
  754. Parameters:
  755. * x, y, z: Parsed x, y, and z coordinates as strings
  756. * relative_to: Position to which to compare the position
  757. Syntax of x, y and z:
  758. * "<number>": return as number
  759. * "~<number>": return <number> + player position on this axis
  760. * "~": return player position on this axis
  761. Returns: a vector or nil for invalid input or if player does not exist
  762. ]]
  763. function core.parse_coordinates(x, y, z, relative_to)
  764. if not relative_to then
  765. x, y, z = tonumber(x), tonumber(y), tonumber(z)
  766. return x and y and z and { x = x, y = y, z = z }
  767. end
  768. local rx = core.parse_relative_number(x, relative_to.x)
  769. local ry = core.parse_relative_number(y, relative_to.y)
  770. local rz = core.parse_relative_number(z, relative_to.z)
  771. return rx and ry and rz and { x = rx, y = ry, z = rz }
  772. end