utils.lua 26.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
-- TE4 - T-Engine 4
-- Copyright (C) 2009, 2010 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program.  If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org

local lpeg = require "lpeg"

function lpeg.anywhere (p)
	return lpeg.P{ p + 1 * lpeg.V(1) }
end

function table.clone(tbl, deep)
	local n = {}
	for k, e in pairs(tbl) do
		-- Deep copy subtables, but not objects!
		if deep and type(e) == "table" and not e.__CLASSNAME then
			n[k] = table.clone(e, true)
		else
			n[k] = e
		end
	end
	return n
end

function table.merge(dst, src, deep)
	for k, e in pairs(src) do
		if deep and dst[k] and type(e) == "table" and type(dst[k]) == "table" and not e.__CLASSNAME then
			table.merge(dst[k], e, true)
		elseif deep and not dst[k] and type(e) == "table" and not e.__CLASSNAME then
			dst[k] = table.clone(e, true)
		else
			dst[k] = e
		end
	end
end

function table.mergeAdd(dst, src, deep)
	for k, e in pairs(src) do
		if deep and dst[k] and type(e) == "table" and type(dst[k]) == "table" and not e.__CLASSNAME then
			table.mergeAdd(dst[k], e, true)
		elseif deep and not dst[k] and type(e) == "table" and not e.__CLASSNAME then
			dst[k] = table.clone(e, true)
		elseif dst[k] and type(e) == "number" then
			dst[k] = dst[k] + e
		else
			dst[k] = e
		end
	end
end

--- Merges additively the named fields and append the array part
-- Yes this is weird and you'll probably not need it, but the engine does :)
function table.mergeAddAppendArray(dst, src, deep)
	-- Append the array part
	for i = 1, #src do
		local b = src[i]
		if deep and type(b) == "table" and not b.__CLASSNAME then b = table.clone(b, true)
		elseif deep and type(b) == "table" and b.__CLASSNAME then b = b:clone()
		end
		table.insert(dst, b)
	end

	-- Copy the table part
	for k, e in pairs(src) do
		if type(k) ~= "number" then
			if deep and dst[k] and type(e) == "table" and type(dst[k]) == "table" and not e.__CLASSNAME then
				-- WARNING we do not recurse on ourself but instead of the simple mergeAdd, we do not want to do the array stuff for subtables
				-- yes I warned you this is weird
				table.mergeAdd(dst[k], e, true)
			elseif deep and not dst[k] and type(e) == "table" and not e.__CLASSNAME then
				dst[k] = table.clone(e, true)
			elseif dst[k] and type(e) == "number" then
				dst[k] = dst[k] + e
			else
				dst[k] = e
			end
		end
	end
end

function table.append(dst, src)
	for i = 1, #src do dst[#dst+1] = src[i] end
end

function table.reverse(t)
	local tt = {}
	for i, e in ipairs(t) do tt[e] = i end
	return tt
end

function table.listify(t)
	local tt = {}
	for k, e in pairs(t) do tt[#tt+1] = {k, e} end
	return tt
end

function table.keys(t)
	local tt = {}
	for k, e in pairs(t) do tt[#tt+1] = k end
	return tt
end

function table.update(dst, src, deep)
	for k, e in pairs(src) do
		if deep and dst[k] and type(e) == "table" and type(dst[k]) == "table" and not e.__CLASSNAME then
			table.update(dst[k], e, true)
		elseif deep and not dst[k] and type(e) == "table" and not e.__CLASSNAME then
			dst[k] = table.clone(e, true)
		elseif not dst[k] and type(dst[k]) ~= "boolean" then
			dst[k] = e
		end
	end
end

function string.ordinal(number)
	local suffix = "th"
	number = tonumber(number)
	local base = number % 10
	if base == 1 then
		suffix = "st"
	elseif base == 2 then
		suffix = "nd"
	elseif base == 3 then
		suffix = "rd"
	end
	return number..suffix
end

function string.capitalize(str)
	if #str > 1 then
		return string.upper(str:sub(1, 1))..str:sub(2)
	elseif #str == 1 then
		return str:upper()
	else
		return str
	end
end

function string.bookCapitalize(str)
	local words = str:split(' ')

	for i = 1, #words do
		local word = words[i]

		-- Don't capitalize certain words unless they are at the begining
		-- of the string.
		if i == 1 or (word ~= "of" and word ~= "the" and word ~= "and" and word ~= "a" and word ~= "an")
		then
			words[i] = word:gsub("^(.)",
							function(x)
								return x:upper()
							end)
		end
	end

	return table.concat(words, " ")
end

function string.lpegSub(s, patt, repl)
	patt = lpeg.P(patt)
	patt = lpeg.Cs((patt / repl + 1)^0)
	return lpeg.match(patt, s)
end

-- Those matching patterns are used both by splitLine and drawColorString*
local Puid = "UID:" * lpeg.R"09"^1 * ":" * lpeg.R"09"
local Puid_cap = "UID:" * lpeg.C(lpeg.R"09"^1) * ":" * lpeg.C(lpeg.R"09")
local Pcolorname = (lpeg.R"AZ" + "_")^3
local Pcode = (lpeg.R"af" + lpeg.R"09" + lpeg.R"AF")
local Pcolorcode = Pcode * Pcode
local Pfontstyle = "{" * (lpeg.P"bold" + lpeg.P"italic" + lpeg.P"underline" + lpeg.P"normal") * "}"
local Pfontstyle_cap = "{" * lpeg.C(lpeg.P"bold" + lpeg.P"italic" + lpeg.P"underline" + lpeg.P"normal") * "}"
local Pcolorcodefull = Pcolorcode * Pcolorcode * Pcolorcode

function string.removeColorCodes(str)
	return str:lpegSub("#" * (Puid + Pcolorcodefull + Pcolorname + Pfontstyle) * "#", "")
end

function string.splitLine(str, max_width, font)
	local space_w = font:size(" ")
	local lines = {}
	local cur_line, cur_size = "", 0
	local v
	local ls = str:split(lpeg.S"\n ")
	for i = 1, #ls do
		local v = ls[i]
		local shortv = v:lpegSub("#" * (Puid + Pcolorcodefull + Pcolorname + Pfontstyle) * "#", "")
		local w, h = font:size(shortv)

		if cur_size + space_w + w < max_width then
			cur_line = cur_line..(cur_size==0 and "" or " ")..v
			cur_size = cur_size + (cur_size==0 and 0 or space_w) + w
		else
			lines[#lines+1] = cur_line
			cur_line = v
			cur_size = w
		end
	end
	if cur_size > 0 then lines[#lines+1] = cur_line end
	return lines
end

function string.splitLines(str, max_width, font)
	local lines = {}
	local ls = str:split(lpeg.S"\n")
	local v
	for i = 1, #ls do
		v = ls[i]
		local ls = v:splitLine(max_width, font)
		if #ls > 0 then
			for i, l in ipairs(ls) do
				lines[#lines+1] = l
			end
		else
			lines[#lines+1] = ""
		end
	end
	return lines
end

-- Split a string by the given character(s)
function string.split(str, char, keep_separator)
	char = lpeg.P(char)
	if keep_separator then char = lpeg.C(char) end
	local elem = lpeg.C((1 - char)^0)
	local p = lpeg.Ct(elem * (char * elem)^0)
	return lpeg.match(p, str)
end


local hex_to_dec = {
	["0"] = 0,
	["1"] = 1,
	["2"] = 2,
	["3"] = 3,
	["4"] = 4,
	["5"] = 5,
	["6"] = 6,
	["7"] = 7,
	["8"] = 8,
	["9"] = 9,
	["a"] = 10,
	["b"] = 11,
	["c"] = 12,
	["d"] = 13,
	["e"] = 14,
	["f"] = 15,
}
local hexcache = {}
function string.parseHex(str)
	if hexcache[str] then return hexcache[str] end
	local res = 0
	local power = 1
	str = str:lower()
	for i = 1, #str do
		res = res + power * (hex_to_dec[str:sub(#str-i+1,#str-i+1)] or 0)
		power = power * 16
	end
	hexcache[str] = res
	return res
end

local tmps = core.display.newSurface(1, 1)
getmetatable(tmps).__index.drawColorString = function(s, font, str, x, y, r, g, b, alpha_from_texture, limit_w)
	local list = str:split("#" * (Puid + Pcolorcodefull + Pcolorname + Pfontstyle) * "#", true)
	r = r or 255
	g = g or 255
	b = b or 255
	limit_w = limit_w or 99999999
	local oldr, oldg, oldb = r, g, b
	local max_h = 0
	local sw = 0
	local bx, by = x, y
	for i, v in ipairs(list) do
		local nr, ng, nb = lpeg.match("#" * lpeg.C(Pcolorcode) * lpeg.C(Pcolorcode) * lpeg.C(Pcolorcode) * "#", v)
		local col = lpeg.match("#" * lpeg.C(Pcolorname) * "#", v)
		local uid, mo = lpeg.match("#" * Puid_cap * "#", v)
		local fontstyle = lpeg.match("#" * Pfontstyle_cap * "#", v)
		if nr and ng and nb then
			oldr, oldg, oldb = r, g, b
			r, g, b = nr:parseHex(), ng:parseHex(), nb:parseHex()
		elseif col then
			if col == "LAST" then
				r, g, b = oldr, oldg, oldb
			else
				oldr, oldg, oldb = r, g, b
				r, g, b = colors[col].r, colors[col].g, colors[col].b
			end
		elseif uid and mo and game.level then
			uid = tonumber(uid)
			mo = tonumber(mo)
			local e = __uids[uid]
			if e then
				local surf = e:getEntityFinalSurface(game.level.map.tiles, font:lineSkip(), font:lineSkip())
				if surf then
					local w, h = surf:getSize()
					if sw + w > limit_w then break end
					s:merge(surf, x, y)
					if h > max_h then max_h = h end
					x = x + (w or 0)
					sw = sw + (w or 0)
				end
			end
		elseif fontstyle then
			font:setStyle(fontstyle)
		else
			local w, h = font:size(v)
			local stop = false
			while sw + w > limit_w do
				v = v:sub(1, #v - 1)
				if #v == 0 then break end
				w, h = font:size(v)
				stop = true
			end
			if h > max_h then max_h = h end
			s:drawStringBlended(font, v, x, y, r, g, b, alpha_from_texture)
			x = x + w
			sw = sw + w
			if stop then break end
		end
	end
	return r, g, b, sw, max_h, bx, by
end

getmetatable(tmps).__index.drawColorStringCentered = function(s, font, str, dx, dy, dw, dh, r, g, b, alpha_from_texture, limit_w)
	local w, h = font:size(str)
	local x, y = dx + (dw - w) / 2, dy + (dh - h) / 2
	s:drawColorString(font, str, x, y, r, g, b, alpha_from_texture, limit_w)
end


getmetatable(tmps).__index.drawColorStringBlended = function(s, font, str, x, y, r, g, b, alpha_from_texture, limit_w)
	local list = str:split("#" * (Puid + Pcolorcodefull + Pcolorname + Pfontstyle) * "#", true)
	r = r or 255
	g = g or 255
	b = b or 255
	limit_w = limit_w or 99999999
	local oldr, oldg, oldb = r, g, b
	local max_h = 0
	local sw = 0
	local bx, by = x, y
	for i, v in ipairs(list) do
		local nr, ng, nb = lpeg.match("#" * lpeg.C(Pcolorcode) * lpeg.C(Pcolorcode) * lpeg.C(Pcolorcode) * "#", v)
		local col = lpeg.match("#" * lpeg.C(Pcolorname) * "#", v)
		local uid, mo = lpeg.match("#" * Puid_cap * "#", v)
		local fontstyle = lpeg.match("#" * Pfontstyle_cap * "#", v)
		if nr and ng and nb then
			oldr, oldg, oldb = r, g, b
			r, g, b = nr:parseHex(), ng:parseHex(), nb:parseHex()
		elseif col then
			if col == "LAST" then
				r, g, b = oldr, oldg, oldb
			else
				oldr, oldg, oldb = r, g, b
				r, g, b = colors[col].r, colors[col].g, colors[col].b
			end
		elseif uid and mo and game.level then
			uid = tonumber(uid)
			mo = tonumber(mo)
			local e = __uids[uid]
			if e then
				local surf = e:getEntityFinalSurface(game.level.map.tiles, font:lineSkip(), font:lineSkip())
				if surf then
					local w, h = surf:getSize()
					if sw + (w or 0) > limit_w then break end
					s:merge(surf, x, y)
					if h > max_h then max_h = h end
					x = x + (w or 0)
					sw = sw + (w or 0)
				end
			end
		elseif fontstyle then
			font:setStyle(fontstyle)
		else
			local w, h = font:size(v)
			local stop = false
			while sw + w > limit_w do
				v = v:sub(1, #v - 1)
				if #v == 0 then break end
				w, h = font:size(v)
				stop = true
			end
			if h > max_h then max_h = h end
			s:drawStringBlended(font, v, x, y, r, g, b, alpha_from_texture)
			x = x + w
			sw = sw + w
			if stop then break end
		end
	end
	return r, g, b, sw, max_h, bx, by
end

getmetatable(tmps).__index.drawColorStringBlendedCentered = function(s, font, str, dx, dy, dw, dh, r, g, b, alpha_from_texture, limit_w)
	local w, h = font:size(str)
	local x, y = dx + (dw - w) / 2, dy + (dh - h) / 2
	s:drawColorStringBlended(font, str, x, y, r, g, b, alpha_from_texture, limit_w)
end

local font_cache = {}
local oldNewFont = core.display.newFont
core.display.newFont = function(font, size)
	if font_cache[font] and font_cache[font][size] then print("Using cached font", font, size) return font_cache[font][size] end
	font_cache[font] = font_cache[font] or {}
	font_cache[font][size] = oldNewFont(font, size)
	return font_cache[font][size]
end

local tmps = core.display.newFont("/data/font/Vera.ttf", 12)
local word_size_cache = {}
local fontoldsize = getmetatable(tmps).__index.size
getmetatable(tmps).__index.size = function(font, str)
	local list = str:split("#" * (Puid + Pcolorcodefull + Pcolorname + Pfontstyle) * "#", true)
	local mw, mh = 0, 0
	local fstyle = font:getStyle()
	word_size_cache[font] = word_size_cache[font] or {}
	word_size_cache[font][fstyle] = word_size_cache[font][fstyle] or {}
	local v
	for i = 1, #list do
		v = list[i]
		local nr, ng, nb = lpeg.match("#" * lpeg.C(Pcolorcode) * lpeg.C(Pcolorcode) * lpeg.C(Pcolorcode) * "#", v)
		local col = lpeg.match("#" * lpeg.C(Pcolorname) * "#", v)
		local uid, mo = lpeg.match("#" * Puid_cap * "#", v)
		local fontstyle = lpeg.match("#" * Pfontstyle_cap * "#", v)
		if nr and ng and nb then
			-- Ignore
		elseif col then
			-- Ignore
		elseif uid and mo and game.level then
			-- Ignore
		elseif fontstyle then
			font:setStyle(fontstyle)
			fstyle = fontstyle
			word_size_cache[font][fstyle] = word_size_cache[font][fstyle] or {}
		else
			local w, h
			if word_size_cache[font][fstyle][v] then
				w, h = word_size_cache[font][fstyle][v][1], word_size_cache[font][fstyle][v][2]
			else
				w, h = fontoldsize(font, v)
				word_size_cache[font][fstyle][v] = {w, h}
			end
			if h > mh then mh = h end
			mw = mw + w
		end
	end
	return mw, mh
end

tstring = {}
tstring.is_tstring = true

function tstring:add(...)
	local v = {...}
	for i = 1, #v do
		self[#self+1] = v[i]
	end
	return self
end

function tstring:merge(v)
	for i = 1, #v do
		self[#self+1] = v[i]
	end
	return self
end

function tstring:countLines()
	local nb = 1
	local v
	for i = 1, #self do
		v = self[i]
		if type(v) == "boolean" then nb = nb + 1 end
	end
	return nb
end

function tstring.from(str)
	if type(str) ~= "table" then
		return tstring{str}
	else
		return str
	end
end

--- Parse a string and return a tstring
function string.toTString(str)
	local tstr = tstring{}
	local list = str:split(("#" * (Puid + Pcolorcodefull + Pcolorname + Pfontstyle) * "#") + lpeg.P"\n", true)
	for i = 1, #list do
		v = list[i]
		local nr, ng, nb = lpeg.match("#" * lpeg.C(Pcolorcode) * lpeg.C(Pcolorcode) * lpeg.C(Pcolorcode) * "#", v)
		local col = lpeg.match("#" * lpeg.C(Pcolorname) * "#", v)
		local uid, mo = lpeg.match("#" * Puid_cap * "#", v)
		local fontstyle = lpeg.match("#" * Pfontstyle_cap * "#", v)
		if nr and ng and nb then
			tstr:add({"color", nr:parseHex(), ng:parseHex(), nb:parseHex()})
		elseif col then
			tstr:add({"color", col})
		elseif uid and mo then
			tstr:add({"uid", tonumber(uid)})
		elseif fontstyle then
			tstr:add({"font", fontstyle})
		elseif v == "\n" then
			tstr:add(true)
		else
			tstr:add(v)
		end
	end
	return tstr
end
function string:toString() return self end

--- Tablestrings degrade "peacefully" into normal formated strings
function tstring:toString()
	local ret = {}
	local v
	for i = 1, #self do
		v = self[i]
		if type(v) == "boolean" then ret[#ret+1] = "\n"
		elseif type(v) == "string" then ret[#ret+1] = v
		elseif type(v) == "table" then
			if v[1] == "color" and v[2] == "LAST" then ret[#ret+1] = "#LAST#"
			elseif v[1] == "color" and not v[3] then ret[#ret+1] = "#"..v[2].."#"
			elseif v[1] == "color" then ret[#ret+1] = ("#%02x%02x%02x#"):format(v[2], v[3], v[4]):upper()
			elseif v[1] == "font" then ret[#ret+1] = "#{"..v[2].."}#"
			elseif v[1] == "uid" then ret[#ret+1] = "#UID:"..v[2]..":0#"
			end
		end
	end
	return table.concat(ret)
end
function tstring:toTString() return self end

--- Tablestrings can not be formated, this just returns self
function tstring:format() return self end

function tstring:splitLines(max_width, font)
	local space_w = font:size(" ")
	local ret = tstring{}
	local cur_size =0
	local v, tv
	for i = 1, #self do
		v = self[i]
		tv = type(v)
		if tv == "string" then
			local ls = v:split(lpeg.S"\n ", true)
			for i = 1, #ls do
				local vv = ls[i]
				if vv == "\n" then
					ret[#ret+1] = true
					cur_size = 0
				else
					local w, h = fontoldsize(font, vv)
					if cur_size + w < max_width then
						cur_size = cur_size + w
						ret[#ret+1] = vv
					else
						ret[#ret+1] = true
						ret[#ret+1] = vv
						cur_size = w
					end
				end
			end
		elseif tv == "table" and v[1] == "font" then
			font:setStyle(v[2])
			ret[#ret+1] = v
		elseif tv == "table" and v[1] == "uid" then
			local e = __uids[v[2]]
			if e and game.level then
				local surf = e:getEntityFinalSurface(game.level.map.tiles, font:lineSkip(), font:lineSkip())
				if surf then
					local w, h = surf:getSize()
					if cur_size + w < max_width then
						cur_size = cur_size + w
						ret[#ret+1] = vv
					else
						ret[#ret+1] = true
						ret[#ret+1] = vv
						cur_size = w
					end
				end
			end
		elseif tv == "boolean" then
			cur_size = 0
			ret[#ret+1] = v
		else
			ret[#ret+1] = v
		end
	end
	return ret
end

function tstring:makeLineTextures(max_width, font)
	local list = self:splitLines(max_width, font)
	local fh = font:lineSkip()
	local s = core.display.newSurface(max_width, fh)
	s:erase(0, 0, 0, 0)
	local texs = {}
	local w = 0
	local r, g, b = 255, 255, 255
	local oldr, oldg, oldb = 255, 255, 255
	local v, tv
	for i = 1, #list do
		v = list[i]
		tv = type(v)
		if tv == "string" then
			s:drawStringBlended(font, v, w, 0, r, g, b, true)
			w = w + fontoldsize(font, v)
		elseif tv == "boolean" then
			w = 0
			local dat = {}
			dat._tex, dat._tex_w, dat._tex_h = s:glTexture()
			texs[#texs+1] = dat
			s:erase(0, 0, 0, 0)
		else
			if v[1] == "color" and v[2] == "LAST" then
				r, g, b = oldr, oldg, oldb
			elseif v[1] == "color" and not v[3] then
				oldr, oldg, oldb = r, g, b
				r, g, b = unpack(colors.simple(colors[v[2]] or {255,255,255}))
			elseif v[1] == "color" then
				oldr, oldg, oldb = r, g, b
				r, g, b = v[2], v[3], v[4]
			elseif v[1] == "font" then
				font:setStyle(v[2])
			elseif v[1] == "uid" then
				local e = __uids[v[2]]
				if e then
					local surf = e:getEntityFinalSurface(game.level.map.tiles, font:lineSkip(), font:lineSkip())
					if surf then
						local sw = surf:getSize()
						w = w + sw
					end
				end
			end
		end
	end

	-- Last line
	local dat = {}
	dat._tex, dat._tex_w, dat._tex_h = s:glTexture()
	texs[#texs+1] = dat

	return texs
end

function tstring:drawOnSurface(s, max_width, max_lines, font, x, y, r, g, b)
	local list = self:splitLines(max_width, font)
	max_lines = util.bound(max_lines or #list, 1, #list)
	local fh = font:lineSkip()
	local w, h = 0, 0
	r, g, b = r or 255, g or 255, b or 255
	local oldr, oldg, oldb = r, g, b
	local v, tv
	for i = 1, #list do
		v = list[i]
		tv = type(v)
		if tv == "string" then
			s:drawStringBlended(font, v, x + w, y + h, r, g, b, true)
			w = w + fontoldsize(font, v)
		elseif tv == "boolean" then
--			w = 0
--			h = h + fh
			max_lines = max_lines - 1
			if max_lines <= 0 then break end
		else
			if v[1] == "color" and v[2] == "LAST" then
				r, g, b = oldr, oldg, oldb
			elseif v[1] == "color" and not v[3] then
				oldr, oldg, oldb = r, g, b
				r, g, b = unpack(colors.simple(colors[v[2]] or {255,255,255}))
			elseif v[1] == "color" then
				oldr, oldg, oldb = r, g, b
				r, g, b = v[2], v[3], v[4]
			elseif v[1] == "font" then
				font:setStyle(v[2])
			end
		end
	end
end

-- Make tstring into an object
local tsmeta = {__index=tstring, __tostring = tstring.toString}
setmetatable(tstring, {
	__call = function(self, t)
		setmetatable(t, tsmeta)
		return t
	end,
})


dir_to_angle = {
	[1] = 225,
	[2] = 270,
	[3] = 315,
	[4] = 180,
	[5] = 0,
	[6] = 0,
	[7] = 135,
	[8] = 90,
	[9] = 45,
}
dir_to_coord = {
	[1] = {-1, 1},
	[2] = { 0, 1},
	[3] = { 1, 1},
	[4] = {-1, 0},
	[5] = { 0, 0},
	[6] = { 1, 0},
	[7] = {-1,-1},
	[8] = { 0,-1},
	[9] = { 1,-1},
}
coord_to_dir = {
	[-1] = {
		[-1] = 7,
		[ 0] = 4,
		[ 1] = 1,
	},
	[ 0] = {
		[-1] = 8,
		[ 0] = 5,
		[ 1] = 2,
	},
	[ 1] = {
		[-1] = 9,
		[ 0] = 6,
		[ 1] = 3,
	},
}

dir_sides =
{
	[1] = {left=2, right=4},
	[2] = {left=3, right=1},
	[3] = {left=6, right=2},
	[4] = {left=1, right=7},
	[6] = {left=9, right=3},
	[7] = {left=4, right=8},
	[8] = {left=7, right=9},
	[9] = {left=8, right=6},
}

util = {}

function util.getDir(x1, y1, x2, y2)
	local xd, yd = x1 - x2, y1 - y2
	if xd ~= 0 then xd = xd / math.abs(xd) end
	if yd ~= 0 then yd = yd / math.abs(yd) end
	return coord_to_dir[xd][yd], xd, yd
end

function util.coordAddDir(x, y, dir)
	return x + dir_to_coord[dir][1], y + dir_to_coord[dir][2]
end

function util.boundWrap(i, min, max)
	if i < min then i = max
	elseif i > max then i = min end
	return i
end
function util.bound(i, min, max)
	if i < min then i = min
	elseif i > max then i = max end
	return i
end
function util.scroll(sel, scroll, max)
	if sel > scroll + max - 1 then scroll = sel - max + 1 end
	if sel < scroll then scroll = sel end
	return scroll
end

function util.getval(val, ...)
	if type(val) == "function" then return val(...)
	elseif type(val) == "table" then return val[rng.range(1, #val)]
	else return val
	end
end

function core.fov.circle_grids(x, y, radius, block)
	if radius == 0 then return {[x]={[y]=true}} end
	local grids = {}
	core.fov.calc_circle(x, y, radius, function(_, lx, ly)
		if not grids[lx] then grids[lx] = {} end
		grids[lx][ly] = true

		if block and game.level.map:checkEntity(lx, ly, engine.Map.TERRAIN, "block_move") then return true end
	end, function()end, nil)

	-- point of origin
	if not grids[x] then grids[x] = {} end
	grids[x][y] = true

	return grids
end

function core.fov.beam_grids(x, y, radius, dir, angle, block)
	if radius == 0 then return {[x]={[y]=true}} end
	local grids = {}
	core.fov.calc_beam(x, y, radius, dir, angle, function(_, lx, ly)
		if not grids[lx] then grids[lx] = {} end
		grids[lx][ly] = true

		if block and game.level.map:checkEntity(lx, ly, engine.Map.TERRAIN, "block_move") then return true end
	end, function()end, nil)

	-- point of origin
	if not grids[x] then grids[x] = {} end
	grids[x][y] = true

	return grids
end

--- Finds free grids around coords in a radius.
-- This will return a random grid, the closest possible to the epicenter
-- @param sx the epicenter coordinates
-- @param sy the epicenter coordinates
-- @param radius the radius in which to search
-- @param block true if we only consider line of sight
-- @param what a table which can have the fields Map.ACTOR, Map.OBJECT, ..., set to true. If so it will only return grids that are free of this kind of entities.
function util.findFreeGrid(sx, sy, radius, block, what)
	what = what or {}
	local grids = core.fov.circle_grids(sx, sy, radius, block)
	local gs = {}
	for x, yy in pairs(grids) do for y, _ in pairs(yy) do
		local ok = true
		if not game.level.map:isBound(x, y) then ok = false end
		for w, _ in pairs(what) do
--			print("findFreeGrid test", x, y, w, ":=>", game.level.map(x, y, w))
			if game.level.map(x, y, w) then ok = false end
		end
		if game.level.map:checkEntity(x, y, game.level.map.TERRAIN, "block_move") then ok = false end
--		print("findFreeGrid", x, y, "from", sx,sy,"=>", ok)
		if ok then
			gs[#gs+1] = {x, y, math.floor(core.fov.distance(sx, sy, x, y)), rng.range(1, 1000)}
		end
	end end

	if #gs == 0 then return nil end

	table.sort(gs, function(a, b)
		if a[3] == b[3] then
			return a[4] < b[4]
		else
			return a[3] < b[3]
		end
	end)

	print("findFreeGrid using", gs[1][1], gs[1][2])
	return gs[1][1], gs[1][2]
end

function util.showMainMenu(no_reboot, reboot_engine, reboot_engine_version, reboot_module, reboot_name, reboot_new, reboot_einfo)
	-- Turn based by default
	core.game.setRealtime(0)

	-- Save any remaining files
	savefile_pipe:forceWait()

	if game and type(game) == "table" and game.__session_time_played_start then
		profile.generic.modules_played = profile.generic.modules_played or {}
		profile.generic.modules_played[game.__mod_info.short_name] = (profile.generic.modules_played[game.__mod_info.short_name] or 0) + (os.time() - game.__session_time_played_start)
		profile:saveGenericProfile("modules_played", profile.generic.modules_played)
	end

	-- Join threads
	if game and type(game) == "table" then game:joinThreads(30) end

	if no_reboot then
		local Module = require("engine.Module")
		local ms = Module:listModules()
		local mod = ms[__load_module]
		Module:instanciate(mod, __player_name, __player_new, true)
	else
		-- Tell the C engine to discard the current lua state and make a new one
		print("[MAIN] rebooting lua state: ", reboot_engine, reboot_engine_version, reboot_module, reboot_name, reboot_new)
		core.game.reboot(reboot_engine or "te4", reboot_engine_version or "LATEST", reboot_module or "boot", reboot_name or "player", reboot_new, reboot_einfo or "")
	end
end

function rng.mbonus(max, level, max_level)
	if level > max_level - 1 then level = max_level - 1 end

	local bonus = (max * level) / max_level
	local extra = (max * level) % max_level
	if rng.range(0, max_level - 1) < extra then bonus = bonus + 1 end

	local stand = max / 4
	extra = max % 4
	if rng.range(0, 3) < extra then stand = stand + 1 end

	local val = rng.normal(bonus, stand)
	if val < 0 then val = 0 end
	if val > max then val = max end

	return val
end

function rng.table(t)
	local id = rng.range(1, #t)
	return t[id], id
end

function rng.tableRemove(t)
	local id = rng.range(1, #t)
	return table.remove(t, id)
end

function rng.tableIndex(t, ignore)
	local rt = {}
	if not ignore then ignore = {} end
	for k, e in pairs(t) do if not ignore[k] then rt[#rt+1] = k end end
	return rng.table(rt)
end

function util.factorial(n)
	if n == 0 then
		return 1
	else
		return n * util.factorial(n - 1)
	end
end

function rng.poissonProcess(k, turn_scale, rate)
	return math.exp(-rate*turn_scale) * ((rate*turn_scale) ^ k)/ util.factorial(k)
end

function util.show_backtrace()
	local level = 2

	print("backtrace:")
	while true do
		local stacktrace = debug.getinfo(level, "nlS")
		if stacktrace == nil then break end
		print(("    function: %s (%s) at %s:%d"):format(stacktrace.name or "???", stacktrace.what, stacktrace.source or stacktrace.short_src or "???", stacktrace.currentline))
		level = level + 1
	end
end

function util.uuid()
	local x = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}
	local y = {'8', '9', 'a', 'b'}
	local tpl = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx"
	local uuid = tpl:gsub("[xy]", function(c) if c=='y' then return rng.table(y) else return rng.table(x) end end)
	return uuid
end

function util.browserOpenUrl(url)
	local tries = {
		"rundll32 url.dll,FileProtocolHandler %s",  -- Windows
		"open %s",  -- OSX
		"xdg-open %s",  -- Linux - portable way
		"gnome-open %s",  -- Linux - Gnome
		"kde-open %s",  -- Linux - Kde
		"firefox %s",  -- Linux - try to find something
		"mozilla-firefox %s",  -- Linux - try to find something
	}
	while #tries > 0 do
		local urlbase = table.remove(tries, 1)
		urlbase = urlbase:format(url)
		print("Trying to run URL with command: ", urlbase)
		if os.execute(urlbase) == 0 then return true end
	end
	return false
end

function __dump_fct(f)
	return string.format("%q", string.dump(f))
end