ActorTalents.lua 43.6 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 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
-- TE4 - T-Engine 4
-- Copyright (C) 2009 - 2019 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

require "engine.class"

--- Handles actors stats
-- @classmod engine.generator.interface.ActorTalents
module(..., package.seeall, class.make)

_M.talents_def = {}
_M.talents_types_def = {}

--- Defines actor talents
-- Static!
function _M:loadDefinition(file, env)
	env = env or setmetatable({
		DamageType = require("engine.DamageType"),
		Particles = require("engine.Particles"),
		Talents = self,
		Map = require("engine.Map"),
		MapEffect = require("engine.MapEffect"),
		newTalent = function(t) self:newTalent(t) end,
		newTalentType = function(t) self:newTalentType(t) end,
		load = function(f) self:loadDefinition(f, env) end
	}, {__index=getfenv(2)})
	local f, err = util.loadfilemods(file, env)
	if not f and err then error(err) end
	f()
end

--- Defines one talent type(group)
-- Static!
function _M:newTalentType(t)
	t.__ATOMIC = true
	assert(t.name, "no talent type name")
	assert(t.type, "no talent type type")
	t.description = t.description or ""
	t.category = t.category or t.type:gsub("/.*", "")
	t.points = t.points or 1
	-- I18N
	t.name = _t(t.name)
	t.talents = {}
	table.insert(self.talents_types_def, t)
	self.talents_types_def[t.type] = self.talents_types_def[t.type] or t
end

--- Defines one talent
-- Static!
function _M:newTalent(t)
	t.__ATOMIC = true
	assert(t.name, "no talent name")
	assert(t.type, "no or unknown talent type")
	if type(t.type) == "string" then t.type = {t.type, 1} end
	if not t.type[2] then t.type[2] = 1 end
	t.short_name = t.short_name or t.name
	t.short_name = t.short_name:upper():gsub("[ ']", "_")
	t.mode = t.mode or "activated"
	t.points = t.points or 1
	assert(t.mode == "activated" or t.mode == "sustained" or t.mode == "passive", "wrong talent mode, requires either 'activated' or 'sustained'")
	assert(t.info, "no talent info")

	-- Can pass a string, make it into a function
	if type(t.info) == "string" then
		local infostr = t.info
		t.info = function() return infostr end
	end
	-- Remove line stat with tabs to be cleaner ..
	local info = t.info
	t.info = function(self, t) return info(self, t):gsub("\n\t+", "\n") end

	-- I18N
	t.name = _t(t.name, "talent name")

	t.id = "T_"..t.short_name
	self.talents_def[t.id] = t
	assert(not self[t.id], "talent already exists with id T_"..t.short_name)
	self[t.id] = t.id
--	print("[TALENT]", t.name, t.short_name, t.id)

	-- Register in the type
	table.insert(self.talents_types_def[t.type[1]].talents, t)
end

--- Initialises stats with default values if needed
function _M:init(t)
	self.talents = t.talents or {}
	self.talents_types = t.talents_types or {}
	self.talents_types_mastery = self.talents_types_mastery or {}
	self.talents_mastery_bonus = self.talents_mastery_bonus or {}
	self.talents_cd = self.talents_cd or {}
	self.sustain_talents = self.sustain_talents or {}
	self.talents_auto = self.talents_auto or {}
	self.talents_confirm_use = self.talents_confirm_use or {}
	self.talents_learn_vals = t.talents_learn_vals or {}
	self.talents_add_levels = {}
end

--- Resolve leveling talents
function _M:resolveLevelTalents()
	if not self.start_level or not self._levelup_talents then return end
	for tid, info in pairs(self._levelup_talents) do
		if not info.max or (self.talents[tid] or 0) < info.max then
			local last = info.last or self.start_level
			if self.level - last >= info.every then
				self:learnTalent(tid, true)
				info.last = self.level
			end
		end
	end
end

--- Make the actor use a talent
-- @param id talent ID
-- @param who talent user
-- @param force_level talent level(raw) override
-- @param ignore_cd do not affect or consider cooldown
-- @param force_target the target of the talent (override)
-- @param silent do not display messages about use
-- @param no_confirm  Never ask confirmation
-- @return the return value from the talent code if successful or false:
--	activated talents: value returned from the action function
--	sustainable talents: value returned from the activate function (if inactive, should be a table of parameters)
--		or value returned from the talent deactivate function (if active)
--  talent code should always return a non false/nil result if successful
function _M:useTalent(id, who, force_level, ignore_cd, force_target, silent, no_confirm)
	who = who or self
	local ab, ret = _M.talents_def[id]
	assert(ab, "trying to use talent "..tostring(id).." but it is not defined")

	self.talent_error = nil
	local cancel = false
	local co, success, err
	
	local msg, line

	local old_level, old_target, new_target = nil, nil, nil
	local function prepareUse()
		-- Stub some stuff
		if force_level then old_level = who.talents[id] end
		if ab.mode == "activated" then
			if ab.onAIGetTarget and not who.player then old_target = rawget(who, "getTarget"); new_target = function() return ab.onAIGetTarget(self, ab) end end
			if force_target and not old_target then old_target = rawget(who, "getTarget"); new_target = function(a) return force_target.x, force_target.y, not force_target.__no_self and force_target end end
		end
		if new_target then who.getTarget = new_target end
		if force_level then who.talents[id] = force_level end
	end
	local function finishUse()
		if new_target then who.getTarget = old_target end
		if force_level then who.talents[id] = old_level end
	end

	if ab.mode == "activated" and ab.action then
		if self:isTalentCoolingDown(ab) and not ignore_cd then
			game.logPlayer(who, "%s is still on cooldown for %d turns.", ab.name:capitalize(), math.ceil(self.talents_cd[ab.id]))
			return false
		end
		co = coroutine.create(function() -- coroutine to run activated talent code
			if cancel then
				success = false
				return false
			end
			
			if not self:preUseTalent(ab, silent) then return false end
			
			msg, line = game.logNewest()
			if not silent then self:logTalentMessage(ab) end
			
			self:setCurrentTalentMode("active", ab.id)
			prepareUse()
			local ok, ret, special = xpcall(function() return ab.action(who, ab) end, debug.traceback)
			finishUse()
			self:setCurrentTalentMode(nil)
			self.__talent_running = nil
			if not ok then self:onTalentLuaError(ab, ret) error(ret) end

			if not ret and self._silent_talent_failure then -- remove messages generated by failed talent
				local msg, newline = game.logNewest()
				if newline ~= line then game.logRollback(line) end
			end

			if not self:postUseTalent(ab, ret, silent) then return false end

			-- Everything went ok? then start cooldown if any
			if not ignore_cd and (not special or not special.ignore_cd) then self:startTalentCooldown(ab) end
			if ab.post_action then ab.post_action(who, ab) end
			return ret
		end)
	elseif ab.mode == "sustained" and ab.activate and ab.deactivate then
		if self:isTalentCoolingDown(ab) and not ignore_cd then
			game.logPlayer(who, "%s is still on cooldown for %d turns.", ab.name:capitalize(), math.ceil(self.talents_cd[ab.id]))
			return false
		end
		if ignore_cd == "ignore_check_only" then ignore_cd = nil end
		co = coroutine.create(function() -- coroutine to run sustainable talent code
			if cancel then
				success = false
				return false
			end
			if not self:preUseTalent(ab, silent) then return false end
			msg, line = game.logNewest()
			if not silent then self:logTalentMessage(ab) end
			
			local ok, ret, special
			if not self.sustain_talents[id] then -- activating
				if self.deactivating_sustain_talent == ab.id then return end
				self:setCurrentTalentMode("active", ab.id)
				prepareUse()
				ok, ret, special = xpcall(function() return ab.activate(who, ab) end, debug.traceback)
				finishUse()
				self:setCurrentTalentMode(nil)
				if not ok then self:onTalentLuaError(ab, ret) error(ret) end
				if ret == true then ret = {} end -- fix for badly coded talents
				if ret then ret.name = ret.name or ab.name end

				if not ret and self._silent_talent_failure then -- remove messages generated by failed talent
					local msg, newline = game.logNewest()
					if newline ~= line then game.logRollback(line) end
				end

				if not self:postUseTalent(ab, ret, silent) then return false end

				self.sustain_talents[id] = ret

				if ab.sustain_lists then
					local lists = ab.sustain_lists
					if 'table' ~= type(lists) then lists = {lists} end
					for _, list in ipairs(lists) do
						if 'table' == type(list) then
							list = table.getTable(self, unpack(list))
						else
							list = table.getTable(self, list)
						end
						table.insert(list, id)
					end
				end
				if ab.post_action then ab.post_action(who, ab) end
			else -- deactivating
				if self.deactivating_sustain_talent == ab.id then return end

				local p = self.sustain_talents[id]
				if p and type(p) == "table" and p.__tmpvals then
					for i = 1, #p.__tmpvals do
						self:removeTemporaryValue(p.__tmpvals[i][1], p.__tmpvals[i][2])
					end
				end
				p.__tmpvals = nil
				if p and type(p) == "table" and p.__tmpparticles then
					for i = 1, #p.__tmpparticles do
						self:removeParticles(p.__tmpparticles[i])
					end
				end
				p.__tmpparticles = nil
				self:setCurrentTalentMode("active", ab.id)
				prepareUse()
				ok, ret, special = xpcall(function() return ab.deactivate(who, ab, p) end, debug.traceback)
				finishUse()
				self:setCurrentTalentMode(nil)
				if not ok then self:onTalentLuaError(ab, ret) error(ret) end
				
				if not ret and self._silent_talent_failure then -- remove messages generated by failed talent
					local msg, newline = game.logNewest()
					if newline ~= line then game.logRollback(line) end
				end

				self.deactivating_sustain_talent = ab.id
				if not self:postUseTalent(ab, ret, silent) then self.deactivating_sustain_talent = nil return false end
				self.deactivating_sustain_talent = nil

				-- Everything went ok? then start cooldown if any
				if not ignore_cd then self:startTalentCooldown(ab) end
				self.sustain_talents[id] = nil

				if ab.sustain_lists then
					local lists = ab.sustain_lists
					if 'table' ~= type(lists) then lists = {lists} end
					for _, list in ipairs(lists) do
						if 'table' == type(list) then
							list = table.getTable(self, unpack(list))
						else
							list = table.getTable(self, list)
						end
						table.removeFromList(list, id)
					end
				end
				if ab.post_action then ab.post_action(who, ab) end
			end
			return ret
		end)
	else
		print("[useTalent] Attempt to use non activated or sustainable talent: "..id.." :: "..ab.name.." :: "..ab.mode)
	end
	if co then -- talent is usable and has passed checks
		local co_wrapper = coroutine.create(function() -- coroutine for talent interface
			success = true
			local ok
			while success do
				self.__talent_running = ab
				ok, ret = coroutine.resume(co) -- ret == error or return value from co
				success = success and ok
				self.__talent_running = nil
				if ok and coroutine.status(co) == "dead" then -- coroutine terminated normally
					if success and not ret then -- talent failed
						print("[useTalent] TALENT FAILED:", ab.id, "for", self.name, self.uid, success)
					--game.log("#ORANGE# %s TALENT USE FAILED [%s (silent_failure:%s at (%s, %s)]", ab.id, self.name, self._silent_talent_failure, self.x, self.y) -- debugging
					end
					return ret
				end
				if ret then error(ret) end --propagate error
				coroutine.yield()
			end
		end)
		if not no_confirm and self:isTalentConfirmable(ab) then
			local abname = game:getGenericTextTiles(ab)..tostring(self:getTalentDisplayName(ab))
			require "engine.ui.Dialog":yesnoPopup(_t"Talent Use Confirmation", ("Use %s?"):tformat(abname),
			function(quit)
				if quit ~= false then
					cancel = true
				end
				success, ret = coroutine.resume(co_wrapper)
				if not success and ret then -- talent code error
					self:onTalentLuaError(ab, ret)
					--print("useTalent:", debug.traceback(co_wrapper), '\n')
					error(ret)
				end
			end,
			_t"Cancel",_t"Continue")
		else
			success, ret = coroutine.resume(co_wrapper) -- cancel checked in coroutine
		end
		-- Cleanup in case we coroutine'd out
		self.__talent_running = nil
		if not success and ret then -- talent code error
			self:onTalentLuaError(ab, ret)
			--print("useTalent:", debug.traceback(co_wrapper), '\n')
			error(ret)
		end
	end
	self.changed = true
	
	return ret -- return value from successfully used talent
end

--- Set true to remove game log messages generated by talents that started but did not complete
--	affects messages logged after preUseTalent check when action/activate/deactivate function returns nil or false
_M._silent_talent_failure = false

--- Get the talent use message, replacing some markers in its message string with info on the talent
function _M:useTalentMessage(ab)
	if not ab.message then return nil end
	local str = util.getval(ab.message, self, ab)
	local _, _, target = self:getTarget()
	local tname = _t"unknown"
	if target then tname = target:getName() end
	str = str:noun_sub("@Source@", self:getName():capitalize())
	str = str:noun_sub("@source@", self:getName())
	str = str:noun_sub("@target@", tname)
	str = str:noun_sub("@Target@", tname:capitalize())
	str = str:gsub("@hisher@", string.his_her(self))
	return str
end

--- Display the talent use message in the game log
-- Redefine as needed
-- called in useTalent after successful preUseTalent check
-- @param[type=table] talent the talent (not the id, the table)
-- uses ab.message if defined or generates default use text (ab.message == false suppresses)
function _M:logTalentMessage(ab)
	if ab.message == false then return
	elseif ab.message then
		game.logSeen(self, "%s", self:useTalentMessage(ab))
	elseif ab.mode == "sustained" then
		game.logSeen(self, "%s %s %s.", self:getName():capitalize(), self:isTalentActive(ab.id) and _t"deactivates" or _t"activates", ab.name)
	else
		game.logSeen(self, "%s uses %s.", self:getName():capitalize(), ab.name)
	end
end

--- Called BEFORE a talent is used -- CAN it be used?
-- Redefine as needed
-- @param[type=table] ab the talent (not the id, the table)
-- @param[type=boolean] silent no messages will be outputted
-- @param[type=boolean] fake no actions are taken, only checks
-- @return[1] true to continue
-- @return[2] false to stop
function _M:preUseTalent(ab, silent, fake)
	return true
end

--- Called AFTER a talent is used -- WAS it successfully used?
-- Redefine as needed
-- @param[type=table] ab the talent (not the id, the table)
-- @param ret the return of the talent action, activate, or deactivate function
-- @param[type=boolean] silent no messages will be outputted
-- @return[1] true to continue
-- @return[2] false to stop
function _M:postUseTalent(ab, ret, silent)
	return true
end

--- Called if a talent errors out when used
-- Redefine as needed
-- @param ab the talent table
-- @param err the table of errors returned from xpcall
-- sets self.talent_error and logs errors to _M._talent_errors
-- 		data forma: {[ab.id]=ab, Actor=self, uid=, x=, y=, err=err, turn=game.turn}
function _M:onTalentLuaError(ab, err)
	if self.talent_error then return end -- handle only the first error
	self.talent_error = {[ab.id]=ab, Actor=self, uid=self.uid, name=self.name, err=err, x=self.x, y=self.y, turn=game.turn}
	print("##Use Talent Lua Error##", ab and ab.id, "Actor:", self.uid, self.name)
	_M._talent_errors = _M._talent_errors or {} -- log the error globally
	table.insert(_M._talent_errors, self.talent_error)
	return
end

--- Force a talent to activate without using energy or such  
-- "def" can have a field "ignore_energy" to not consume energy; other parameters can be passed and handled by an overload of this method.  
-- Object activation interface calls this method with an "ignore_ressources" parameter
function _M:forceUseTalent(t, def)
	if type(t) == "table" then t = t.id end -- Ugh
	local oldpause = game.paused
	local oldenergy = self.energy.value
	if def.ignore_energy then self.energy.value = 10000 end

	if def.ignore_ressources then self:attr("force_talent_ignore_ressources", 1) end
	self:setCurrentTalentMode("forced", t)
	local ret = {self:useTalent(t, def.force_who, def.force_level, def.ignore_cd or def.ignore_cooldown, def.force_target, def.silent, true)}
	self:setCurrentTalentMode(nil)
	if def.ignore_ressources then self:attr("force_talent_ignore_ressources", -1) end

	if def.ignore_energy then
		game.paused = oldpause
		self.energy.value = oldenergy
	end
	return unpack(ret)
end

--- Is the sustained talent activated ?
function _M:isTalentActive(t_id)
	return self.sustain_talents[t_id]
end

--- Checks a talent against a filter
-- @param[type=table] t the talent definition
-- @param[type=table, optional] filter a table of filter parameters
-- @return true if the talent satisfies the filter
-- Filter parameters:
--	mode: the mode of the talent (must match exactly)
--	not_mode: forbidden talent mode
--	ignore: additional filter that must NOT be satisfied
--	type: talent type[1] and subtype[2] that must be matched (if defined)
--	name: talent name (must match exactly)
--	short_name: talent short_name
--	define_as: talent define_as parameter
--	properties: list of properties (fields) that must be defined in the talent definition
--	properties_match: list of all required properties (fields) that must match exactly
--	not_properties: list of properties (fields) that must be nil or false in the talent definition
--	not_properties_match: list of all property values that must not match exactly
--	properties_include: list of properties (fields) to include (at least one must be defined)
--	preUse <boolean>: check self:preUseTalent(t, true, filter.fake)
--	aiPreUse <boolean>: check self:aiPreUseTalent(t, true, filter.fake)
--	special: function(t, self) that must return true (checked last)
-- Actor parameters:
--	self.filter_talents: additional filter to be applied to all talents for this actor
function _M:filterTalent(t, filter)
	if not filter then return true end
	if filter.ignore and self:filterTalent(t, filter.ignore) then return false end

	if filter.mode and filter.mode ~= t.mode then return false end
	if filter.not_mode and filter.not_mode == t.mode then return false end
	if filter.type then -- talent type
		if filter.type[1] ~= t.type[1] then return false end
		if filter.type[2] and filter.type[2] ~= t.type[2] then return false	end
	end
	if filter.name and filter.name ~= t.name then return false end
	if filter.short_name and filter.short_name ~= t.short_name then return false end
	if filter.properties then -- list of required properties
		for i = 1, #filter.properties do if t[filter.properties[i]] == nil then return false end end
	end
	if filter.properties_match then -- list of all required properties that must match exactly
		for prop, val in pairs(filter.properties_match) do if t[prop] ~= val then return false end end
	end
	if filter.not_properties then -- list of forbidden properties
		for i = 1, #filter.not_properties do if t[filter.not_properties[i]] then return false end end
	end
	if filter.not_properties_match then -- list of forbidden property values
		for prop, val in pairs(filter.not_properties_match) do if t[prop] == val then return false end end
	end
	if filter.properties_include then -- list of properties to include (at least one must be defined)
		local ok = false
		for i = 1, #filter.properties_include do if t[filter.properties_include[i]] ~= nil then ok = true break end end
		if not ok then return false end
	end
	if filter.preUse and not self:preUseTalent(t, true, filter.fake) then return false end
	if filter.aiPreUse and not self:aiPreUseTalent(t, true, filter.fake) then return false	end
	
	if self.filter_talents and not self:filterTalent(t, self.filter_talents) then return false end
	if filter.special and not filter.special(t, self) then return false end
	return true
end

--- Returns how many talents of this type the actor knows
-- @param type the talent type to count
-- @param exclude_id if not nil the count will ignore this talent id
-- @param limit_type if not nil the count will ignore talents with talent category level equal or higher that this
function _M:numberKnownTalent(type, exclude_id, limit_type)
	local nb = 0
	for id, _ in pairs(self.talents) do
		local t = _M.talents_def[id]
		if t.type[1] == type and (not exclude_id or exclude_id ~= id) and (not limit_type or not t.type[2] or t.type[2] < limit_type) then nb = nb + 1 end
	end
	return nb
end

--- Returns how many levels talents of this type the actor knows
-- @param type the talent type to count
-- @param exclude_id if not nil the count will ignore this talent id
-- @param limit_type if not nil the count will ignore talents with talent category level equal or higher that this
function _M:numberKnownTalentLevels(type, exclude_id, limit_type)
	local nb = 0
	for id, lvl in pairs(self.talents) do
		local t = _M.talents_def[id]
		if t.type[1] == type and (not exclude_id or exclude_id ~= id) and (not limit_type or not t.type[2] or t.type[2] < limit_type) then nb = nb + lvl end
	end
	return nb
end

--- Actor learns a talent
-- @param t_id the id of the talent to learn
-- @param force if true do not check canLearnTalent
-- @param nb the amount to increase the raw talent level by, default 1
-- @return[1] nil if failed
-- @return[1] an error message
-- @return[2] true if the talent was learned
function _M:learnTalent(t_id, force, nb)
--	print("[TALENT]", self.name, self.uid, "learning", t_id, force, nb)
	local t = _M.talents_def[t_id]
	assert(t, "Learning unknown talent: "..tostring(t_id))

	if not force then
		local ok, err = self:canLearnTalent(t)
		if not ok and err then return nil, err end
	end

	if not self.talents[t_id] then
		-- Auto assign to hotkey
		if t.mode ~= "passive" and not t.no_auto_hotkey and self.hotkey then
			local position

			if self.player then
				if self == game:getPlayer(true) then
					position = self:findQuickHotkey("Player: Specific", "talent", t_id)
					if not position then
						local global_hotkeys = engine.interface.PlayerHotkeys.quickhotkeys["Player: Global"]
						if global_hotkeys and global_hotkeys["talent"] then position = global_hotkeys["talent"][t_id] end
					end
				else
					position = self:findQuickHotkey(self.name, "talent", t_id)
				end
			end

			if position and not self.hotkey[position] then
				self.hotkey[position] = {"talent", t_id}
			else
				for i = 1, 12 * (self.nb_hotkey_pages or 5) do
					if not self.hotkey[i] then
						self.hotkey[i] = {"talent", t_id}
						break
					end
				end
			end
		end

		if t.learn_lists then
			local lists = t.learn_lists
			if 'table' ~= type(lists) then lists = {lists} end
			for _, list in ipairs(lists) do
				if 'table' == type(list) then
					list = table.getTable(self, unpack(list))
				else
					list = table.getTable(self, list)
				end
				table.insert(list, t.id)
			end
		end
	end

	for i = 1, (nb or 1) do
		self.talents[t_id] = (self.talents[t_id] or 0) + 1
		if t.on_learn then
			local ret = t.on_learn(self, t)
			if ret then
				if ret == true then ret = {} end
				self.talents_learn_vals[t.id] = self.talents_learn_vals[t.id] or {}
				self.talents_learn_vals[t.id][self.talents[t_id]] = ret
			end
		end
	end

	if t.passives then
		self.talents_learn_vals[t.id] = self.talents_learn_vals[t.id] or {}
		local p = self.talents_learn_vals[t.id]

		if p.__tmpvals then for i = 1, #p.__tmpvals do
			self:removeTemporaryValue(p.__tmpvals[i][1], p.__tmpvals[i][2])
		end end
		self.talents_learn_vals[t.id] = {}

		t.passives(self, t, self.talents_learn_vals[t.id])
	end

	self.changed = true
	return true
end

--- Actor forgets a talent completely
-- @param t_id the id of the talent to learn
-- @return[1] nil if failed
-- @return[1] an error message
-- @return[2] true if the talent was unlearned
function _M:unlearnTalentFull(t_id)
	local lvl = self:getTalentLevelRaw(t_id)
	if lvl > 0 then self:unlearnTalent(t_id, lvl) end
end

--- Actor forgets a talent
-- @param t_id the id of the talent to learn
-- @param nb
-- @return true if the talent was unlearnt, nil and an error message otherwise
function _M:unlearnTalent(t_id, nb)
	if not self:knowTalent(t_id) then return false, "talent not known" end

	local t = _M.talents_def[t_id]

	nb = math.min(nb or 1, self.talents[t_id])

	for j = 1, nb do
		if self.talents[t_id] and self.talents[t_id] == 1 then
			if self.hotkey then
				for i, known_t_id in pairs(self.hotkey) do
					if known_t_id[1] == "talent" and known_t_id[2] == t_id then self.hotkey[i] = nil end
				end
			end
		end

		self.talents[t_id] = self.talents[t_id] - 1
		if self.talents[t_id] == 0 then self.talents[t_id] = nil end

		if t.on_unlearn then
			local p = nil
			if self.talents_learn_vals[t.id] and self.talents_learn_vals[t.id][(self.talents[t_id] or 0) + 1] then
				p = self.talents_learn_vals[t.id][(self.talents[t_id] or 0) + 1]
				if p.__tmpvals then
					for i = 1, #p.__tmpvals do
						self:removeTemporaryValue(p.__tmpvals[i][1], p.__tmpvals[i][2])
					end
				end
			end
			t.on_unlearn(self, t, p)
		end
	end

	if t.passives then
		self.talents_learn_vals[t.id] = self.talents_learn_vals[t.id] or {}
		local p = self.talents_learn_vals[t.id]

		if p.__tmpvals then for i = 1, #p.__tmpvals do
			self:removeTemporaryValue(p.__tmpvals[i][1], p.__tmpvals[i][2])
		end end

		if self:knowTalent(t_id) then
			self.talents_learn_vals[t.id] = {}
			t.passives(self, t, self.talents_learn_vals[t.id])
		else
			self.talents_learn_vals[t.id] = nil
		end
	end

	if t.learn_lists and not self:knowTalent(t_id) then
		local lists = t.learn_lists
		if 'table' ~= type(lists) then lists = {lists} end
		for _, list in ipairs(lists) do
			if 'table' == type(list) then
				list = table.getTable(self, unpack(list))
			else
				list = table.getTable(self, list)
			end
			table.removeFromList(list, t.id)
		end
	end

	if self.talents[t_id] == nil then self.talents_auto[t_id] = nil end

	self.changed = true
	return true
end

--- Force passives update
function _M:updateTalentPassives(tid)
	if not self:knowTalent(tid) then return end

	local t = self:getTalentFromId(tid)
	if not t.passives then return end

	self.talents_learn_vals[t.id] = self.talents_learn_vals[t.id] or {}
	local p = self.talents_learn_vals[t.id]

	if p.__tmpvals then for i = 1, #p.__tmpvals do
		self:removeTemporaryValue(p.__tmpvals[i][1], p.__tmpvals[i][2])
	end end

	self.talents_learn_vals[t.id] = {}
	t.passives(self, t, self.talents_learn_vals[t.id])
end

--- Force all known passives to update
function _M:updateAllTalentsPassives()
	for tid, _ in pairs(self.talents) do
		self:updateTalentPassives(tid)
	end
end

--- Checks if the talent can be learned
-- @param t the talent to check
-- @param offset the level offset to check, defaults to 1
-- @param ignore_special ignore requirement of special
function _M:canLearnTalent(t, offset, ignore_special)
	-- Check prerequisites
	if rawget(t, "require") then
		local req = t.require
		if type(req) == "function" then req = req(self, t) end
		local tlev = self:getTalentLevelRaw(t) + (offset or 1)

		-- Obviously this requires the ActorStats interface
		if req.stat then
			for s, v in pairs(req.stat) do
				v = util.getval(v, tlev)
				if self:getStat(s) < v then return nil, ("not enough stat: %s"):tformat(s:upper()) end
			end
		end
		if req.level then
			if self.level < util.getval(req.level, tlev) then
				return nil, _t"not enough levels"
			end
		end
		if req.special and not ignore_special then
			if not req.special.fct(self, t, offset) then
				return nil, req.special.desc
			end
		end
		if req.special2 and not ignore_special then
			if not req.special2.fct(self, t, offset) then
				return nil, req.special2.desc
			end
		end
		if req.special3 and not ignore_special then
			if not req.special3.fct(self, t, offset) then
				return nil, req.special3.desc
			end
		end
		if req.talent then
			for _, tid in ipairs(req.talent) do
				if type(tid) == "table" then
					if type(tid[2]) == "boolean" and tid[2] == false then
						if self:knowTalent(tid[1]) then return nil, _t"missing dependency" end
					else
						if self:getTalentLevelRaw(tid[1]) < tid[2] then return nil, _t"missing dependency" end
					end
				else
					if not self:knowTalent(tid) then return nil, _t"missing dependency" end
				end
			end
		end
		if req.birth_descriptors then
			for _, d in ipairs(req.birth_descriptors) do
				if not self.descriptor or self.descriptor[d[1]] ~= d[2] then return nil, ("is not %s"):tformat(_t(d[2])) end
			end
		end
	end

	if not self:knowTalentType(t.type[1]) and not t.type_no_req then return nil, _t"unknown talent type" end

	-- Check talent type
	local known = self:numberKnownTalent(t.type[1], t.id, t.type[2])
	if t.type[2] and known < t.type[2] - 1 then
		return nil, _t"not enough talents of this type known"
	end

	-- Ok!
	return true
end

--- Formats the requirements as a (multiline) string
-- @param t_id the id of the talent to desc
-- @param levmod a number (1 should be the smartest) to add to current talent level to display requirements, defaults to 0
function _M:getTalentReqDesc(t_id, levmod)
	local t = _M.talents_def[t_id]
	local req = t.require
	if not req then return tstring{}, nil end
	if type(req) == "function" then req = req(self, t) end

	local tlev = self:getTalentLevelRaw(t_id) + (levmod or 0)

	local str = tstring{}

	if not t.type_no_req then
		str:add((self:knowTalentType(t.type[1]) and {"color", 0x00,0xff,0x00} or {"color", 0xff,0x00,0x00}), _t"- Talent category known", true)
	end

	if t.type[2] and t.type[2] > 1 then
		local known = self:numberKnownTalent(t.type[1], t.id, t.type[2])
		local c = (known >= t.type[2] - 1) and {"color", 0x00,0xff,0x00} or {"color", 0xff,0x00,0x00}
		str:add(c, ("- Lower talents of the same category: %d"):tformat(t.type[2] - 1), true)
	end

	-- Obviously this requires the ActorStats interface
	if req.stat then
		for s, v in pairs(req.stat) do
			v = util.getval(v, tlev)
			local c = (self:getStat(s) >= v) and {"color", 0x00,0xff,0x00} or {"color", 0xff,0x00,0x00}
			str:add(c, ("- %s %d"):format(self.stats_def[s].name, v), true)
		end
	end
	if req.level then
		local v = util.getval(req.level, tlev)
		local c = (self.level >= v) and {"color", 0x00,0xff,0x00} or {"color", 0xff,0x00,0x00}
		str:add(c, ("- Level %d"):tformat(v), true)
	end
	if req.special then
		local c = (req.special.fct(self, t, offset)) and {"color", 0x00,0xff,0x00} or {"color", 0xff,0x00,0x00}
		str:add(c, ("- %s"):format(req.special.desc), true)
	end
	if req.special2 then
		local c = (req.special2.fct(self, t, offset)) and {"color", 0x00,0xff,0x00} or {"color", 0xff,0x00,0x00}
		str:add(c, ("- %s"):format(req.special2.desc), true)
	end
	if req.special3 then
		local c = (req.special3.fct(self, t, offset)) and {"color", 0x00,0xff,0x00} or {"color", 0xff,0x00,0x00}
		str:add(c, ("- %s"):format(req.special3.desc), true)
	end
	if req.talent then
		for _, tid in ipairs(req.talent) do
			if type(tid) == "table" then
				if type(tid[2]) == "boolean" and tid[2] == false then
					local c = (not self:knowTalent(tid[1])) and {"color", 0x00,0xff,0x00} or {"color", 0xff,0x00,0x00}
					str:add(c, ("- Talent %s (not known)"):tformat(self:getTalentFromId(tid[1]).name), true)
				else
					local c = (self:getTalentLevelRaw(tid[1]) >= tid[2]) and {"color", 0x00,0xff,0x00} or {"color", 0xff,0x00,0x00}
					str:add(c, ("- Talent %s (%d)"):tformat(self:getTalentFromId(tid[1]).name, tid[2]), true)
				end
			else
				local c = self:knowTalent(tid) and {"color", 0x00,0xff,0x00} or {"color", 0xff,0x00,0x00}
				str:add(c, ("- Talent %s"):tformat(self:getTalentFromId(tid).name), true)
			end
		end
	end
	if req.birth_descriptors then
		for _, d in ipairs(req.birth_descriptors) do
			local c = self.descriptor and self.descriptor[d[1]] == d[2] and {"color", 0x00,0xff,0x00} or {"color", 0xff,0x00,0x00}
			str:add(c, ("- Is %s"):tformat(_t(d[2])), true)
		end
	end

	return str, req
end

--- Return the full description of a talent
-- You may overload it to add more data (like power usage, ...)
function _M:getTalentFullDescription(t)
	return tstring{t.info(self, t), true}
end

--- Do we know this talent type
function _M:knowTalentType(name)
	return self.talents_types[name]
end

--- Do we know this talent
function _M:knowTalent(id)
	if type(id) == "table" then id = id.id end
	return (self:getTalentLevelRaw(id) > 0) and true or false
end

--- Called if a talent level is > 0
function _M:alterTalentLevelRaw(t, lvl)
	if self.talents_add_levels and self.talents_add_levels[id] then lvl = lvl + self.talents_add_levels[id] end
	return lvl
end

--- Talent level, 0 if not known
function _M:getTalentLevelRaw(id)
	if type(id) == "table" then id = id.id end
	return self.talents[id] or 0
end

--- Talent level, 0 if not known
-- Includes mastery (defaults to 1)
function _M:getTalentLevel(id)
	local t
	if type(id) == "table" then t, id = id, id.id
	else t = _M.talents_def[id] end
	if not t then return 0 end

	local lvl = self:getTalentLevelRaw(id)
	if lvl > 0 then lvl = self:alterTalentLevelRaw(t, lvl) end
	return lvl * (self:getTalentMastery(t) or 0)

end

--- Talent type level, sum of all raw levels of talents inside
function _M:getTalentTypeLevelRaw(tt)
	local nb = 0
	for tid, lev in pairs(self.talents) do
		local t = self:getTalentFromId(tid)
		if t.type[1] == tt then nb = nb + lev end
	end
	return nb
end

--- Return talent type mastery
function _M:getTalentTypeMastery(tt)
	return (self.talents_types_mastery[tt] or 0) + 1
end

--- Return talent type mastery for this talent
function _M:getTalentMastery(t)
	local tt = t.type[1]
	return self:getTalentTypeMastery(tt)
end

--- Sets talent type mastery
function _M:setTalentTypeMastery(tt, v)
	-- "v - 1" because a mastery is expressed as x + 1, not x, so that 0 is the default value (thus getting 1)
	self.talents_types_mastery[tt] = v - 1

	self:updateTalentTypeMastery(tt)
end

--- Recompute things that need recomputing
function _M:updateTalentTypeMastery(tt)
	for i, t in pairs(self.talents_types_def[tt] and self.talents_types_def[tt].talents or {}) do
		if t.auto_relearn_passive or t.passives then
			local lvl = self:getTalentLevelRaw(t)
			if lvl > 0 then
				self:unlearnTalent(t.id, lvl)
				self:learnTalent(t.id, true, lvl)
			end
		end
	end
	if self.talents_types_def[tt] and self.talents_types_def[tt].on_mastery_change then
		self.talents_types_def[tt].on_mastery_change(self, self:getTalentTypeMastery(tt), tt)
	end
end

--- Return talent definition from id
function _M:getTalentFromId(id)
	if type(id) == "table" then return id end
	return _M.talents_def[id]
end

--- Return talent definition from id
function _M:getTalentTypeFrom(id)
	return _M.talents_types_def[id]
end

--- Actor learns a talent type
-- @param tt the id of the talent to learn
-- @param v value
-- @return[1] nil if failed
-- @return[1] an error message
-- @return[2] true if the talent was learned
function _M:learnTalentType(tt, v)
	if v == nil then v = true end
	if self.talents_types[tt] then return end
	self.talents_types[tt] = v
	self.talents_types_mastery[tt] = self.talents_types_mastery[tt] or 0
	self.changed = true
	return true
end

--- Actor forgets a talent type
-- @param tt the id of the talent to unlearn
-- @return[1] nil if failed
-- @return[1] an error message
-- @return[2] true if the talent was unlearned
function _M:unlearnTalentType(tt)
	self.talents_types[tt] = false
	self.changed = true
	return true
end

--- Gets a talent cooldown
-- @param t the talent to get cooldown
function _M:getTalentCooldown(t)
	if not t.cooldown then return end
	local cd = t.cooldown
	if type(cd) == "function" then cd = cd(self, t) end
	return cd
end

--- Starts a talent cooldown
-- @param t the talent to cooldown
-- @param v override the normal cooldown that that, nil to get the normal effect
function _M:startTalentCooldown(t, v)
	t = self:getTalentFromId(t)
	local cd = t.cooldown
	if v then cd = math.max(v, self.talents_cd[t.id] or 0) end
	if not cd then return end
	if type(cd) == "function" then cd = cd(self, t) end
	self.talents_cd[t.id] = cd
	self.changed = true
	if t.cooldownStart then t.cooldownStart(self, t) end
end

--- Alter the remanining cooldown of a talent
-- @param t the talent affect cooldown
-- @param v the value to add/remove to the cooldown
function _M:alterTalentCoolingdown(t, v)
	t = self:getTalentFromId(t)
	if not self.talents_cd[t.id] then return nil end
	self.talents_cd[t.id] = self.talents_cd[t.id] + v
	if self.talents_cd[t.id] <= 0 then self.talents_cd[t.id] = nil end
	return self.talents_cd[t.id]
end

--- Is talent in cooldown?
function _M:isTalentCoolingDown(t)
	t = self:getTalentFromId(t)
	if not t or not t.cooldown then return false end
	if self.talents_cd[t.id] and self.talents_cd[t.id] > 0 then return self.talents_cd[t.id] else return false end
end

--- Returns the range of a talent (defaults to 1)
function _M:getTalentRange(t)
	if not t.range then return 1 end
	if type(t.range) == "function" then return t.range(self, t) end
	return t.range
end

--- Returns the radius of a talent (defaults to 0)
function _M:getTalentRadius(t)
	if not t.radius then return 0 end
	if type(t.radius) == "function" then return t.radius(self, t) end
	return t.radius
end

--- Returns the target table for a talent
function _M:getTalentTarget(t)
	if type(t.target) == "function" then
		typ = t.target(self, t)
		if typ then typ.talent_mode = self:getCurrentTalentMode() end
		return typ
	end
	if t.target then t.target.talent_mode = self:getCurrentTalentMode() end -- Yes t is a global, not linked to actor, but this shouldnt matter as this will be set every time anyway
	return t.target
end

-- Returns whether the talent needs a target or not
function _M:getTalentRequiresTarget(t)
	if type(t.requires_target) == "function" then return t.requires_target(self, t) end
	return t.requires_target
end

--- Returns the projectile speed of a talent
function _M:getTalentProjectileSpeed(t)
	if not t.proj_speed then return nil end
	if type(t.proj_speed) == "function" then return t.proj_speed(self, t) end
	return t.proj_speed
end

--- Returns display name
function _M:getTalentDisplayName(t)
	if not t.display_name then return t.name end
	if type(t.display_name) == "function" then return t.display_name(self, t) end
	return t.display_name
end

--- Cooldown all talents
-- This should be called in your actors "act()" method
-- @param turns the number of turns to cooldown the talents
function _M:cooldownTalents(turns)
	for tid, c in pairs(self.talents_cd) do
		self.changed = true
		self.talents_cd[tid] = self.talents_cd[tid] - (turns or 1)
		if self.talents_cd[tid] <= 0 then
			self.talents_cd[tid] = nil
			if self.onTalentCooledDown then self:onTalentCooledDown(tid) end
			local t = _M.talents_def[tid]
			if t and t.cooldownStop then t.cooldownStop(self, t) end
		end
	end
end

--- Setup the talent as autocast
function _M:setTalentAuto(tid, v)
	if type(tid) == "table" then tid = tid.id end
	if v then self.talents_auto[tid] = true
	else self.talents_auto[tid] = nil
	end
end

--- Setup the talent as autocast
function _M:isTalentAuto(tid)
	if type(tid) == "table" then tid = tid.id end
	return self.talents_auto[tid]
end

--- Try to auto use listed talents
-- This should be called in your actors "act()" method
function _M:automaticTalents()
	for tid, c in pairs(self.talents_auto) do
		local t = self.talents_def[tid]
		if not t.no_npc_use and (t.mode ~= "sustained" or not self.sustain_talents[tid]) and not self.talents_cd[tid] and self:preUseTalent(t, true, true) and (not t.auto_use_check or t.auto_use_check(self, t)) then
			self:useTalent(tid)
		end
	end
end

--- Set the talent confirmation
function _M:setTalentConfirmable(tid, v)
	if type(tid) == "table" then tid = tid.id end
	if v then self.talents_confirm_use[tid] = true
	else self.talents_confirm_use[tid] = nil
	end
end

--- Does the talent require confirmation to use?
function _M:isTalentConfirmable(tid)
	if type(tid) == "table" then tid = tid.id end
	if not self.talents_confirm_use then self.talents_confirm_use = {} end -- For compatibility with older versions, can be removed
	return self.player and self.talents_confirm_use[tid]
end

--- Show usage dialog
function _M:useTalents(add_cols)
	local d = require("engine.dialogs.UseTalents").new(self, add_cols)
	game:registerDialog(d)
end

--- Helper function to add temporary values and not have to remove them manualy
function _M:talentTemporaryValue(p, k, v)
	if not p.__tmpvals then p.__tmpvals = {} end
	p.__tmpvals[#p.__tmpvals+1] = {k, self:addTemporaryValue(k, v)}
end

--- Helper function to add temporary particles and not have to remove them manualy
function _M:talentParticles(p, ...)
	local Particles = require "engine.Particles"
	if not p.__tmpparticles then p.__tmpparticles = {} end
	local ret = {}
	for _, ps in ipairs{...} do
		local pp = self:addParticles(Particles.new(ps.type, 1, ps.args, ps.shader))
		p.__tmpparticles[#p.__tmpparticles+1] = pp
		ret[#ret+1] = pp
	end
	return unpack(ret)
end

function _M:getCurrentTalent()
	return self._temp_data and self._temp_data.current_talent and self._temp_data.current_talent[1] or nil
end

function _M:getCurrentTalentMode()
	return self._temp_data and self._temp_data.current_talent_mode and self._temp_data.current_talent_mode[1] or "none"
end

function _M:getCurrentTalentModeLast()
	return self._temp_data and self._temp_data.current_talent_mode and self._temp_data.current_talent_mode[#self._temp_data.current_talent_mode] or "none"
end

function _M:setCurrentTalentMode(mode, tid)
	if not self._temp_data then self._temp_data = {} end
	if not self._temp_data.current_talent_mode then self._temp_data.current_talent_mode = {} end
	if not self._temp_data.current_talent then self._temp_data.current_talent = {} end
	if mode then
		table.insert(self._temp_data.current_talent_mode, mode)
		table.insert(self._temp_data.current_talent, tid)
	else
		table.remove(self._temp_data.current_talent_mode)
		table.remove(self._temp_data.current_talent)
	end
end

--- Trigger a talent method
function _M:triggerTalent(tid, name, ...)
	if self:isTalentCoolingDown(tid) then return end

	local t = _M.talents_def[tid]
	name = name or "trigger"
	if t[name] then
		self.__talent_running = t
		self:setCurrentTalentMode("trigger", t.id)
		local ret = {t[name](self, t, ...)}
		self:setCurrentTalentMode(nil)
		self.__talent_running = nil
		return unpack(ret, 1, table.maxn(ret))
	end
end

--- Trigger a talent method
function _M:callTalent(tid, name, ...)
	local t = _M.talents_def[tid]
	name = name or "trigger"
	if t[name] then
		self.__talent_running = t
		self:setCurrentTalentMode("call", t.id)
		local ret = {t[name](self, t, ...)}
		self:setCurrentTalentMode(nil)
		self.__talent_running = nil
		return unpack(ret, 1, table.maxn(ret))
	end
end

--- Trigger all talents matching
function _M:talentCallbackOn(on, ...)
	for tid, _ in pairs(self.sustain_talents) do
		local t = self:getTalentFromId(tid)
		if t and t[on] then
			self:callTalent(tid, on, ...)
		end
	end
end

local dialog_returns_list = setmetatable({}, {__mode="v"})
local dialog_returns = setmetatable({}, {__mode="k"})

--- Retrieve talent dialog data
function _M:talentDialogData()
	return dialog_returns_list, dialog_returns
end

--- Set the result for a talent dialog
function _M:talentDialogReturn(...)
	local d = dialog_returns_list[#dialog_returns_list]
	if not d then return end

	dialog_returns[d] = {...}
end

--- Get the dialog
function _M:talentDialogGet()
	return dialog_returns_list[#dialog_returns_list]
end

--- Show a dialog and wait for it to end in a talent
function _M:talentDialog(d)
	if not game:hasDialog(d) then game:registerDialog(d) end

	dialog_returns_list[#dialog_returns_list+1] = d

	local co = coroutine.running()
	d.unload = function(dialog)
		local ok, err = coroutine.resume(co, dialog_returns[d])
		if not ok and err then
			print(debug.traceback(co))
			self:onTalentLuaError(nil, err)
			error(err)
		end
	end
	local ret = coroutine.yield()

	dialog_returns[d] = nil
	table.removeFromList(dialog_returns_list, d)

	return unpack(ret or {})
end