misc_helpers.lua 18 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. return math.sqrt(x * x + y * y)
  200. end
  201. --------------------------------------------------------------------------------
  202. function math.sign(x, tolerance)
  203. tolerance = tolerance or 0
  204. if x > tolerance then
  205. return 1
  206. elseif x < -tolerance then
  207. return -1
  208. end
  209. return 0
  210. end
  211. --------------------------------------------------------------------------------
  212. function math.factorial(x)
  213. assert(x % 1 == 0 and x >= 0, "factorial expects a non-negative integer")
  214. if x >= 171 then
  215. -- 171! is greater than the biggest double, no need to calculate
  216. return math.huge
  217. end
  218. local v = 1
  219. for k = 2, x do
  220. v = v * k
  221. end
  222. return v
  223. end
  224. function math.round(x)
  225. if x >= 0 then
  226. return math.floor(x + 0.5)
  227. end
  228. return math.ceil(x - 0.5)
  229. end
  230. function core.formspec_escape(text)
  231. if text ~= nil then
  232. text = string.gsub(text,"\\","\\\\")
  233. text = string.gsub(text,"%]","\\]")
  234. text = string.gsub(text,"%[","\\[")
  235. text = string.gsub(text,";","\\;")
  236. text = string.gsub(text,",","\\,")
  237. end
  238. return text
  239. end
  240. function core.wrap_text(text, max_length, as_table)
  241. local result = {}
  242. local line = {}
  243. if #text <= max_length then
  244. return as_table and {text} or text
  245. end
  246. for word in text:gmatch('%S+') do
  247. local cur_length = #table.concat(line, ' ')
  248. if cur_length > 0 and cur_length + #word + 1 >= max_length then
  249. -- word wouldn't fit on current line, move to next line
  250. table.insert(result, table.concat(line, ' '))
  251. line = {}
  252. end
  253. table.insert(line, word)
  254. end
  255. table.insert(result, table.concat(line, ' '))
  256. return as_table and result or table.concat(result, '\n')
  257. end
  258. --------------------------------------------------------------------------------
  259. if INIT == "game" then
  260. local dirs1 = {9, 18, 7, 12}
  261. local dirs2 = {20, 23, 22, 21}
  262. function core.rotate_and_place(itemstack, placer, pointed_thing,
  263. infinitestacks, orient_flags, prevent_after_place)
  264. orient_flags = orient_flags or {}
  265. local unode = core.get_node_or_nil(pointed_thing.under)
  266. if not unode then
  267. return
  268. end
  269. local undef = core.registered_nodes[unode.name]
  270. local sneaking = placer and placer:get_player_control().sneak
  271. if undef and undef.on_rightclick and not sneaking then
  272. return undef.on_rightclick(pointed_thing.under, unode, placer,
  273. itemstack, pointed_thing)
  274. end
  275. local fdir = placer and core.dir_to_facedir(placer:get_look_dir()) or 0
  276. local above = pointed_thing.above
  277. local under = pointed_thing.under
  278. local iswall = (above.y == under.y)
  279. local isceiling = not iswall and (above.y < under.y)
  280. if undef and undef.buildable_to then
  281. iswall = false
  282. end
  283. if orient_flags.force_floor then
  284. iswall = false
  285. isceiling = false
  286. elseif orient_flags.force_ceiling then
  287. iswall = false
  288. isceiling = true
  289. elseif orient_flags.force_wall then
  290. iswall = true
  291. isceiling = false
  292. elseif orient_flags.invert_wall then
  293. iswall = not iswall
  294. end
  295. local param2 = fdir
  296. if iswall then
  297. param2 = dirs1[fdir + 1]
  298. elseif isceiling then
  299. if orient_flags.force_facedir then
  300. param2 = 20
  301. else
  302. param2 = dirs2[fdir + 1]
  303. end
  304. else -- place right side up
  305. if orient_flags.force_facedir then
  306. param2 = 0
  307. end
  308. end
  309. local old_itemstack = ItemStack(itemstack)
  310. local new_itemstack = core.item_place_node(itemstack, placer,
  311. pointed_thing, param2, prevent_after_place)
  312. return infinitestacks and old_itemstack or new_itemstack
  313. end
  314. --------------------------------------------------------------------------------
  315. --Wrapper for rotate_and_place() to check for sneak and assume Creative mode
  316. --implies infinite stacks when performing a 6d rotation.
  317. --------------------------------------------------------------------------------
  318. core.rotate_node = function(itemstack, placer, pointed_thing)
  319. local name = placer and placer:get_player_name() or ""
  320. local invert_wall = placer and placer:get_player_control().sneak or false
  321. return core.rotate_and_place(itemstack, placer, pointed_thing,
  322. core.is_creative_enabled(name),
  323. {invert_wall = invert_wall}, true)
  324. end
  325. end
  326. --------------------------------------------------------------------------------
  327. function core.explode_table_event(evt)
  328. if evt ~= nil then
  329. local parts = evt:split(":")
  330. if #parts == 3 then
  331. local t = parts[1]:trim()
  332. local r = tonumber(parts[2]:trim())
  333. local c = tonumber(parts[3]:trim())
  334. if type(r) == "number" and type(c) == "number"
  335. and t ~= "INV" then
  336. return {type=t, row=r, column=c}
  337. end
  338. end
  339. end
  340. return {type="INV", row=0, column=0}
  341. end
  342. --------------------------------------------------------------------------------
  343. function core.explode_textlist_event(evt)
  344. if evt ~= nil then
  345. local parts = evt:split(":")
  346. if #parts == 2 then
  347. local t = parts[1]:trim()
  348. local r = tonumber(parts[2]:trim())
  349. if type(r) == "number" and t ~= "INV" then
  350. return {type=t, index=r}
  351. end
  352. end
  353. end
  354. return {type="INV", index=0}
  355. end
  356. --------------------------------------------------------------------------------
  357. function core.explode_scrollbar_event(evt)
  358. local retval = core.explode_textlist_event(evt)
  359. retval.value = retval.index
  360. retval.index = nil
  361. return retval
  362. end
  363. --------------------------------------------------------------------------------
  364. function core.rgba(r, g, b, a)
  365. return a and string.format("#%02X%02X%02X%02X", r, g, b, a) or
  366. string.format("#%02X%02X%02X", r, g, b)
  367. end
  368. --------------------------------------------------------------------------------
  369. function core.pos_to_string(pos, decimal_places)
  370. local x = pos.x
  371. local y = pos.y
  372. local z = pos.z
  373. if decimal_places ~= nil then
  374. x = string.format("%." .. decimal_places .. "f", x)
  375. y = string.format("%." .. decimal_places .. "f", y)
  376. z = string.format("%." .. decimal_places .. "f", z)
  377. end
  378. return "(" .. x .. "," .. y .. "," .. z .. ")"
  379. end
  380. --------------------------------------------------------------------------------
  381. function core.string_to_pos(value)
  382. if value == nil then
  383. return nil
  384. end
  385. local x, y, z = string.match(value, "^([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+)$")
  386. if x and y and z then
  387. x = tonumber(x)
  388. y = tonumber(y)
  389. z = tonumber(z)
  390. return vector.new(x, y, z)
  391. end
  392. x, y, z = string.match(value, "^%( *([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+) *%)$")
  393. if x and y and z then
  394. x = tonumber(x)
  395. y = tonumber(y)
  396. z = tonumber(z)
  397. return vector.new(x, y, z)
  398. end
  399. return nil
  400. end
  401. --------------------------------------------------------------------------------
  402. function core.string_to_area(value)
  403. local p1, p2 = unpack(value:split(") ("))
  404. if p1 == nil or p2 == nil then
  405. return nil
  406. end
  407. p1 = core.string_to_pos(p1 .. ")")
  408. p2 = core.string_to_pos("(" .. p2)
  409. if p1 == nil or p2 == nil then
  410. return nil
  411. end
  412. return p1, p2
  413. end
  414. local function test_string_to_area()
  415. local p1, p2 = core.string_to_area("(10.0, 5, -2) ( 30.2, 4, -12.53)")
  416. assert(p1.x == 10.0 and p1.y == 5 and p1.z == -2)
  417. assert(p2.x == 30.2 and p2.y == 4 and p2.z == -12.53)
  418. p1, p2 = core.string_to_area("(10.0, 5, -2 30.2, 4, -12.53")
  419. assert(p1 == nil and p2 == nil)
  420. p1, p2 = core.string_to_area("(10.0, 5,) -2 fgdf2, 4, -12.53")
  421. assert(p1 == nil and p2 == nil)
  422. end
  423. test_string_to_area()
  424. --------------------------------------------------------------------------------
  425. function table.copy(t, seen)
  426. local n = {}
  427. seen = seen or {}
  428. seen[t] = n
  429. for k, v in pairs(t) do
  430. n[(type(k) == "table" and (seen[k] or table.copy(k, seen))) or k] =
  431. (type(v) == "table" and (seen[v] or table.copy(v, seen))) or v
  432. end
  433. return n
  434. end
  435. function table.insert_all(t, other)
  436. for i=1, #other do
  437. t[#t + 1] = other[i]
  438. end
  439. return t
  440. end
  441. function table.key_value_swap(t)
  442. local ti = {}
  443. for k,v in pairs(t) do
  444. ti[v] = k
  445. end
  446. return ti
  447. end
  448. function table.shuffle(t, from, to, random)
  449. from = from or 1
  450. to = to or #t
  451. random = random or math.random
  452. local n = to - from + 1
  453. while n > 1 do
  454. local r = from + n-1
  455. local l = from + random(0, n-1)
  456. t[l], t[r] = t[r], t[l]
  457. n = n-1
  458. end
  459. end
  460. --------------------------------------------------------------------------------
  461. -- mainmenu only functions
  462. --------------------------------------------------------------------------------
  463. if INIT == "mainmenu" then
  464. function core.get_game(index)
  465. local games = core.get_games()
  466. if index > 0 and index <= #games then
  467. return games[index]
  468. end
  469. return nil
  470. end
  471. end
  472. if core.gettext then -- for client and mainmenu
  473. function fgettext_ne(text, ...)
  474. text = core.gettext(text)
  475. local arg = {n=select('#', ...), ...}
  476. if arg.n >= 1 then
  477. -- Insert positional parameters ($1, $2, ...)
  478. local result = ''
  479. local pos = 1
  480. while pos <= text:len() do
  481. local newpos = text:find('[$]', pos)
  482. if newpos == nil then
  483. result = result .. text:sub(pos)
  484. pos = text:len() + 1
  485. else
  486. local paramindex =
  487. tonumber(text:sub(newpos+1, newpos+1))
  488. result = result .. text:sub(pos, newpos-1)
  489. .. tostring(arg[paramindex])
  490. pos = newpos + 2
  491. end
  492. end
  493. text = result
  494. end
  495. return text
  496. end
  497. function fgettext(text, ...)
  498. return core.formspec_escape(fgettext_ne(text, ...))
  499. end
  500. end
  501. local ESCAPE_CHAR = string.char(0x1b)
  502. function core.get_color_escape_sequence(color)
  503. return ESCAPE_CHAR .. "(c@" .. color .. ")"
  504. end
  505. function core.get_background_escape_sequence(color)
  506. return ESCAPE_CHAR .. "(b@" .. color .. ")"
  507. end
  508. function core.colorize(color, message)
  509. local lines = tostring(message):split("\n", true)
  510. local color_code = core.get_color_escape_sequence(color)
  511. for i, line in ipairs(lines) do
  512. lines[i] = color_code .. line
  513. end
  514. return table.concat(lines, "\n") .. core.get_color_escape_sequence("#ffffff")
  515. end
  516. function core.strip_foreground_colors(str)
  517. return (str:gsub(ESCAPE_CHAR .. "%(c@[^)]+%)", ""))
  518. end
  519. function core.strip_background_colors(str)
  520. return (str:gsub(ESCAPE_CHAR .. "%(b@[^)]+%)", ""))
  521. end
  522. function core.strip_colors(str)
  523. return (str:gsub(ESCAPE_CHAR .. "%([bc]@[^)]+%)", ""))
  524. end
  525. function core.translate(textdomain, str, ...)
  526. local start_seq
  527. if textdomain == "" then
  528. start_seq = ESCAPE_CHAR .. "T"
  529. else
  530. start_seq = ESCAPE_CHAR .. "(T@" .. textdomain .. ")"
  531. end
  532. local arg = {n=select('#', ...), ...}
  533. local end_seq = ESCAPE_CHAR .. "E"
  534. local arg_index = 1
  535. local translated = str:gsub("@(.)", function(matched)
  536. local c = string.byte(matched)
  537. if string.byte("1") <= c and c <= string.byte("9") then
  538. local a = c - string.byte("0")
  539. if a ~= arg_index then
  540. error("Escape sequences in string given to core.translate " ..
  541. "are not in the correct order: got @" .. matched ..
  542. "but expected @" .. tostring(arg_index))
  543. end
  544. if a > arg.n then
  545. error("Not enough arguments provided to core.translate")
  546. end
  547. arg_index = arg_index + 1
  548. return ESCAPE_CHAR .. "F" .. arg[a] .. ESCAPE_CHAR .. "E"
  549. elseif matched == "n" then
  550. return "\n"
  551. else
  552. return matched
  553. end
  554. end)
  555. if arg_index < arg.n + 1 then
  556. error("Too many arguments provided to core.translate")
  557. end
  558. return start_seq .. translated .. end_seq
  559. end
  560. function core.get_translator(textdomain)
  561. return function(str, ...) return core.translate(textdomain or "", str, ...) end
  562. end
  563. --------------------------------------------------------------------------------
  564. -- Returns the exact coordinate of a pointed surface
  565. --------------------------------------------------------------------------------
  566. function core.pointed_thing_to_face_pos(placer, pointed_thing)
  567. -- Avoid crash in some situations when player is inside a node, causing
  568. -- 'above' to equal 'under'.
  569. if vector.equals(pointed_thing.above, pointed_thing.under) then
  570. return pointed_thing.under
  571. end
  572. local eye_height = placer:get_properties().eye_height
  573. local eye_offset_first = placer:get_eye_offset()
  574. local node_pos = pointed_thing.under
  575. local camera_pos = placer:get_pos()
  576. local pos_off = vector.multiply(
  577. vector.subtract(pointed_thing.above, node_pos), 0.5)
  578. local look_dir = placer:get_look_dir()
  579. local offset, nc
  580. local oc = {}
  581. for c, v in pairs(pos_off) do
  582. if nc or v == 0 then
  583. oc[#oc + 1] = c
  584. else
  585. offset = v
  586. nc = c
  587. end
  588. end
  589. local fine_pos = {[nc] = node_pos[nc] + offset}
  590. camera_pos.y = camera_pos.y + eye_height + eye_offset_first.y / 10
  591. local f = (node_pos[nc] + offset - camera_pos[nc]) / look_dir[nc]
  592. for i = 1, #oc do
  593. fine_pos[oc[i]] = camera_pos[oc[i]] + look_dir[oc[i]] * f
  594. end
  595. return fine_pos
  596. end
  597. function core.string_to_privs(str, delim)
  598. assert(type(str) == "string")
  599. delim = delim or ','
  600. local privs = {}
  601. for _, priv in pairs(string.split(str, delim)) do
  602. privs[priv:trim()] = true
  603. end
  604. return privs
  605. end
  606. function core.privs_to_string(privs, delim)
  607. assert(type(privs) == "table")
  608. delim = delim or ','
  609. local list = {}
  610. for priv, bool in pairs(privs) do
  611. if bool then
  612. list[#list + 1] = priv
  613. end
  614. end
  615. return table.concat(list, delim)
  616. end
  617. function core.is_nan(number)
  618. return number ~= number
  619. end