animation_tree.cpp 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847
  1. /*************************************************************************/
  2. /* animation_tree.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "animation_tree.h"
  31. #include "animation_blend_tree.h"
  32. #include "core/config/engine.h"
  33. #include "scene/resources/animation.h"
  34. #include "scene/scene_string_names.h"
  35. #include "servers/audio/audio_stream.h"
  36. void AnimationNode::get_parameter_list(List<PropertyInfo> *r_list) const {
  37. Array parameters;
  38. if (GDVIRTUAL_CALL(_get_parameter_list, parameters)) {
  39. for (int i = 0; i < parameters.size(); i++) {
  40. Dictionary d = parameters[i];
  41. ERR_CONTINUE(d.is_empty());
  42. r_list->push_back(PropertyInfo::from_dict(d));
  43. }
  44. }
  45. }
  46. Variant AnimationNode::get_parameter_default_value(const StringName &p_parameter) const {
  47. Variant ret;
  48. if (GDVIRTUAL_CALL(_get_parameter_default_value, p_parameter, ret)) {
  49. return ret;
  50. }
  51. return Variant();
  52. }
  53. void AnimationNode::set_parameter(const StringName &p_name, const Variant &p_value) {
  54. ERR_FAIL_COND(!state);
  55. ERR_FAIL_COND(!state->tree->property_parent_map.has(base_path));
  56. ERR_FAIL_COND(!state->tree->property_parent_map[base_path].has(p_name));
  57. StringName path = state->tree->property_parent_map[base_path][p_name];
  58. state->tree->property_map[path] = p_value;
  59. }
  60. Variant AnimationNode::get_parameter(const StringName &p_name) const {
  61. ERR_FAIL_COND_V(!state, Variant());
  62. ERR_FAIL_COND_V(!state->tree->property_parent_map.has(base_path), Variant());
  63. ERR_FAIL_COND_V(!state->tree->property_parent_map[base_path].has(p_name), Variant());
  64. StringName path = state->tree->property_parent_map[base_path][p_name];
  65. return state->tree->property_map[path];
  66. }
  67. void AnimationNode::get_child_nodes(List<ChildNode> *r_child_nodes) {
  68. Dictionary cn;
  69. if (GDVIRTUAL_CALL(_get_child_nodes, cn)) {
  70. List<Variant> keys;
  71. cn.get_key_list(&keys);
  72. for (const Variant &E : keys) {
  73. ChildNode child;
  74. child.name = E;
  75. child.node = cn[E];
  76. r_child_nodes->push_back(child);
  77. }
  78. }
  79. }
  80. void AnimationNode::blend_animation(const StringName &p_animation, real_t p_time, real_t p_delta, bool p_seeked, real_t p_blend, int p_pingponged) {
  81. ERR_FAIL_COND(!state);
  82. ERR_FAIL_COND(!state->player->has_animation(p_animation));
  83. Ref<Animation> animation = state->player->get_animation(p_animation);
  84. if (animation.is_null()) {
  85. AnimationNodeBlendTree *btree = Object::cast_to<AnimationNodeBlendTree>(parent);
  86. if (btree) {
  87. String name = btree->get_node_name(Ref<AnimationNodeAnimation>(this));
  88. make_invalid(vformat(RTR("In node '%s', invalid animation: '%s'."), name, p_animation));
  89. } else {
  90. make_invalid(vformat(RTR("Invalid animation: '%s'."), p_animation));
  91. }
  92. return;
  93. }
  94. ERR_FAIL_COND(!animation.is_valid());
  95. AnimationState anim_state;
  96. anim_state.blend = p_blend;
  97. anim_state.track_blends = &blends;
  98. anim_state.delta = p_delta;
  99. anim_state.time = p_time;
  100. anim_state.animation = animation;
  101. anim_state.seeked = p_seeked;
  102. anim_state.pingponged = p_pingponged;
  103. state->animation_states.push_back(anim_state);
  104. }
  105. real_t AnimationNode::_pre_process(const StringName &p_base_path, AnimationNode *p_parent, State *p_state, real_t p_time, bool p_seek, const Vector<StringName> &p_connections) {
  106. base_path = p_base_path;
  107. parent = p_parent;
  108. connections = p_connections;
  109. state = p_state;
  110. real_t t = process(p_time, p_seek);
  111. state = nullptr;
  112. parent = nullptr;
  113. base_path = StringName();
  114. connections.clear();
  115. return t;
  116. }
  117. void AnimationNode::make_invalid(const String &p_reason) {
  118. ERR_FAIL_COND(!state);
  119. state->valid = false;
  120. if (state->invalid_reasons != String()) {
  121. state->invalid_reasons += "\n";
  122. }
  123. state->invalid_reasons += String::utf8("• ") + p_reason;
  124. }
  125. real_t AnimationNode::blend_input(int p_input, real_t p_time, bool p_seek, real_t p_blend, FilterAction p_filter, bool p_optimize) {
  126. ERR_FAIL_INDEX_V(p_input, inputs.size(), 0);
  127. ERR_FAIL_COND_V(!state, 0);
  128. AnimationNodeBlendTree *blend_tree = Object::cast_to<AnimationNodeBlendTree>(parent);
  129. ERR_FAIL_COND_V(!blend_tree, 0);
  130. StringName node_name = connections[p_input];
  131. if (!blend_tree->has_node(node_name)) {
  132. String name = blend_tree->get_node_name(Ref<AnimationNode>(this));
  133. make_invalid(vformat(RTR("Nothing connected to input '%s' of node '%s'."), get_input_name(p_input), name));
  134. return 0;
  135. }
  136. Ref<AnimationNode> node = blend_tree->get_node(node_name);
  137. //inputs.write[p_input].last_pass = state->last_pass;
  138. real_t activity = 0.0;
  139. real_t ret = _blend_node(node_name, blend_tree->get_node_connection_array(node_name), nullptr, node, p_time, p_seek, p_blend, p_filter, p_optimize, &activity);
  140. Vector<AnimationTree::Activity> *activity_ptr = state->tree->input_activity_map.getptr(base_path);
  141. if (activity_ptr && p_input < activity_ptr->size()) {
  142. activity_ptr->write[p_input].last_pass = state->last_pass;
  143. activity_ptr->write[p_input].activity = activity;
  144. }
  145. return ret;
  146. }
  147. real_t AnimationNode::blend_node(const StringName &p_sub_path, Ref<AnimationNode> p_node, real_t p_time, bool p_seek, real_t p_blend, FilterAction p_filter, bool p_optimize) {
  148. return _blend_node(p_sub_path, Vector<StringName>(), this, p_node, p_time, p_seek, p_blend, p_filter, p_optimize);
  149. }
  150. real_t AnimationNode::_blend_node(const StringName &p_subpath, const Vector<StringName> &p_connections, AnimationNode *p_new_parent, Ref<AnimationNode> p_node, real_t p_time, bool p_seek, real_t p_blend, FilterAction p_filter, bool p_optimize, real_t *r_max) {
  151. ERR_FAIL_COND_V(!p_node.is_valid(), 0);
  152. ERR_FAIL_COND_V(!state, 0);
  153. int blend_count = blends.size();
  154. if (p_node->blends.size() != blend_count) {
  155. p_node->blends.resize(blend_count);
  156. }
  157. real_t *blendw = p_node->blends.ptrw();
  158. const real_t *blendr = blends.ptr();
  159. bool any_valid = false;
  160. if (has_filter() && is_filter_enabled() && p_filter != FILTER_IGNORE) {
  161. for (int i = 0; i < blend_count; i++) {
  162. blendw[i] = 0.0; //all to zero by default
  163. }
  164. const NodePath *K = nullptr;
  165. while ((K = filter.next(K))) {
  166. if (!state->track_map.has(*K)) {
  167. continue;
  168. }
  169. int idx = state->track_map[*K];
  170. blendw[idx] = 1.0; //filtered goes to one
  171. }
  172. switch (p_filter) {
  173. case FILTER_IGNORE:
  174. break; //will not happen anyway
  175. case FILTER_PASS: {
  176. //values filtered pass, the rest don't
  177. for (int i = 0; i < blend_count; i++) {
  178. if (blendw[i] == 0) { //not filtered, does not pass
  179. continue;
  180. }
  181. blendw[i] = blendr[i] * p_blend;
  182. if (blendw[i] > CMP_EPSILON) {
  183. any_valid = true;
  184. }
  185. }
  186. } break;
  187. case FILTER_STOP: {
  188. //values filtered don't pass, the rest are blended
  189. for (int i = 0; i < blend_count; i++) {
  190. if (blendw[i] > 0) { //filtered, does not pass
  191. continue;
  192. }
  193. blendw[i] = blendr[i] * p_blend;
  194. if (blendw[i] > CMP_EPSILON) {
  195. any_valid = true;
  196. }
  197. }
  198. } break;
  199. case FILTER_BLEND: {
  200. //filtered values are blended, the rest are passed without blending
  201. for (int i = 0; i < blend_count; i++) {
  202. if (blendw[i] == 1.0) {
  203. blendw[i] = blendr[i] * p_blend; //filtered, blend
  204. } else {
  205. blendw[i] = blendr[i]; //not filtered, do not blend
  206. }
  207. if (blendw[i] > CMP_EPSILON) {
  208. any_valid = true;
  209. }
  210. }
  211. } break;
  212. }
  213. } else {
  214. for (int i = 0; i < blend_count; i++) {
  215. //regular blend
  216. blendw[i] = blendr[i] * p_blend;
  217. if (blendw[i] > CMP_EPSILON) {
  218. any_valid = true;
  219. }
  220. }
  221. }
  222. if (r_max) {
  223. *r_max = 0;
  224. for (int i = 0; i < blend_count; i++) {
  225. *r_max = MAX(*r_max, blendw[i]);
  226. }
  227. }
  228. if (!p_seek && p_optimize && !any_valid) { //pointless to go on, all are zero
  229. return 0;
  230. }
  231. String new_path;
  232. AnimationNode *new_parent;
  233. //this is the slowest part of processing, but as strings process in powers of 2, and the paths always exist, it will not result in that many allocations
  234. if (p_new_parent) {
  235. new_parent = p_new_parent;
  236. new_path = String(base_path) + String(p_subpath) + "/";
  237. } else {
  238. ERR_FAIL_COND_V(!parent, 0);
  239. new_parent = parent;
  240. new_path = String(parent->base_path) + String(p_subpath) + "/";
  241. }
  242. return p_node->_pre_process(new_path, new_parent, state, p_time, p_seek, p_connections);
  243. }
  244. int AnimationNode::get_input_count() const {
  245. return inputs.size();
  246. }
  247. String AnimationNode::get_input_name(int p_input) {
  248. ERR_FAIL_INDEX_V(p_input, inputs.size(), String());
  249. return inputs[p_input].name;
  250. }
  251. String AnimationNode::get_caption() const {
  252. String ret;
  253. if (GDVIRTUAL_CALL(_get_caption, ret)) {
  254. return ret;
  255. }
  256. return "Node";
  257. }
  258. void AnimationNode::add_input(const String &p_name) {
  259. //root nodes can't add inputs
  260. ERR_FAIL_COND(Object::cast_to<AnimationRootNode>(this) != nullptr);
  261. Input input;
  262. ERR_FAIL_COND(p_name.find(".") != -1 || p_name.find("/") != -1);
  263. input.name = p_name;
  264. inputs.push_back(input);
  265. emit_changed();
  266. }
  267. void AnimationNode::set_input_name(int p_input, const String &p_name) {
  268. ERR_FAIL_INDEX(p_input, inputs.size());
  269. ERR_FAIL_COND(p_name.find(".") != -1 || p_name.find("/") != -1);
  270. inputs.write[p_input].name = p_name;
  271. emit_changed();
  272. }
  273. void AnimationNode::remove_input(int p_index) {
  274. ERR_FAIL_INDEX(p_index, inputs.size());
  275. inputs.remove(p_index);
  276. emit_changed();
  277. }
  278. double AnimationNode::process(double p_time, bool p_seek) {
  279. double ret;
  280. if (GDVIRTUAL_CALL(_process, p_time, p_seek, ret)) {
  281. return ret;
  282. }
  283. return 0;
  284. }
  285. void AnimationNode::set_filter_path(const NodePath &p_path, bool p_enable) {
  286. if (p_enable) {
  287. filter[p_path] = true;
  288. } else {
  289. filter.erase(p_path);
  290. }
  291. }
  292. void AnimationNode::set_filter_enabled(bool p_enable) {
  293. filter_enabled = p_enable;
  294. }
  295. bool AnimationNode::is_filter_enabled() const {
  296. return filter_enabled;
  297. }
  298. bool AnimationNode::is_path_filtered(const NodePath &p_path) const {
  299. return filter.has(p_path);
  300. }
  301. bool AnimationNode::has_filter() const {
  302. bool ret;
  303. if (GDVIRTUAL_CALL(_has_filter, ret)) {
  304. return ret;
  305. }
  306. return false;
  307. }
  308. Array AnimationNode::_get_filters() const {
  309. Array paths;
  310. const NodePath *K = nullptr;
  311. while ((K = filter.next(K))) {
  312. paths.push_back(String(*K)); //use strings, so sorting is possible
  313. }
  314. paths.sort(); //done so every time the scene is saved, it does not change
  315. return paths;
  316. }
  317. void AnimationNode::_set_filters(const Array &p_filters) {
  318. filter.clear();
  319. for (int i = 0; i < p_filters.size(); i++) {
  320. set_filter_path(p_filters[i], true);
  321. }
  322. }
  323. void AnimationNode::_validate_property(PropertyInfo &property) const {
  324. if (!has_filter() && (property.name == "filter_enabled" || property.name == "filters")) {
  325. property.usage = PROPERTY_USAGE_NONE;
  326. }
  327. }
  328. Ref<AnimationNode> AnimationNode::get_child_by_name(const StringName &p_name) {
  329. Ref<AnimationNode> ret;
  330. if (GDVIRTUAL_CALL(_get_child_by_name, p_name, ret)) {
  331. return ret;
  332. }
  333. return Ref<AnimationNode>();
  334. }
  335. void AnimationNode::_bind_methods() {
  336. ClassDB::bind_method(D_METHOD("get_input_count"), &AnimationNode::get_input_count);
  337. ClassDB::bind_method(D_METHOD("get_input_name", "input"), &AnimationNode::get_input_name);
  338. ClassDB::bind_method(D_METHOD("add_input", "name"), &AnimationNode::add_input);
  339. ClassDB::bind_method(D_METHOD("remove_input", "index"), &AnimationNode::remove_input);
  340. ClassDB::bind_method(D_METHOD("set_filter_path", "path", "enable"), &AnimationNode::set_filter_path);
  341. ClassDB::bind_method(D_METHOD("is_path_filtered", "path"), &AnimationNode::is_path_filtered);
  342. ClassDB::bind_method(D_METHOD("set_filter_enabled", "enable"), &AnimationNode::set_filter_enabled);
  343. ClassDB::bind_method(D_METHOD("is_filter_enabled"), &AnimationNode::is_filter_enabled);
  344. ClassDB::bind_method(D_METHOD("_set_filters", "filters"), &AnimationNode::_set_filters);
  345. ClassDB::bind_method(D_METHOD("_get_filters"), &AnimationNode::_get_filters);
  346. ClassDB::bind_method(D_METHOD("blend_animation", "animation", "time", "delta", "seeked", "blend", "pingponged"), &AnimationNode::blend_animation, DEFVAL(0));
  347. ClassDB::bind_method(D_METHOD("blend_node", "name", "node", "time", "seek", "blend", "filter", "optimize"), &AnimationNode::blend_node, DEFVAL(FILTER_IGNORE), DEFVAL(true));
  348. ClassDB::bind_method(D_METHOD("blend_input", "input_index", "time", "seek", "blend", "filter", "optimize"), &AnimationNode::blend_input, DEFVAL(FILTER_IGNORE), DEFVAL(true));
  349. ClassDB::bind_method(D_METHOD("set_parameter", "name", "value"), &AnimationNode::set_parameter);
  350. ClassDB::bind_method(D_METHOD("get_parameter", "name"), &AnimationNode::get_parameter);
  351. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "filter_enabled", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR), "set_filter_enabled", "is_filter_enabled");
  352. ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "filters", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL), "_set_filters", "_get_filters");
  353. GDVIRTUAL_BIND(_get_child_nodes);
  354. GDVIRTUAL_BIND(_get_parameter_list);
  355. GDVIRTUAL_BIND(_get_child_by_name, "name");
  356. GDVIRTUAL_BIND(_get_parameter_default_value, "parameter");
  357. GDVIRTUAL_BIND(_process, "time", "seek");
  358. GDVIRTUAL_BIND(_get_caption);
  359. GDVIRTUAL_BIND(_has_filter);
  360. ADD_SIGNAL(MethodInfo("removed_from_graph"));
  361. ADD_SIGNAL(MethodInfo("tree_changed"));
  362. BIND_ENUM_CONSTANT(FILTER_IGNORE);
  363. BIND_ENUM_CONSTANT(FILTER_PASS);
  364. BIND_ENUM_CONSTANT(FILTER_STOP);
  365. BIND_ENUM_CONSTANT(FILTER_BLEND);
  366. }
  367. AnimationNode::AnimationNode() {
  368. }
  369. ////////////////////
  370. void AnimationTree::set_tree_root(const Ref<AnimationNode> &p_root) {
  371. if (root.is_valid()) {
  372. root->disconnect("tree_changed", callable_mp(this, &AnimationTree::_tree_changed));
  373. }
  374. root = p_root;
  375. if (root.is_valid()) {
  376. root->connect("tree_changed", callable_mp(this, &AnimationTree::_tree_changed));
  377. }
  378. properties_dirty = true;
  379. update_configuration_warnings();
  380. }
  381. Ref<AnimationNode> AnimationTree::get_tree_root() const {
  382. return root;
  383. }
  384. void AnimationTree::set_active(bool p_active) {
  385. if (active == p_active) {
  386. return;
  387. }
  388. active = p_active;
  389. started = active;
  390. if (process_callback == ANIMATION_PROCESS_IDLE) {
  391. set_process_internal(active);
  392. } else {
  393. set_physics_process_internal(active);
  394. }
  395. if (!active && is_inside_tree()) {
  396. for (Set<TrackCache *>::Element *E = playing_caches.front(); E; E = E->next()) {
  397. if (ObjectDB::get_instance(E->get()->object_id)) {
  398. E->get()->object->call("stop");
  399. }
  400. }
  401. playing_caches.clear();
  402. }
  403. }
  404. bool AnimationTree::is_active() const {
  405. return active;
  406. }
  407. void AnimationTree::set_process_callback(AnimationProcessCallback p_mode) {
  408. if (process_callback == p_mode) {
  409. return;
  410. }
  411. bool was_active = is_active();
  412. if (was_active) {
  413. set_active(false);
  414. }
  415. process_callback = p_mode;
  416. if (was_active) {
  417. set_active(true);
  418. }
  419. }
  420. AnimationTree::AnimationProcessCallback AnimationTree::get_process_callback() const {
  421. return process_callback;
  422. }
  423. void AnimationTree::_node_removed(Node *p_node) {
  424. cache_valid = false;
  425. }
  426. bool AnimationTree::_update_caches(AnimationPlayer *player) {
  427. setup_pass++;
  428. if (!player->has_node(player->get_root())) {
  429. ERR_PRINT("AnimationTree: AnimationPlayer root is invalid.");
  430. set_active(false);
  431. return false;
  432. }
  433. Node *parent = player->get_node(player->get_root());
  434. List<StringName> sname;
  435. player->get_animation_list(&sname);
  436. for (const StringName &E : sname) {
  437. Ref<Animation> anim = player->get_animation(E);
  438. for (int i = 0; i < anim->get_track_count(); i++) {
  439. NodePath path = anim->track_get_path(i);
  440. Animation::TrackType track_type = anim->track_get_type(i);
  441. Animation::TrackType track_cache_type = track_type;
  442. if (track_cache_type == Animation::TYPE_POSITION_3D || track_cache_type == Animation::TYPE_ROTATION_3D || track_cache_type == Animation::TYPE_SCALE_3D) {
  443. track_cache_type = Animation::TYPE_POSITION_3D; //reference them as position3D tracks, even if they modify rotation or scale
  444. }
  445. TrackCache *track = nullptr;
  446. if (track_cache.has(path)) {
  447. track = track_cache.get(path);
  448. }
  449. //if not valid, delete track
  450. if (track && (track->type != track_cache_type || ObjectDB::get_instance(track->object_id) == nullptr)) {
  451. playing_caches.erase(track);
  452. memdelete(track);
  453. track_cache.erase(path);
  454. track = nullptr;
  455. }
  456. if (!track) {
  457. RES resource;
  458. Vector<StringName> leftover_path;
  459. Node *child = parent->get_node_and_resource(path, resource, leftover_path);
  460. if (!child) {
  461. ERR_PRINT("AnimationTree: '" + String(E) + "', couldn't resolve track: '" + String(path) + "'");
  462. continue;
  463. }
  464. if (!child->is_connected("tree_exited", callable_mp(this, &AnimationTree::_node_removed))) {
  465. child->connect("tree_exited", callable_mp(this, &AnimationTree::_node_removed), varray(child));
  466. }
  467. switch (track_type) {
  468. case Animation::TYPE_VALUE: {
  469. TrackCacheValue *track_value = memnew(TrackCacheValue);
  470. if (resource.is_valid()) {
  471. track_value->object = resource.ptr();
  472. } else {
  473. track_value->object = child;
  474. }
  475. track_value->subpath = leftover_path;
  476. track_value->object_id = track_value->object->get_instance_id();
  477. track = track_value;
  478. } break;
  479. case Animation::TYPE_POSITION_3D:
  480. case Animation::TYPE_ROTATION_3D:
  481. case Animation::TYPE_SCALE_3D: {
  482. #ifndef _3D_DISABLED
  483. Node3D *node_3d = Object::cast_to<Node3D>(child);
  484. if (!node_3d) {
  485. ERR_PRINT("AnimationTree: '" + String(E) + "', transform track does not point to Node3D: '" + String(path) + "'");
  486. continue;
  487. }
  488. TrackCacheTransform *track_xform = memnew(TrackCacheTransform);
  489. track_xform->type = Animation::TYPE_POSITION_3D;
  490. track_xform->node_3d = node_3d;
  491. track_xform->skeleton = nullptr;
  492. track_xform->bone_idx = -1;
  493. if (path.get_subname_count() == 1 && Object::cast_to<Skeleton3D>(node_3d)) {
  494. Skeleton3D *sk = Object::cast_to<Skeleton3D>(node_3d);
  495. track_xform->skeleton = sk;
  496. int bone_idx = sk->find_bone(path.get_subname(0));
  497. if (bone_idx != -1) {
  498. track_xform->bone_idx = bone_idx;
  499. }
  500. }
  501. track_xform->object = node_3d;
  502. track_xform->object_id = track_xform->object->get_instance_id();
  503. track = track_xform;
  504. switch (track_type) {
  505. case Animation::TYPE_POSITION_3D: {
  506. track_xform->loc_used = true;
  507. } break;
  508. case Animation::TYPE_ROTATION_3D: {
  509. track_xform->rot_used = true;
  510. } break;
  511. case Animation::TYPE_SCALE_3D: {
  512. track_xform->scale_used = true;
  513. } break;
  514. default: {
  515. }
  516. }
  517. #endif // _3D_DISABLED
  518. } break;
  519. case Animation::TYPE_BLEND_SHAPE: {
  520. #ifndef _3D_DISABLED
  521. if (path.get_subname_count() != 1) {
  522. ERR_PRINT("AnimationTree: '" + String(E) + "', blend shape track does not contain a blend shape subname: '" + String(path) + "'");
  523. continue;
  524. }
  525. MeshInstance3D *mesh_3d = Object::cast_to<MeshInstance3D>(child);
  526. if (!mesh_3d) {
  527. ERR_PRINT("AnimationTree: '" + String(E) + "', blend shape track does not point to MeshInstance3D: '" + String(path) + "'");
  528. continue;
  529. }
  530. StringName blend_shape_name = path.get_subname(0);
  531. int blend_shape_idx = mesh_3d->find_blend_shape_by_name(blend_shape_name);
  532. if (blend_shape_idx == -1) {
  533. ERR_PRINT("AnimationTree: '" + String(E) + "', blend shape track points to a non-existing name: '" + String(blend_shape_name) + "'");
  534. continue;
  535. }
  536. TrackCacheBlendShape *track_bshape = memnew(TrackCacheBlendShape);
  537. track_bshape->mesh_3d = mesh_3d;
  538. track_bshape->shape_index = blend_shape_idx;
  539. track_bshape->object = mesh_3d;
  540. track_bshape->object_id = mesh_3d->get_instance_id();
  541. track = track_bshape;
  542. #endif
  543. } break;
  544. case Animation::TYPE_METHOD: {
  545. TrackCacheMethod *track_method = memnew(TrackCacheMethod);
  546. if (resource.is_valid()) {
  547. track_method->object = resource.ptr();
  548. } else {
  549. track_method->object = child;
  550. }
  551. track_method->object_id = track_method->object->get_instance_id();
  552. track = track_method;
  553. } break;
  554. case Animation::TYPE_BEZIER: {
  555. TrackCacheBezier *track_bezier = memnew(TrackCacheBezier);
  556. if (resource.is_valid()) {
  557. track_bezier->object = resource.ptr();
  558. } else {
  559. track_bezier->object = child;
  560. }
  561. track_bezier->subpath = leftover_path;
  562. track_bezier->object_id = track_bezier->object->get_instance_id();
  563. track = track_bezier;
  564. } break;
  565. case Animation::TYPE_AUDIO: {
  566. TrackCacheAudio *track_audio = memnew(TrackCacheAudio);
  567. track_audio->object = child;
  568. track_audio->object_id = track_audio->object->get_instance_id();
  569. track = track_audio;
  570. } break;
  571. case Animation::TYPE_ANIMATION: {
  572. TrackCacheAnimation *track_animation = memnew(TrackCacheAnimation);
  573. track_animation->object = child;
  574. track_animation->object_id = track_animation->object->get_instance_id();
  575. track = track_animation;
  576. } break;
  577. default: {
  578. ERR_PRINT("Animation corrupted (invalid track type)");
  579. continue;
  580. }
  581. }
  582. track_cache[path] = track;
  583. } else if (track_cache_type == Animation::TYPE_POSITION_3D) {
  584. TrackCacheTransform *track_xform = static_cast<TrackCacheTransform *>(track);
  585. if (track->setup_pass != setup_pass) {
  586. track_xform->loc_used = false;
  587. track_xform->rot_used = false;
  588. track_xform->scale_used = false;
  589. }
  590. switch (track_type) {
  591. case Animation::TYPE_POSITION_3D: {
  592. track_xform->loc_used = true;
  593. } break;
  594. case Animation::TYPE_ROTATION_3D: {
  595. track_xform->rot_used = true;
  596. } break;
  597. case Animation::TYPE_SCALE_3D: {
  598. track_xform->scale_used = true;
  599. } break;
  600. default: {
  601. }
  602. }
  603. }
  604. track->setup_pass = setup_pass;
  605. }
  606. }
  607. List<NodePath> to_delete;
  608. const NodePath *K = nullptr;
  609. while ((K = track_cache.next(K))) {
  610. TrackCache *tc = track_cache[*K];
  611. if (tc->setup_pass != setup_pass) {
  612. to_delete.push_back(*K);
  613. }
  614. }
  615. while (to_delete.front()) {
  616. NodePath np = to_delete.front()->get();
  617. memdelete(track_cache[np]);
  618. track_cache.erase(np);
  619. to_delete.pop_front();
  620. }
  621. state.track_map.clear();
  622. K = nullptr;
  623. int idx = 0;
  624. while ((K = track_cache.next(K))) {
  625. state.track_map[*K] = idx;
  626. idx++;
  627. }
  628. state.track_count = idx;
  629. cache_valid = true;
  630. return true;
  631. }
  632. void AnimationTree::_clear_caches() {
  633. const NodePath *K = nullptr;
  634. while ((K = track_cache.next(K))) {
  635. memdelete(track_cache[*K]);
  636. }
  637. playing_caches.clear();
  638. track_cache.clear();
  639. cache_valid = false;
  640. }
  641. void AnimationTree::_process_graph(real_t p_delta) {
  642. _update_properties(); //if properties need updating, update them
  643. //check all tracks, see if they need modification
  644. root_motion_transform = Transform3D();
  645. if (!root.is_valid()) {
  646. ERR_PRINT("AnimationTree: root AnimationNode is not set, disabling playback.");
  647. set_active(false);
  648. cache_valid = false;
  649. return;
  650. }
  651. if (!has_node(animation_player)) {
  652. ERR_PRINT("AnimationTree: no valid AnimationPlayer path set, disabling playback");
  653. set_active(false);
  654. cache_valid = false;
  655. return;
  656. }
  657. AnimationPlayer *player = Object::cast_to<AnimationPlayer>(get_node(animation_player));
  658. ObjectID current_animation_player;
  659. if (player) {
  660. current_animation_player = player->get_instance_id();
  661. }
  662. if (last_animation_player != current_animation_player) {
  663. if (last_animation_player.is_valid()) {
  664. Object *old_player = ObjectDB::get_instance(last_animation_player);
  665. if (old_player) {
  666. old_player->disconnect("caches_cleared", callable_mp(this, &AnimationTree::_clear_caches));
  667. }
  668. }
  669. if (player) {
  670. player->connect("caches_cleared", callable_mp(this, &AnimationTree::_clear_caches));
  671. }
  672. last_animation_player = current_animation_player;
  673. }
  674. if (!player) {
  675. ERR_PRINT("AnimationTree: path points to a node not an AnimationPlayer, disabling playback");
  676. set_active(false);
  677. cache_valid = false;
  678. return;
  679. }
  680. if (!cache_valid) {
  681. if (!_update_caches(player)) {
  682. return;
  683. }
  684. }
  685. { //setup
  686. process_pass++;
  687. state.valid = true;
  688. state.invalid_reasons = "";
  689. state.animation_states.clear(); //will need to be re-created
  690. state.valid = true;
  691. state.player = player;
  692. state.last_pass = process_pass;
  693. state.tree = this;
  694. // root source blends
  695. root->blends.resize(state.track_count);
  696. real_t *src_blendsw = root->blends.ptrw();
  697. for (int i = 0; i < state.track_count; i++) {
  698. src_blendsw[i] = 1.0; //by default all go to 1 for the root input
  699. }
  700. }
  701. //process
  702. {
  703. if (started) {
  704. //if started, seek
  705. root->_pre_process(SceneStringNames::get_singleton()->parameters_base_path, nullptr, &state, 0, true, Vector<StringName>());
  706. started = false;
  707. }
  708. root->_pre_process(SceneStringNames::get_singleton()->parameters_base_path, nullptr, &state, p_delta, false, Vector<StringName>());
  709. }
  710. if (!state.valid) {
  711. return; //state is not valid. do nothing.
  712. }
  713. //apply value/transform/bezier blends to track caches and execute method/audio/animation tracks
  714. {
  715. bool can_call = is_inside_tree() && !Engine::get_singleton()->is_editor_hint();
  716. for (const AnimationNode::AnimationState &as : state.animation_states) {
  717. Ref<Animation> a = as.animation;
  718. double time = as.time;
  719. double delta = as.delta;
  720. real_t weight = as.blend;
  721. bool seeked = as.seeked;
  722. int pingponged = as.pingponged;
  723. #ifndef _3D_DISABLED
  724. bool backward = signbit(delta);
  725. #endif // _3D_DISABLED
  726. for (int i = 0; i < a->get_track_count(); i++) {
  727. NodePath path = a->track_get_path(i);
  728. ERR_CONTINUE(!track_cache.has(path));
  729. TrackCache *track = track_cache[path];
  730. Animation::TrackType ttype = a->track_get_type(i);
  731. if (ttype != Animation::TYPE_POSITION_3D && ttype != Animation::TYPE_ROTATION_3D && ttype != Animation::TYPE_SCALE_3D && track->type != ttype) {
  732. //broken animation, but avoid error spamming
  733. continue;
  734. }
  735. track->root_motion = root_motion_track == path;
  736. ERR_CONTINUE(!state.track_map.has(path));
  737. int blend_idx = state.track_map[path];
  738. ERR_CONTINUE(blend_idx < 0 || blend_idx >= state.track_count);
  739. real_t blend = (*as.track_blends)[blend_idx] * weight;
  740. if (blend < CMP_EPSILON) {
  741. continue; //nothing to blend
  742. }
  743. switch (ttype) {
  744. case Animation::TYPE_POSITION_3D: {
  745. #ifndef _3D_DISABLED
  746. TrackCacheTransform *t = static_cast<TrackCacheTransform *>(track);
  747. if (t->process_pass != process_pass) {
  748. t->process_pass = process_pass;
  749. t->loc = Vector3();
  750. t->rot = Quaternion();
  751. t->rot_blend_accum = 0;
  752. t->scale = Vector3(1, 1, 1);
  753. }
  754. if (track->root_motion) {
  755. double prev_time = time - delta;
  756. if (!backward) {
  757. if (prev_time < 0) {
  758. switch (a->get_loop_mode()) {
  759. case Animation::LOOP_NONE: {
  760. prev_time = 0;
  761. } break;
  762. case Animation::LOOP_LINEAR: {
  763. prev_time = Math::fposmod(prev_time, (double)a->get_length());
  764. } break;
  765. case Animation::LOOP_PINGPONG: {
  766. prev_time = Math::pingpong(prev_time, (double)a->get_length());
  767. } break;
  768. default:
  769. break;
  770. }
  771. }
  772. } else {
  773. if (prev_time > a->get_length()) {
  774. switch (a->get_loop_mode()) {
  775. case Animation::LOOP_NONE: {
  776. prev_time = (double)a->get_length();
  777. } break;
  778. case Animation::LOOP_LINEAR: {
  779. prev_time = Math::fposmod(prev_time, (double)a->get_length());
  780. } break;
  781. case Animation::LOOP_PINGPONG: {
  782. prev_time = Math::pingpong(prev_time, (double)a->get_length());
  783. } break;
  784. default:
  785. break;
  786. }
  787. }
  788. }
  789. Vector3 loc[2];
  790. if (!backward) {
  791. if (prev_time > time) {
  792. Error err = a->position_track_interpolate(i, prev_time, &loc[0]);
  793. if (err != OK) {
  794. continue;
  795. }
  796. a->position_track_interpolate(i, (double)a->get_length(), &loc[1]);
  797. t->loc += (loc[1] - loc[0]) * blend;
  798. prev_time = 0;
  799. }
  800. } else {
  801. if (prev_time < time) {
  802. Error err = a->position_track_interpolate(i, prev_time, &loc[0]);
  803. if (err != OK) {
  804. continue;
  805. }
  806. a->position_track_interpolate(i, 0, &loc[1]);
  807. t->loc += (loc[1] - loc[0]) * blend;
  808. prev_time = 0;
  809. }
  810. }
  811. Error err = a->position_track_interpolate(i, prev_time, &loc[0]);
  812. if (err != OK) {
  813. continue;
  814. }
  815. a->position_track_interpolate(i, time, &loc[1]);
  816. t->loc += (loc[1] - loc[0]) * blend;
  817. prev_time = !backward ? 0 : (double)a->get_length();
  818. } else {
  819. Vector3 loc;
  820. Error err = a->position_track_interpolate(i, time, &loc);
  821. if (err != OK) {
  822. continue;
  823. }
  824. t->loc = t->loc.lerp(loc, blend);
  825. }
  826. #endif // _3D_DISABLED
  827. } break;
  828. case Animation::TYPE_ROTATION_3D: {
  829. #ifndef _3D_DISABLED
  830. TrackCacheTransform *t = static_cast<TrackCacheTransform *>(track);
  831. if (t->process_pass != process_pass) {
  832. t->process_pass = process_pass;
  833. t->loc = Vector3();
  834. t->rot = Quaternion();
  835. t->rot_blend_accum = 0;
  836. t->scale = Vector3(1, 1, 1);
  837. }
  838. if (track->root_motion) {
  839. double prev_time = time - delta;
  840. if (!backward) {
  841. if (prev_time < 0) {
  842. switch (a->get_loop_mode()) {
  843. case Animation::LOOP_NONE: {
  844. prev_time = 0;
  845. } break;
  846. case Animation::LOOP_LINEAR: {
  847. prev_time = Math::fposmod(prev_time, (double)a->get_length());
  848. } break;
  849. case Animation::LOOP_PINGPONG: {
  850. prev_time = Math::pingpong(prev_time, (double)a->get_length());
  851. } break;
  852. default:
  853. break;
  854. }
  855. }
  856. } else {
  857. if (prev_time > a->get_length()) {
  858. switch (a->get_loop_mode()) {
  859. case Animation::LOOP_NONE: {
  860. prev_time = (double)a->get_length();
  861. } break;
  862. case Animation::LOOP_LINEAR: {
  863. prev_time = Math::fposmod(prev_time, (double)a->get_length());
  864. } break;
  865. case Animation::LOOP_PINGPONG: {
  866. prev_time = Math::pingpong(prev_time, (double)a->get_length());
  867. } break;
  868. default:
  869. break;
  870. }
  871. }
  872. }
  873. Quaternion rot[2];
  874. if (!backward) {
  875. if (prev_time > time) {
  876. Error err = a->rotation_track_interpolate(i, prev_time, &rot[0]);
  877. if (err != OK) {
  878. continue;
  879. }
  880. a->rotation_track_interpolate(i, (double)a->get_length(), &rot[1]);
  881. Quaternion q = Quaternion().slerp(rot[0].normalized().inverse() * rot[1].normalized(), blend).normalized();
  882. t->rot = (t->rot * q).normalized();
  883. prev_time = 0;
  884. }
  885. } else {
  886. if (prev_time < time) {
  887. Error err = a->rotation_track_interpolate(i, prev_time, &rot[0]);
  888. if (err != OK) {
  889. continue;
  890. }
  891. a->rotation_track_interpolate(i, 0, &rot[1]);
  892. Quaternion q = Quaternion().slerp(rot[0].normalized().inverse() * rot[1].normalized(), blend).normalized();
  893. t->rot = (t->rot * q).normalized();
  894. prev_time = 0;
  895. }
  896. }
  897. Error err = a->rotation_track_interpolate(i, prev_time, &rot[0]);
  898. if (err != OK) {
  899. continue;
  900. }
  901. a->rotation_track_interpolate(i, time, &rot[1]);
  902. Quaternion q = Quaternion().slerp(rot[0].normalized().inverse() * rot[1].normalized(), blend).normalized();
  903. t->rot = (t->rot * q).normalized();
  904. prev_time = !backward ? 0 : (double)a->get_length();
  905. } else {
  906. Quaternion rot;
  907. Error err = a->rotation_track_interpolate(i, time, &rot);
  908. if (err != OK) {
  909. continue;
  910. }
  911. if (t->rot_blend_accum == 0) {
  912. t->rot = rot;
  913. t->rot_blend_accum = blend;
  914. } else {
  915. real_t rot_total = t->rot_blend_accum + blend;
  916. t->rot = rot.slerp(t->rot, t->rot_blend_accum / rot_total).normalized();
  917. t->rot_blend_accum = rot_total;
  918. }
  919. }
  920. #endif // _3D_DISABLED
  921. } break;
  922. case Animation::TYPE_SCALE_3D: {
  923. #ifndef _3D_DISABLED
  924. TrackCacheTransform *t = static_cast<TrackCacheTransform *>(track);
  925. if (t->process_pass != process_pass) {
  926. t->process_pass = process_pass;
  927. t->loc = Vector3();
  928. t->rot = Quaternion();
  929. t->rot_blend_accum = 0;
  930. t->scale = Vector3(1, 1, 1);
  931. }
  932. if (track->root_motion) {
  933. double prev_time = time - delta;
  934. if (!backward) {
  935. if (prev_time < 0) {
  936. switch (a->get_loop_mode()) {
  937. case Animation::LOOP_NONE: {
  938. prev_time = 0;
  939. } break;
  940. case Animation::LOOP_LINEAR: {
  941. prev_time = Math::fposmod(prev_time, (double)a->get_length());
  942. } break;
  943. case Animation::LOOP_PINGPONG: {
  944. prev_time = Math::pingpong(prev_time, (double)a->get_length());
  945. } break;
  946. default:
  947. break;
  948. }
  949. }
  950. } else {
  951. if (prev_time > a->get_length()) {
  952. switch (a->get_loop_mode()) {
  953. case Animation::LOOP_NONE: {
  954. prev_time = (double)a->get_length();
  955. } break;
  956. case Animation::LOOP_LINEAR: {
  957. prev_time = Math::fposmod(prev_time, (double)a->get_length());
  958. } break;
  959. case Animation::LOOP_PINGPONG: {
  960. prev_time = Math::pingpong(prev_time, (double)a->get_length());
  961. } break;
  962. default:
  963. break;
  964. }
  965. }
  966. }
  967. Vector3 scale[2];
  968. if (!backward) {
  969. if (prev_time > time) {
  970. Error err = a->scale_track_interpolate(i, prev_time, &scale[0]);
  971. if (err != OK) {
  972. continue;
  973. }
  974. a->scale_track_interpolate(i, (double)a->get_length(), &scale[1]);
  975. t->scale += (scale[1] - scale[0]) * blend;
  976. prev_time = 0;
  977. }
  978. } else {
  979. if (prev_time < time) {
  980. Error err = a->scale_track_interpolate(i, prev_time, &scale[0]);
  981. if (err != OK) {
  982. continue;
  983. }
  984. a->scale_track_interpolate(i, 0, &scale[1]);
  985. t->scale += (scale[1] - scale[0]) * blend;
  986. prev_time = 0;
  987. }
  988. }
  989. Error err = a->scale_track_interpolate(i, prev_time, &scale[0]);
  990. if (err != OK) {
  991. continue;
  992. }
  993. a->scale_track_interpolate(i, time, &scale[1]);
  994. t->scale += (scale[1] - scale[0]) * blend;
  995. prev_time = !backward ? 0 : (double)a->get_length();
  996. } else {
  997. Vector3 scale;
  998. Error err = a->scale_track_interpolate(i, time, &scale);
  999. if (err != OK) {
  1000. continue;
  1001. }
  1002. t->scale = t->scale.lerp(scale, blend);
  1003. }
  1004. #endif // _3D_DISABLED
  1005. } break;
  1006. case Animation::TYPE_BLEND_SHAPE: {
  1007. #ifndef _3D_DISABLED
  1008. TrackCacheBlendShape *t = static_cast<TrackCacheBlendShape *>(track);
  1009. if (t->process_pass != process_pass) {
  1010. t->process_pass = process_pass;
  1011. t->value = 0;
  1012. }
  1013. float value;
  1014. Error err = a->blend_shape_track_interpolate(i, time, &value);
  1015. //ERR_CONTINUE(err!=OK); //used for testing, should be removed
  1016. if (err != OK) {
  1017. continue;
  1018. }
  1019. t->value = Math::lerp(t->value, value, blend);
  1020. #endif // _3D_DISABLED
  1021. } break;
  1022. case Animation::TYPE_VALUE: {
  1023. TrackCacheValue *t = static_cast<TrackCacheValue *>(track);
  1024. Animation::UpdateMode update_mode = a->value_track_get_update_mode(i);
  1025. if (update_mode == Animation::UPDATE_CONTINUOUS || update_mode == Animation::UPDATE_CAPTURE) { //delta == 0 means seek
  1026. Variant value = a->value_track_interpolate(i, time);
  1027. if (value == Variant()) {
  1028. continue;
  1029. }
  1030. if (t->process_pass != process_pass) {
  1031. t->value = value;
  1032. t->process_pass = process_pass;
  1033. }
  1034. Variant::interpolate(t->value, value, blend, t->value);
  1035. } else {
  1036. List<int> indices;
  1037. a->value_track_get_key_indices(i, time, delta, &indices, pingponged);
  1038. for (int &F : indices) {
  1039. Variant value = a->track_get_key_value(i, F);
  1040. t->object->set_indexed(t->subpath, value);
  1041. }
  1042. }
  1043. } break;
  1044. case Animation::TYPE_METHOD: {
  1045. if (delta == 0) {
  1046. continue;
  1047. }
  1048. TrackCacheMethod *t = static_cast<TrackCacheMethod *>(track);
  1049. List<int> indices;
  1050. a->method_track_get_key_indices(i, time, delta, &indices, pingponged);
  1051. for (int &F : indices) {
  1052. StringName method = a->method_track_get_name(i, F);
  1053. Vector<Variant> params = a->method_track_get_params(i, F);
  1054. int s = params.size();
  1055. static_assert(VARIANT_ARG_MAX == 8, "This code needs to be updated if VARIANT_ARG_MAX != 8");
  1056. ERR_CONTINUE(s > VARIANT_ARG_MAX);
  1057. if (can_call) {
  1058. t->object->call_deferred(
  1059. method,
  1060. s >= 1 ? params[0] : Variant(),
  1061. s >= 2 ? params[1] : Variant(),
  1062. s >= 3 ? params[2] : Variant(),
  1063. s >= 4 ? params[3] : Variant(),
  1064. s >= 5 ? params[4] : Variant(),
  1065. s >= 6 ? params[5] : Variant(),
  1066. s >= 7 ? params[6] : Variant(),
  1067. s >= 8 ? params[7] : Variant());
  1068. }
  1069. }
  1070. } break;
  1071. case Animation::TYPE_BEZIER: {
  1072. TrackCacheBezier *t = static_cast<TrackCacheBezier *>(track);
  1073. real_t bezier = a->bezier_track_interpolate(i, time);
  1074. if (t->process_pass != process_pass) {
  1075. t->value = bezier;
  1076. t->process_pass = process_pass;
  1077. }
  1078. t->value = Math::lerp(t->value, bezier, blend);
  1079. } break;
  1080. case Animation::TYPE_AUDIO: {
  1081. TrackCacheAudio *t = static_cast<TrackCacheAudio *>(track);
  1082. if (seeked) {
  1083. //find whatever should be playing
  1084. int idx = a->track_find_key(i, time);
  1085. if (idx < 0) {
  1086. continue;
  1087. }
  1088. Ref<AudioStream> stream = a->audio_track_get_key_stream(i, idx);
  1089. if (!stream.is_valid()) {
  1090. t->object->call("stop");
  1091. t->playing = false;
  1092. playing_caches.erase(t);
  1093. } else {
  1094. real_t start_ofs = a->audio_track_get_key_start_offset(i, idx);
  1095. start_ofs += time - a->track_get_key_time(i, idx);
  1096. real_t end_ofs = a->audio_track_get_key_end_offset(i, idx);
  1097. real_t len = stream->get_length();
  1098. if (start_ofs > len - end_ofs) {
  1099. t->object->call("stop");
  1100. t->playing = false;
  1101. playing_caches.erase(t);
  1102. continue;
  1103. }
  1104. t->object->call("set_stream", stream);
  1105. t->object->call("play", start_ofs);
  1106. t->playing = true;
  1107. playing_caches.insert(t);
  1108. if (len && end_ofs > 0) { //force an end at a time
  1109. t->len = len - start_ofs - end_ofs;
  1110. } else {
  1111. t->len = 0;
  1112. }
  1113. t->start = time;
  1114. }
  1115. } else {
  1116. //find stuff to play
  1117. List<int> to_play;
  1118. a->track_get_key_indices_in_range(i, time, delta, &to_play, pingponged);
  1119. if (to_play.size()) {
  1120. int idx = to_play.back()->get();
  1121. Ref<AudioStream> stream = a->audio_track_get_key_stream(i, idx);
  1122. if (!stream.is_valid()) {
  1123. t->object->call("stop");
  1124. t->playing = false;
  1125. playing_caches.erase(t);
  1126. } else {
  1127. real_t start_ofs = a->audio_track_get_key_start_offset(i, idx);
  1128. real_t end_ofs = a->audio_track_get_key_end_offset(i, idx);
  1129. real_t len = stream->get_length();
  1130. t->object->call("set_stream", stream);
  1131. t->object->call("play", start_ofs);
  1132. t->playing = true;
  1133. playing_caches.insert(t);
  1134. if (len && end_ofs > 0) { //force an end at a time
  1135. t->len = len - start_ofs - end_ofs;
  1136. } else {
  1137. t->len = 0;
  1138. }
  1139. t->start = time;
  1140. }
  1141. } else if (t->playing) {
  1142. bool loop = a->get_loop_mode() != Animation::LoopMode::LOOP_NONE;
  1143. bool stop = false;
  1144. if (!loop) {
  1145. if (delta > 0) {
  1146. if (time < t->start) {
  1147. stop = true;
  1148. }
  1149. } else if (delta < 0) {
  1150. if (time > t->start) {
  1151. stop = true;
  1152. }
  1153. }
  1154. } else if (t->len > 0) {
  1155. real_t len = t->start > time ? (a->get_length() - t->start) + time : time - t->start;
  1156. if (len > t->len) {
  1157. stop = true;
  1158. }
  1159. }
  1160. if (stop) {
  1161. //time to stop
  1162. t->object->call("stop");
  1163. t->playing = false;
  1164. playing_caches.erase(t);
  1165. }
  1166. }
  1167. }
  1168. real_t db = Math::linear2db(MAX(blend, 0.00001));
  1169. if (t->object->has_method("set_unit_db")) {
  1170. t->object->call("set_unit_db", db);
  1171. } else {
  1172. t->object->call("set_volume_db", db);
  1173. }
  1174. } break;
  1175. case Animation::TYPE_ANIMATION: {
  1176. TrackCacheAnimation *t = static_cast<TrackCacheAnimation *>(track);
  1177. AnimationPlayer *player2 = Object::cast_to<AnimationPlayer>(t->object);
  1178. if (!player2) {
  1179. continue;
  1180. }
  1181. if (seeked) {
  1182. //seek
  1183. int idx = a->track_find_key(i, time);
  1184. if (idx < 0) {
  1185. continue;
  1186. }
  1187. double pos = a->track_get_key_time(i, idx);
  1188. StringName anim_name = a->animation_track_get_key_animation(i, idx);
  1189. if (String(anim_name) == "[stop]" || !player2->has_animation(anim_name)) {
  1190. continue;
  1191. }
  1192. Ref<Animation> anim = player2->get_animation(anim_name);
  1193. real_t at_anim_pos = 0.0;
  1194. switch (anim->get_loop_mode()) {
  1195. case Animation::LoopMode::LOOP_NONE: {
  1196. at_anim_pos = MAX((double)anim->get_length(), time - pos); //seek to end
  1197. } break;
  1198. case Animation::LoopMode::LOOP_LINEAR: {
  1199. at_anim_pos = Math::fposmod(time - pos, (double)anim->get_length()); //seek to loop
  1200. } break;
  1201. case Animation::LoopMode::LOOP_PINGPONG: {
  1202. at_anim_pos = Math::pingpong(time - pos, (double)a->get_length());
  1203. } break;
  1204. default:
  1205. break;
  1206. }
  1207. if (player2->is_playing() || seeked) {
  1208. player2->play(anim_name);
  1209. player2->seek(at_anim_pos);
  1210. t->playing = true;
  1211. playing_caches.insert(t);
  1212. } else {
  1213. player2->set_assigned_animation(anim_name);
  1214. player2->seek(at_anim_pos, true);
  1215. }
  1216. } else {
  1217. //find stuff to play
  1218. List<int> to_play;
  1219. a->track_get_key_indices_in_range(i, time, delta, &to_play, pingponged);
  1220. if (to_play.size()) {
  1221. int idx = to_play.back()->get();
  1222. StringName anim_name = a->animation_track_get_key_animation(i, idx);
  1223. if (String(anim_name) == "[stop]" || !player2->has_animation(anim_name)) {
  1224. if (playing_caches.has(t)) {
  1225. playing_caches.erase(t);
  1226. player2->stop();
  1227. t->playing = false;
  1228. }
  1229. } else {
  1230. player2->play(anim_name);
  1231. t->playing = true;
  1232. playing_caches.insert(t);
  1233. }
  1234. }
  1235. }
  1236. } break;
  1237. }
  1238. }
  1239. }
  1240. }
  1241. {
  1242. // finally, set the tracks
  1243. const NodePath *K = nullptr;
  1244. while ((K = track_cache.next(K))) {
  1245. TrackCache *track = track_cache[*K];
  1246. if (track->process_pass != process_pass) {
  1247. continue; //not processed, ignore
  1248. }
  1249. switch (track->type) {
  1250. case Animation::TYPE_POSITION_3D: {
  1251. #ifndef _3D_DISABLED
  1252. TrackCacheTransform *t = static_cast<TrackCacheTransform *>(track);
  1253. if (t->root_motion) {
  1254. Transform3D xform;
  1255. xform.origin = t->loc;
  1256. xform.basis.set_quaternion_scale(t->rot, t->scale);
  1257. root_motion_transform = xform;
  1258. } else if (t->skeleton && t->bone_idx >= 0) {
  1259. if (t->loc_used) {
  1260. t->skeleton->set_bone_pose_position(t->bone_idx, t->loc);
  1261. }
  1262. if (t->rot_used) {
  1263. t->skeleton->set_bone_pose_rotation(t->bone_idx, t->rot);
  1264. }
  1265. if (t->scale_used) {
  1266. t->skeleton->set_bone_pose_scale(t->bone_idx, t->scale);
  1267. }
  1268. } else if (!t->skeleton) {
  1269. if (t->loc_used) {
  1270. t->node_3d->set_position(t->loc);
  1271. }
  1272. if (t->rot_used) {
  1273. t->node_3d->set_rotation(t->rot.get_euler());
  1274. }
  1275. if (t->scale_used) {
  1276. t->node_3d->set_scale(t->scale);
  1277. }
  1278. }
  1279. #endif // _3D_DISABLED
  1280. } break;
  1281. case Animation::TYPE_BLEND_SHAPE: {
  1282. #ifndef _3D_DISABLED
  1283. TrackCacheBlendShape *t = static_cast<TrackCacheBlendShape *>(track);
  1284. if (t->mesh_3d) {
  1285. t->mesh_3d->set_blend_shape_value(t->shape_index, t->value);
  1286. }
  1287. #endif // _3D_DISABLED
  1288. } break;
  1289. case Animation::TYPE_VALUE: {
  1290. TrackCacheValue *t = static_cast<TrackCacheValue *>(track);
  1291. t->object->set_indexed(t->subpath, t->value);
  1292. } break;
  1293. case Animation::TYPE_BEZIER: {
  1294. TrackCacheBezier *t = static_cast<TrackCacheBezier *>(track);
  1295. t->object->set_indexed(t->subpath, t->value);
  1296. } break;
  1297. default: {
  1298. } //the rest don't matter
  1299. }
  1300. }
  1301. }
  1302. }
  1303. void AnimationTree::advance(real_t p_time) {
  1304. _process_graph(p_time);
  1305. }
  1306. void AnimationTree::_notification(int p_what) {
  1307. if (active && p_what == NOTIFICATION_INTERNAL_PHYSICS_PROCESS && process_callback == ANIMATION_PROCESS_PHYSICS) {
  1308. _process_graph(get_physics_process_delta_time());
  1309. }
  1310. if (active && p_what == NOTIFICATION_INTERNAL_PROCESS && process_callback == ANIMATION_PROCESS_IDLE) {
  1311. _process_graph(get_process_delta_time());
  1312. }
  1313. if (p_what == NOTIFICATION_EXIT_TREE) {
  1314. _clear_caches();
  1315. if (last_animation_player.is_valid()) {
  1316. Object *player = ObjectDB::get_instance(last_animation_player);
  1317. if (player) {
  1318. player->disconnect("caches_cleared", callable_mp(this, &AnimationTree::_clear_caches));
  1319. }
  1320. }
  1321. } else if (p_what == NOTIFICATION_ENTER_TREE) {
  1322. if (last_animation_player.is_valid()) {
  1323. Object *player = ObjectDB::get_instance(last_animation_player);
  1324. if (player) {
  1325. player->connect("caches_cleared", callable_mp(this, &AnimationTree::_clear_caches));
  1326. }
  1327. }
  1328. }
  1329. }
  1330. void AnimationTree::set_animation_player(const NodePath &p_player) {
  1331. animation_player = p_player;
  1332. update_configuration_warnings();
  1333. }
  1334. NodePath AnimationTree::get_animation_player() const {
  1335. return animation_player;
  1336. }
  1337. bool AnimationTree::is_state_invalid() const {
  1338. return !state.valid;
  1339. }
  1340. String AnimationTree::get_invalid_state_reason() const {
  1341. return state.invalid_reasons;
  1342. }
  1343. uint64_t AnimationTree::get_last_process_pass() const {
  1344. return process_pass;
  1345. }
  1346. TypedArray<String> AnimationTree::get_configuration_warnings() const {
  1347. TypedArray<String> warnings = Node::get_configuration_warnings();
  1348. if (!root.is_valid()) {
  1349. warnings.push_back(TTR("No root AnimationNode for the graph is set."));
  1350. }
  1351. if (!has_node(animation_player)) {
  1352. warnings.push_back(TTR("Path to an AnimationPlayer node containing animations is not set."));
  1353. } else {
  1354. AnimationPlayer *player = Object::cast_to<AnimationPlayer>(get_node(animation_player));
  1355. if (!player) {
  1356. warnings.push_back(TTR("Path set for AnimationPlayer does not lead to an AnimationPlayer node."));
  1357. } else if (!player->has_node(player->get_root())) {
  1358. warnings.push_back(TTR("The AnimationPlayer root node is not a valid node."));
  1359. }
  1360. }
  1361. return warnings;
  1362. }
  1363. void AnimationTree::set_root_motion_track(const NodePath &p_track) {
  1364. root_motion_track = p_track;
  1365. }
  1366. NodePath AnimationTree::get_root_motion_track() const {
  1367. return root_motion_track;
  1368. }
  1369. Transform3D AnimationTree::get_root_motion_transform() const {
  1370. return root_motion_transform;
  1371. }
  1372. void AnimationTree::_tree_changed() {
  1373. if (properties_dirty) {
  1374. return;
  1375. }
  1376. call_deferred(SNAME("_update_properties"));
  1377. properties_dirty = true;
  1378. }
  1379. void AnimationTree::_update_properties_for_node(const String &p_base_path, Ref<AnimationNode> node) {
  1380. ERR_FAIL_COND(node.is_null());
  1381. if (!property_parent_map.has(p_base_path)) {
  1382. property_parent_map[p_base_path] = HashMap<StringName, StringName>();
  1383. }
  1384. if (node->get_input_count() && !input_activity_map.has(p_base_path)) {
  1385. Vector<Activity> activity;
  1386. for (int i = 0; i < node->get_input_count(); i++) {
  1387. Activity a;
  1388. a.activity = 0;
  1389. a.last_pass = 0;
  1390. activity.push_back(a);
  1391. }
  1392. input_activity_map[p_base_path] = activity;
  1393. input_activity_map_get[String(p_base_path).substr(0, String(p_base_path).length() - 1)] = &input_activity_map[p_base_path];
  1394. }
  1395. List<PropertyInfo> plist;
  1396. node->get_parameter_list(&plist);
  1397. for (PropertyInfo &pinfo : plist) {
  1398. StringName key = pinfo.name;
  1399. if (!property_map.has(p_base_path + key)) {
  1400. property_map[p_base_path + key] = node->get_parameter_default_value(key);
  1401. }
  1402. property_parent_map[p_base_path][key] = p_base_path + key;
  1403. pinfo.name = p_base_path + key;
  1404. properties.push_back(pinfo);
  1405. }
  1406. List<AnimationNode::ChildNode> children;
  1407. node->get_child_nodes(&children);
  1408. for (const AnimationNode::ChildNode &E : children) {
  1409. _update_properties_for_node(p_base_path + E.name + "/", E.node);
  1410. }
  1411. }
  1412. void AnimationTree::_update_properties() {
  1413. if (!properties_dirty) {
  1414. return;
  1415. }
  1416. properties.clear();
  1417. property_parent_map.clear();
  1418. input_activity_map.clear();
  1419. input_activity_map_get.clear();
  1420. if (root.is_valid()) {
  1421. _update_properties_for_node(SceneStringNames::get_singleton()->parameters_base_path, root);
  1422. }
  1423. properties_dirty = false;
  1424. notify_property_list_changed();
  1425. }
  1426. bool AnimationTree::_set(const StringName &p_name, const Variant &p_value) {
  1427. if (properties_dirty) {
  1428. _update_properties();
  1429. }
  1430. if (property_map.has(p_name)) {
  1431. property_map[p_name] = p_value;
  1432. return true;
  1433. }
  1434. return false;
  1435. }
  1436. bool AnimationTree::_get(const StringName &p_name, Variant &r_ret) const {
  1437. if (properties_dirty) {
  1438. const_cast<AnimationTree *>(this)->_update_properties();
  1439. }
  1440. if (property_map.has(p_name)) {
  1441. r_ret = property_map[p_name];
  1442. return true;
  1443. }
  1444. return false;
  1445. }
  1446. void AnimationTree::_get_property_list(List<PropertyInfo> *p_list) const {
  1447. if (properties_dirty) {
  1448. const_cast<AnimationTree *>(this)->_update_properties();
  1449. }
  1450. for (const PropertyInfo &E : properties) {
  1451. p_list->push_back(E);
  1452. }
  1453. }
  1454. void AnimationTree::rename_parameter(const String &p_base, const String &p_new_base) {
  1455. //rename values first
  1456. for (const PropertyInfo &E : properties) {
  1457. if (E.name.begins_with(p_base)) {
  1458. String new_name = E.name.replace_first(p_base, p_new_base);
  1459. property_map[new_name] = property_map[E.name];
  1460. }
  1461. }
  1462. //update tree second
  1463. properties_dirty = true;
  1464. _update_properties();
  1465. }
  1466. real_t AnimationTree::get_connection_activity(const StringName &p_path, int p_connection) const {
  1467. if (!input_activity_map_get.has(p_path)) {
  1468. return 0;
  1469. }
  1470. const Vector<Activity> *activity = input_activity_map_get[p_path];
  1471. if (!activity || p_connection < 0 || p_connection >= activity->size()) {
  1472. return 0;
  1473. }
  1474. if ((*activity)[p_connection].last_pass != process_pass) {
  1475. return 0;
  1476. }
  1477. return (*activity)[p_connection].activity;
  1478. }
  1479. void AnimationTree::_bind_methods() {
  1480. ClassDB::bind_method(D_METHOD("set_active", "active"), &AnimationTree::set_active);
  1481. ClassDB::bind_method(D_METHOD("is_active"), &AnimationTree::is_active);
  1482. ClassDB::bind_method(D_METHOD("set_tree_root", "root"), &AnimationTree::set_tree_root);
  1483. ClassDB::bind_method(D_METHOD("get_tree_root"), &AnimationTree::get_tree_root);
  1484. ClassDB::bind_method(D_METHOD("set_process_callback", "mode"), &AnimationTree::set_process_callback);
  1485. ClassDB::bind_method(D_METHOD("get_process_callback"), &AnimationTree::get_process_callback);
  1486. ClassDB::bind_method(D_METHOD("set_animation_player", "root"), &AnimationTree::set_animation_player);
  1487. ClassDB::bind_method(D_METHOD("get_animation_player"), &AnimationTree::get_animation_player);
  1488. ClassDB::bind_method(D_METHOD("set_root_motion_track", "path"), &AnimationTree::set_root_motion_track);
  1489. ClassDB::bind_method(D_METHOD("get_root_motion_track"), &AnimationTree::get_root_motion_track);
  1490. ClassDB::bind_method(D_METHOD("get_root_motion_transform"), &AnimationTree::get_root_motion_transform);
  1491. ClassDB::bind_method(D_METHOD("_update_properties"), &AnimationTree::_update_properties);
  1492. ClassDB::bind_method(D_METHOD("rename_parameter", "old_name", "new_name"), &AnimationTree::rename_parameter);
  1493. ClassDB::bind_method(D_METHOD("advance", "delta"), &AnimationTree::advance);
  1494. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "tree_root", PROPERTY_HINT_RESOURCE_TYPE, "AnimationRootNode"), "set_tree_root", "get_tree_root");
  1495. ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "anim_player", PROPERTY_HINT_NODE_PATH_VALID_TYPES, "AnimationPlayer"), "set_animation_player", "get_animation_player");
  1496. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "active"), "set_active", "is_active");
  1497. ADD_PROPERTY(PropertyInfo(Variant::INT, "process_callback", PROPERTY_HINT_ENUM, "Physics,Idle,Manual"), "set_process_callback", "get_process_callback");
  1498. ADD_GROUP("Root Motion", "root_motion_");
  1499. ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "root_motion_track"), "set_root_motion_track", "get_root_motion_track");
  1500. BIND_ENUM_CONSTANT(ANIMATION_PROCESS_PHYSICS);
  1501. BIND_ENUM_CONSTANT(ANIMATION_PROCESS_IDLE);
  1502. BIND_ENUM_CONSTANT(ANIMATION_PROCESS_MANUAL);
  1503. }
  1504. AnimationTree::AnimationTree() {
  1505. }
  1506. AnimationTree::~AnimationTree() {
  1507. }