animation_tree.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317
  1. #include "animation_tree.h"
  2. #include "animation_blend_tree.h"
  3. #include "core/method_bind_ext.gen.inc"
  4. #include "engine.h"
  5. #include "scene/scene_string_names.h"
  6. #include "servers/audio/audio_stream.h"
  7. void AnimationNode::blend_animation(const StringName &p_animation, float p_time, float p_delta, bool p_seeked, float p_blend) {
  8. ERR_FAIL_COND(!state);
  9. ERR_FAIL_COND(!state->player->has_animation(p_animation));
  10. Ref<Animation> animation = state->player->get_animation(p_animation);
  11. if (animation.is_null()) {
  12. Ref<AnimationNodeBlendTree> btree = get_parent();
  13. if (btree.is_valid()) {
  14. String name = btree->get_node_name(Ref<AnimationNodeAnimation>(this));
  15. make_invalid(vformat(RTR("In node '%s', invalid animation: '%s'."), name, p_animation));
  16. } else {
  17. make_invalid(vformat(RTR("Invalid animation: '%s'."), p_animation));
  18. }
  19. return;
  20. }
  21. ERR_FAIL_COND(!animation.is_valid());
  22. AnimationState anim_state;
  23. anim_state.blend = p_blend;
  24. anim_state.track_blends = &blends;
  25. anim_state.delta = p_delta;
  26. anim_state.time = p_time;
  27. anim_state.animation = animation;
  28. anim_state.seeked = p_seeked;
  29. state->animation_states.push_back(anim_state);
  30. }
  31. float AnimationNode::_pre_process(State *p_state, float p_time, bool p_seek) {
  32. state = p_state;
  33. float t = process(p_time, p_seek);
  34. state = NULL;
  35. return t;
  36. }
  37. void AnimationNode::make_invalid(const String &p_reason) {
  38. ERR_FAIL_COND(!state);
  39. state->valid = false;
  40. if (state->invalid_reasons != String()) {
  41. state->invalid_reasons += "\n";
  42. }
  43. state->invalid_reasons += "- " + p_reason;
  44. }
  45. float AnimationNode::blend_input(int p_input, float p_time, bool p_seek, float p_blend, FilterAction p_filter, bool p_optimize) {
  46. ERR_FAIL_INDEX_V(p_input, inputs.size(), 0);
  47. ERR_FAIL_COND_V(!state, 0);
  48. ERR_FAIL_COND_V(!get_tree(), 0); //should not happen, but used to catch bugs
  49. Ref<AnimationNodeBlendTree> tree = get_parent();
  50. if (!tree.is_valid() && get_tree()->get_tree_root().ptr() != this) {
  51. make_invalid(RTR("Can't blend input because node is not in a tree"));
  52. return 0;
  53. }
  54. ERR_FAIL_COND_V(!tree.is_valid(), 0); //should not happen
  55. StringName anim_name = inputs[p_input].connected_to;
  56. Ref<AnimationNode> node = tree->get_node(anim_name);
  57. if (node.is_null()) {
  58. String name = tree->get_node_name(Ref<AnimationNodeAnimation>(this));
  59. make_invalid(vformat(RTR("Nothing connected to input '%s' of node '%s'."), get_input_name(p_input), name));
  60. return 0;
  61. }
  62. inputs[p_input].last_pass = state->last_pass;
  63. return _blend_node(node, p_time, p_seek, p_blend, p_filter, p_optimize, &inputs[p_input].activity);
  64. }
  65. float AnimationNode::blend_node(Ref<AnimationNode> p_node, float p_time, bool p_seek, float p_blend, FilterAction p_filter, bool p_optimize) {
  66. return _blend_node(p_node, p_time, p_seek, p_blend, p_filter, p_optimize);
  67. }
  68. float AnimationNode::_blend_node(Ref<AnimationNode> p_node, float p_time, bool p_seek, float p_blend, FilterAction p_filter, bool p_optimize, float *r_max) {
  69. ERR_FAIL_COND_V(!p_node.is_valid(), 0);
  70. ERR_FAIL_COND_V(!state, 0);
  71. int blend_count = blends.size();
  72. if (p_node->blends.size() != blend_count) {
  73. p_node->blends.resize(blend_count);
  74. }
  75. float *blendw = p_node->blends.ptrw();
  76. const float *blendr = blends.ptr();
  77. bool any_valid = false;
  78. if (has_filter() && is_filter_enabled() && p_filter != FILTER_IGNORE) {
  79. for (int i = 0; i < blend_count; i++) {
  80. blendw[i] = 0.0; //all to zero by default
  81. }
  82. const NodePath *K = NULL;
  83. while ((K = filter.next(K))) {
  84. if (!state->track_map.has(*K)) {
  85. continue;
  86. }
  87. int idx = state->track_map[*K];
  88. blendw[idx] = 1.0; //filtered goes to one
  89. }
  90. switch (p_filter) {
  91. case FILTER_IGNORE:
  92. break; //will not happen anyway
  93. case FILTER_PASS: {
  94. //values filtered pass, the rest dont
  95. for (int i = 0; i < blend_count; i++) {
  96. if (blendw[i] == 0) //not filtered, does not pass
  97. continue;
  98. blendw[i] = blendr[i] * p_blend;
  99. if (blendw[i] > CMP_EPSILON) {
  100. any_valid = true;
  101. }
  102. }
  103. } break;
  104. case FILTER_STOP: {
  105. //values filtered dont pass, the rest are blended
  106. for (int i = 0; i < blend_count; i++) {
  107. if (blendw[i] > 0) //filtered, does not pass
  108. continue;
  109. blendw[i] = blendr[i] * p_blend;
  110. if (blendw[i] > CMP_EPSILON) {
  111. any_valid = true;
  112. }
  113. }
  114. } break;
  115. case FILTER_BLEND: {
  116. //filtered values are blended, the rest are passed without blending
  117. for (int i = 0; i < blend_count; i++) {
  118. if (blendw[i] == 1.0) {
  119. blendw[i] = blendr[i] * p_blend; //filtered, blend
  120. } else {
  121. blendw[i] = blendr[i]; //not filtered, do not blend
  122. }
  123. if (blendw[i] > CMP_EPSILON) {
  124. any_valid = true;
  125. }
  126. }
  127. } break;
  128. }
  129. } else {
  130. for (int i = 0; i < blend_count; i++) {
  131. //regular blend
  132. blendw[i] = blendr[i] * p_blend;
  133. if (blendw[i] > CMP_EPSILON) {
  134. any_valid = true;
  135. }
  136. }
  137. }
  138. if (r_max) {
  139. *r_max = 0;
  140. for (int i = 0; i < blend_count; i++) {
  141. *r_max = MAX(*r_max, blendw[i]);
  142. }
  143. }
  144. if (!p_seek && p_optimize && !any_valid) //pointless to go on, all are zero
  145. return 0;
  146. return p_node->_pre_process(state, p_time, p_seek);
  147. }
  148. int AnimationNode::get_input_count() const {
  149. return inputs.size();
  150. }
  151. String AnimationNode::get_input_name(int p_input) {
  152. ERR_FAIL_INDEX_V(p_input, inputs.size(), String());
  153. return inputs[p_input].name;
  154. }
  155. float AnimationNode::get_input_activity(int p_input) const {
  156. ERR_FAIL_INDEX_V(p_input, inputs.size(), 0);
  157. if (!get_tree())
  158. return 0;
  159. if (get_tree()->get_last_process_pass() != inputs[p_input].last_pass) {
  160. return 0;
  161. }
  162. return inputs[p_input].activity;
  163. }
  164. StringName AnimationNode::get_input_connection(int p_input) {
  165. ERR_FAIL_INDEX_V(p_input, inputs.size(), StringName());
  166. return inputs[p_input].connected_to;
  167. }
  168. void AnimationNode::set_input_connection(int p_input, const StringName &p_connection) {
  169. ERR_FAIL_INDEX(p_input, inputs.size());
  170. inputs[p_input].connected_to = p_connection;
  171. }
  172. String AnimationNode::get_caption() const {
  173. if (get_script_instance()) {
  174. return get_script_instance()->call("get_caption");
  175. }
  176. return "Node";
  177. }
  178. void AnimationNode::add_input(const String &p_name) {
  179. //root nodes cant add inputs
  180. ERR_FAIL_COND(Object::cast_to<AnimationRootNode>(this) != NULL)
  181. Input input;
  182. ERR_FAIL_COND(p_name.find(".") != -1 || p_name.find("/") != -1);
  183. input.name = p_name;
  184. input.activity = 0;
  185. input.last_pass = 0;
  186. inputs.push_back(input);
  187. emit_changed();
  188. }
  189. void AnimationNode::set_input_name(int p_input, const String &p_name) {
  190. ERR_FAIL_INDEX(p_input, inputs.size());
  191. ERR_FAIL_COND(p_name.find(".") != -1 || p_name.find("/") != -1);
  192. inputs[p_input].name = p_name;
  193. emit_changed();
  194. }
  195. void AnimationNode::remove_input(int p_index) {
  196. ERR_FAIL_INDEX(p_index, inputs.size());
  197. inputs.remove(p_index);
  198. emit_changed();
  199. }
  200. void AnimationNode::_set_parent(Object *p_parent) {
  201. set_parent(Object::cast_to<AnimationNode>(p_parent));
  202. }
  203. void AnimationNode::set_parent(AnimationNode *p_parent) {
  204. parent = p_parent; //do not use ref because parent contains children
  205. if (get_script_instance()) {
  206. get_script_instance()->call("_parent_set", p_parent);
  207. }
  208. }
  209. Ref<AnimationNode> AnimationNode::get_parent() const {
  210. if (parent) {
  211. return Ref<AnimationNode>(parent);
  212. }
  213. return Ref<AnimationNode>();
  214. }
  215. AnimationTree *AnimationNode::get_tree() const {
  216. return player;
  217. }
  218. AnimationPlayer *AnimationNode::get_player() const {
  219. ERR_FAIL_COND_V(!state, NULL);
  220. return state->player;
  221. }
  222. float AnimationNode::process(float p_time, bool p_seek) {
  223. if (get_script_instance()) {
  224. return get_script_instance()->call("process", p_time, p_seek);
  225. }
  226. return 0;
  227. }
  228. void AnimationNode::set_filter_path(const NodePath &p_path, bool p_enable) {
  229. if (p_enable) {
  230. filter[p_path] = true;
  231. } else {
  232. filter.erase(p_path);
  233. }
  234. }
  235. void AnimationNode::set_filter_enabled(bool p_enable) {
  236. filter_enabled = p_enable;
  237. }
  238. bool AnimationNode::is_filter_enabled() const {
  239. return filter_enabled;
  240. }
  241. bool AnimationNode::is_path_filtered(const NodePath &p_path) const {
  242. return filter.has(p_path);
  243. }
  244. bool AnimationNode::has_filter() const {
  245. return false;
  246. }
  247. void AnimationNode::set_position(const Vector2 &p_position) {
  248. position = p_position;
  249. }
  250. Vector2 AnimationNode::get_position() const {
  251. return position;
  252. }
  253. void AnimationNode::set_tree(AnimationTree *p_player) {
  254. if (player != NULL && p_player == NULL) {
  255. emit_signal("removed_from_graph");
  256. }
  257. player = p_player;
  258. }
  259. Array AnimationNode::_get_filters() const {
  260. Array paths;
  261. const NodePath *K = NULL;
  262. while ((K = filter.next(K))) {
  263. paths.push_back(String(*K)); //use strings, so sorting is possible
  264. }
  265. paths.sort(); //done so every time the scene is saved, it does not change
  266. return paths;
  267. }
  268. void AnimationNode::_set_filters(const Array &p_filters) {
  269. filter.clear();
  270. for (int i = 0; i < p_filters.size(); i++) {
  271. set_filter_path(p_filters[i], true);
  272. }
  273. }
  274. void AnimationNode::_validate_property(PropertyInfo &property) const {
  275. if (!has_filter() && (property.name == "filter_enabled" || property.name == "filters")) {
  276. property.usage = 0;
  277. }
  278. }
  279. void AnimationNode::_bind_methods() {
  280. ClassDB::bind_method(D_METHOD("get_input_count"), &AnimationNode::get_input_count);
  281. ClassDB::bind_method(D_METHOD("get_input_name", "input"), &AnimationNode::get_input_name);
  282. ClassDB::bind_method(D_METHOD("get_input_connection", "input"), &AnimationNode::get_input_connection);
  283. ClassDB::bind_method(D_METHOD("get_input_activity", "input"), &AnimationNode::get_input_activity);
  284. ClassDB::bind_method(D_METHOD("add_input", "name"), &AnimationNode::add_input);
  285. ClassDB::bind_method(D_METHOD("remove_input", "index"), &AnimationNode::remove_input);
  286. ClassDB::bind_method(D_METHOD("set_filter_path", "path", "enable"), &AnimationNode::set_filter_path);
  287. ClassDB::bind_method(D_METHOD("is_path_filtered", "path"), &AnimationNode::is_path_filtered);
  288. ClassDB::bind_method(D_METHOD("set_filter_enabled", "enable"), &AnimationNode::set_filter_enabled);
  289. ClassDB::bind_method(D_METHOD("is_filter_enabled"), &AnimationNode::is_filter_enabled);
  290. ClassDB::bind_method(D_METHOD("set_position", "position"), &AnimationNode::set_position);
  291. ClassDB::bind_method(D_METHOD("get_position"), &AnimationNode::get_position);
  292. ClassDB::bind_method(D_METHOD("_set_filters", "filters"), &AnimationNode::_set_filters);
  293. ClassDB::bind_method(D_METHOD("_get_filters"), &AnimationNode::_get_filters);
  294. ClassDB::bind_method(D_METHOD("blend_animation", "animation", "time", "delta", "seeked", "blend"), &AnimationNode::blend_animation);
  295. ClassDB::bind_method(D_METHOD("blend_node", "node", "time", "seek", "blend", "filter", "optimize"), &AnimationNode::blend_node, DEFVAL(FILTER_IGNORE), DEFVAL(true));
  296. ClassDB::bind_method(D_METHOD("blend_input", "input_index", "time", "seek", "blend", "filter", "optimize"), &AnimationNode::blend_input, DEFVAL(FILTER_IGNORE), DEFVAL(true));
  297. ClassDB::bind_method(D_METHOD("set_parent", "parent"), &AnimationNode::_set_parent);
  298. ClassDB::bind_method(D_METHOD("get_parent"), &AnimationNode::get_parent);
  299. ClassDB::bind_method(D_METHOD("get_tree"), &AnimationNode::get_tree);
  300. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "filter_enabled", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "set_filter_enabled", "is_filter_enabled");
  301. ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "filters", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL), "_set_filters", "_get_filters");
  302. BIND_VMETHOD(MethodInfo("process", PropertyInfo(Variant::REAL, "time"), PropertyInfo(Variant::BOOL, "seek")));
  303. BIND_VMETHOD(MethodInfo(Variant::STRING, "get_caption"));
  304. BIND_VMETHOD(MethodInfo(Variant::STRING, "has_filter"));
  305. BIND_VMETHOD(MethodInfo("_parent_set", PropertyInfo(Variant::OBJECT, "parent")));
  306. ADD_SIGNAL(MethodInfo("removed_from_graph"));
  307. BIND_ENUM_CONSTANT(FILTER_IGNORE);
  308. BIND_ENUM_CONSTANT(FILTER_PASS);
  309. BIND_ENUM_CONSTANT(FILTER_STOP);
  310. BIND_ENUM_CONSTANT(FILTER_BLEND);
  311. }
  312. AnimationNode::AnimationNode() {
  313. state = NULL;
  314. parent = NULL;
  315. player = NULL;
  316. set_local_to_scene(true);
  317. filter_enabled = false;
  318. }
  319. ////////////////////
  320. void AnimationTree::set_tree_root(const Ref<AnimationNode> &p_root) {
  321. if (root.is_valid()) {
  322. root->set_tree(NULL);
  323. }
  324. if (p_root.is_valid()) {
  325. ERR_EXPLAIN("root node already set to another player");
  326. ERR_FAIL_COND(p_root->player);
  327. }
  328. root = p_root;
  329. if (root.is_valid()) {
  330. root->set_tree(this);
  331. }
  332. update_configuration_warning();
  333. }
  334. Ref<AnimationNode> AnimationTree::get_tree_root() const {
  335. return root;
  336. }
  337. void AnimationTree::set_active(bool p_active) {
  338. if (active == p_active)
  339. return;
  340. active = p_active;
  341. started = active;
  342. if (process_mode == ANIMATION_PROCESS_IDLE) {
  343. set_process_internal(active);
  344. } else {
  345. set_physics_process_internal(active);
  346. }
  347. if (!active && is_inside_tree()) {
  348. for (Set<TrackCache *>::Element *E = playing_caches.front(); E; E = E->next()) {
  349. if (ObjectDB::get_instance(E->get()->object_id)) {
  350. E->get()->object->call("stop");
  351. }
  352. }
  353. playing_caches.clear();
  354. }
  355. }
  356. bool AnimationTree::is_active() const {
  357. return active;
  358. }
  359. void AnimationTree::set_process_mode(AnimationProcessMode p_mode) {
  360. if (process_mode == p_mode)
  361. return;
  362. bool was_active = is_active();
  363. if (was_active) {
  364. set_active(false);
  365. }
  366. process_mode = p_mode;
  367. if (was_active) {
  368. set_active(true);
  369. }
  370. }
  371. AnimationTree::AnimationProcessMode AnimationTree::get_process_mode() const {
  372. return process_mode;
  373. }
  374. void AnimationTree::_node_removed(Node *p_node) {
  375. cache_valid = false;
  376. }
  377. bool AnimationTree::_update_caches(AnimationPlayer *player) {
  378. setup_pass++;
  379. if (!player->has_node(player->get_root())) {
  380. ERR_PRINT("AnimationTree: AnimationPlayer root is invalid.");
  381. set_active(false);
  382. return false;
  383. }
  384. Node *parent = player->get_node(player->get_root());
  385. List<StringName> sname;
  386. player->get_animation_list(&sname);
  387. for (List<StringName>::Element *E = sname.front(); E; E = E->next()) {
  388. Ref<Animation> anim = player->get_animation(E->get());
  389. for (int i = 0; i < anim->get_track_count(); i++) {
  390. NodePath path = anim->track_get_path(i);
  391. Animation::TrackType track_type = anim->track_get_type(i);
  392. TrackCache *track = NULL;
  393. if (track_cache.has(path)) {
  394. track = track_cache.get(path);
  395. }
  396. //if not valid, delete track
  397. if (track && (track->type != track_type || ObjectDB::get_instance(track->object_id) == NULL)) {
  398. playing_caches.erase(track);
  399. memdelete(track);
  400. track_cache.erase(path);
  401. track = NULL;
  402. }
  403. if (!track) {
  404. RES resource;
  405. Vector<StringName> leftover_path;
  406. Node *child = parent->get_node_and_resource(path, resource, leftover_path);
  407. if (!child) {
  408. ERR_PRINTS("AnimationTree: '" + String(E->get()) + "', couldn't resolve track: '" + String(path) + "'");
  409. continue;
  410. }
  411. if (!child->is_connected("tree_exited", this, "_node_removed")) {
  412. child->connect("tree_exited", this, "_node_removed", varray(child));
  413. }
  414. switch (track_type) {
  415. case Animation::TYPE_VALUE: {
  416. TrackCacheValue *track_value = memnew(TrackCacheValue);
  417. if (resource.is_valid()) {
  418. track_value->object = resource.ptr();
  419. } else {
  420. track_value->object = child;
  421. }
  422. track_value->subpath = leftover_path;
  423. track_value->object_id = track_value->object->get_instance_id();
  424. track = track_value;
  425. } break;
  426. case Animation::TYPE_TRANSFORM: {
  427. Spatial *spatial = Object::cast_to<Spatial>(child);
  428. if (!spatial) {
  429. ERR_PRINTS("AnimationTree: '" + String(E->get()) + "', transform track does not point to spatial: '" + String(path) + "'");
  430. continue;
  431. }
  432. TrackCacheTransform *track_xform = memnew(TrackCacheTransform);
  433. track_xform->spatial = spatial;
  434. track_xform->skeleton = NULL;
  435. track_xform->bone_idx = -1;
  436. if (path.get_subname_count() == 1 && Object::cast_to<Skeleton>(spatial)) {
  437. Skeleton *sk = Object::cast_to<Skeleton>(spatial);
  438. int bone_idx = sk->find_bone(path.get_subname(0));
  439. if (bone_idx != -1 && !sk->is_bone_ignore_animation(bone_idx)) {
  440. track_xform->skeleton = sk;
  441. track_xform->bone_idx = bone_idx;
  442. }
  443. }
  444. track_xform->object = spatial;
  445. track_xform->object_id = track_xform->object->get_instance_id();
  446. track = track_xform;
  447. } break;
  448. case Animation::TYPE_METHOD: {
  449. TrackCacheMethod *track_method = memnew(TrackCacheMethod);
  450. if (resource.is_valid()) {
  451. track_method->object = resource.ptr();
  452. } else {
  453. track_method->object = child;
  454. }
  455. track_method->object_id = track_method->object->get_instance_id();
  456. track = track_method;
  457. } break;
  458. case Animation::TYPE_BEZIER: {
  459. TrackCacheBezier *track_bezier = memnew(TrackCacheBezier);
  460. if (resource.is_valid()) {
  461. track_bezier->object = resource.ptr();
  462. } else {
  463. track_bezier->object = child;
  464. }
  465. track_bezier->subpath = leftover_path;
  466. track_bezier->object_id = track_bezier->object->get_instance_id();
  467. track = track_bezier;
  468. } break;
  469. case Animation::TYPE_AUDIO: {
  470. TrackCacheAudio *track_audio = memnew(TrackCacheAudio);
  471. track_audio->object = child;
  472. track_audio->object_id = track_audio->object->get_instance_id();
  473. track = track_audio;
  474. } break;
  475. case Animation::TYPE_ANIMATION: {
  476. TrackCacheAnimation *track_animation = memnew(TrackCacheAnimation);
  477. track_animation->object = child;
  478. track_animation->object_id = track_animation->object->get_instance_id();
  479. track = track_animation;
  480. } break;
  481. }
  482. track_cache[path] = track;
  483. }
  484. track->setup_pass = setup_pass;
  485. }
  486. }
  487. List<NodePath> to_delete;
  488. const NodePath *K = NULL;
  489. while ((K = track_cache.next(K))) {
  490. TrackCache *tc = track_cache[*K];
  491. if (tc->setup_pass != setup_pass) {
  492. to_delete.push_back(*K);
  493. }
  494. }
  495. while (to_delete.front()) {
  496. NodePath np = to_delete.front()->get();
  497. memdelete(track_cache[np]);
  498. track_cache.erase(np);
  499. to_delete.pop_front();
  500. }
  501. state.track_map.clear();
  502. K = NULL;
  503. int idx = 0;
  504. while ((K = track_cache.next(K))) {
  505. state.track_map[*K] = idx;
  506. idx++;
  507. }
  508. state.track_count = idx;
  509. cache_valid = true;
  510. return true;
  511. }
  512. void AnimationTree::_clear_caches() {
  513. const NodePath *K = NULL;
  514. while ((K = track_cache.next(K))) {
  515. memdelete(track_cache[*K]);
  516. }
  517. playing_caches.clear();
  518. track_cache.clear();
  519. cache_valid = false;
  520. }
  521. void AnimationTree::_process_graph(float p_delta) {
  522. //check all tracks, see if they need modification
  523. root_motion_transform = Transform();
  524. if (!root.is_valid()) {
  525. ERR_PRINT("AnimationTree: root AnimationNode is not set, disabling playback.");
  526. set_active(false);
  527. cache_valid = false;
  528. return;
  529. }
  530. if (!has_node(animation_player)) {
  531. ERR_PRINT("AnimationTree: no valid AnimationPlayer path set, disabling playback");
  532. set_active(false);
  533. cache_valid = false;
  534. return;
  535. }
  536. AnimationPlayer *player = Object::cast_to<AnimationPlayer>(get_node(animation_player));
  537. if (!player) {
  538. ERR_PRINT("AnimationTree: path points to a node not an AnimationPlayer, disabling playback");
  539. set_active(false);
  540. cache_valid = false;
  541. return;
  542. }
  543. if (!cache_valid) {
  544. if (!_update_caches(player)) {
  545. return;
  546. }
  547. }
  548. { //setup
  549. process_pass++;
  550. state.valid = true;
  551. state.invalid_reasons = "";
  552. state.animation_states.clear(); //will need to be re-created
  553. state.valid = true;
  554. state.player = player;
  555. state.last_pass = process_pass;
  556. // root source blends
  557. root->blends.resize(state.track_count);
  558. float *src_blendsw = root->blends.ptrw();
  559. for (int i = 0; i < state.track_count; i++) {
  560. src_blendsw[i] = 1.0; //by default all go to 1 for the root input
  561. }
  562. }
  563. //process
  564. {
  565. if (started) {
  566. //if started, seek
  567. root->_pre_process(&state, 0, true);
  568. started = false;
  569. }
  570. root->_pre_process(&state, p_delta, false);
  571. }
  572. if (!state.valid) {
  573. return; //state is not valid. do nothing.
  574. }
  575. //apply value/transform/bezier blends to track caches and execute method/audio/animation tracks
  576. {
  577. bool can_call = is_inside_tree() && !Engine::get_singleton()->is_editor_hint();
  578. for (List<AnimationNode::AnimationState>::Element *E = state.animation_states.front(); E; E = E->next()) {
  579. const AnimationNode::AnimationState &as = E->get();
  580. Ref<Animation> a = as.animation;
  581. float time = as.time;
  582. float delta = as.delta;
  583. bool seeked = as.seeked;
  584. for (int i = 0; i < a->get_track_count(); i++) {
  585. NodePath path = a->track_get_path(i);
  586. TrackCache *track = track_cache[path];
  587. if (track->type != a->track_get_type(i)) {
  588. continue; //may happen should not
  589. }
  590. track->root_motion = root_motion_track == path;
  591. ERR_CONTINUE(!state.track_map.has(path));
  592. int blend_idx = state.track_map[path];
  593. ERR_CONTINUE(blend_idx < 0 || blend_idx >= state.track_count);
  594. float blend = (*as.track_blends)[blend_idx];
  595. if (blend < CMP_EPSILON)
  596. continue; //nothing to blend
  597. switch (track->type) {
  598. case Animation::TYPE_TRANSFORM: {
  599. TrackCacheTransform *t = static_cast<TrackCacheTransform *>(track);
  600. if (t->process_pass != process_pass) {
  601. t->process_pass = process_pass;
  602. t->loc = Vector3();
  603. t->rot = Quat();
  604. t->rot_blend_accum = 0;
  605. t->scale = Vector3();
  606. }
  607. if (track->root_motion) {
  608. float prev_time = time - delta;
  609. if (prev_time < 0) {
  610. if (!a->has_loop()) {
  611. prev_time = 0;
  612. } else {
  613. prev_time = a->get_length() + prev_time;
  614. }
  615. }
  616. Vector3 loc[2];
  617. Quat rot[2];
  618. Vector3 scale[2];
  619. if (prev_time > time) {
  620. Error err = a->transform_track_interpolate(i, prev_time, &loc[0], &rot[0], &scale[0]);
  621. if (err != OK) {
  622. continue;
  623. }
  624. a->transform_track_interpolate(i, a->get_length(), &loc[1], &rot[1], &scale[1]);
  625. t->loc += (loc[1] - loc[0]) * blend;
  626. t->scale += (scale[1] - scale[0]) * blend;
  627. Quat q = Quat().slerp(rot[0].normalized().inverse() * rot[1].normalized(), blend).normalized();
  628. t->rot = (t->rot * q).normalized();
  629. prev_time = 0;
  630. }
  631. Error err = a->transform_track_interpolate(i, prev_time, &loc[0], &rot[0], &scale[0]);
  632. if (err != OK) {
  633. continue;
  634. }
  635. a->transform_track_interpolate(i, time, &loc[1], &rot[1], &scale[1]);
  636. t->loc += (loc[1] - loc[0]) * blend;
  637. t->scale += (scale[1] - scale[0]) * blend;
  638. Quat q = Quat().slerp(rot[0].normalized().inverse() * rot[1].normalized(), blend).normalized();
  639. t->rot = (t->rot * q).normalized();
  640. prev_time = 0;
  641. } else {
  642. Vector3 loc;
  643. Quat rot;
  644. Vector3 scale;
  645. Error err = a->transform_track_interpolate(i, time, &loc, &rot, &scale);
  646. //ERR_CONTINUE(err!=OK); //used for testing, should be removed
  647. scale -= Vector3(1.0, 1.0, 1.0); //helps make it work properly with Add nodes
  648. if (err != OK)
  649. continue;
  650. t->loc = t->loc.linear_interpolate(loc, blend);
  651. if (t->rot_blend_accum==0) {
  652. t->rot = rot;
  653. t->rot_blend_accum = blend;
  654. } else {
  655. float rot_total = t->rot_blend_accum + blend;
  656. t->rot = rot.slerp(t->rot, t->rot_blend_accum / rot_total).normalized();
  657. t->rot_blend_accum = rot_total;
  658. }
  659. t->scale = t->scale.linear_interpolate(scale, blend);
  660. }
  661. } break;
  662. case Animation::TYPE_VALUE: {
  663. TrackCacheValue *t = static_cast<TrackCacheValue *>(track);
  664. Animation::UpdateMode update_mode = a->value_track_get_update_mode(i);
  665. if (update_mode == Animation::UPDATE_CONTINUOUS || update_mode == Animation::UPDATE_CAPTURE) { //delta == 0 means seek
  666. Variant value = a->value_track_interpolate(i, time);
  667. if (value == Variant())
  668. continue;
  669. if (t->process_pass != process_pass) {
  670. Variant::CallError ce;
  671. t->value = Variant::construct(value.get_type(), NULL, 0, ce); //reset
  672. t->process_pass = process_pass;
  673. }
  674. Variant::interpolate(t->value, value, blend, t->value);
  675. } else if (delta != 0) {
  676. List<int> indices;
  677. a->value_track_get_key_indices(i, time, delta, &indices);
  678. for (List<int>::Element *F = indices.front(); F; F = F->next()) {
  679. Variant value = a->track_get_key_value(i, F->get());
  680. t->object->set_indexed(t->subpath, value);
  681. }
  682. }
  683. } break;
  684. case Animation::TYPE_METHOD: {
  685. if (delta == 0) {
  686. continue;
  687. }
  688. TrackCacheMethod *t = static_cast<TrackCacheMethod *>(track);
  689. List<int> indices;
  690. a->method_track_get_key_indices(i, time, delta, &indices);
  691. for (List<int>::Element *E = indices.front(); E; E = E->next()) {
  692. StringName method = a->method_track_get_name(i, E->get());
  693. Vector<Variant> params = a->method_track_get_params(i, E->get());
  694. int s = params.size();
  695. ERR_CONTINUE(s > VARIANT_ARG_MAX);
  696. if (can_call) {
  697. t->object->call_deferred(
  698. method,
  699. s >= 1 ? params[0] : Variant(),
  700. s >= 2 ? params[1] : Variant(),
  701. s >= 3 ? params[2] : Variant(),
  702. s >= 4 ? params[3] : Variant(),
  703. s >= 5 ? params[4] : Variant());
  704. }
  705. }
  706. } break;
  707. case Animation::TYPE_BEZIER: {
  708. TrackCacheBezier *t = static_cast<TrackCacheBezier *>(track);
  709. float bezier = a->bezier_track_interpolate(i, time);
  710. if (t->process_pass != process_pass) {
  711. t->value = 0;
  712. t->process_pass = process_pass;
  713. }
  714. t->value = Math::lerp(t->value, bezier, blend);
  715. } break;
  716. case Animation::TYPE_AUDIO: {
  717. TrackCacheAudio *t = static_cast<TrackCacheAudio *>(track);
  718. if (seeked) {
  719. //find whathever should be playing
  720. int idx = a->track_find_key(i, time);
  721. if (idx < 0)
  722. continue;
  723. Ref<AudioStream> stream = a->audio_track_get_key_stream(i, idx);
  724. if (!stream.is_valid()) {
  725. t->object->call("stop");
  726. t->playing = false;
  727. playing_caches.erase(t);
  728. } else {
  729. float start_ofs = a->audio_track_get_key_start_offset(i, idx);
  730. start_ofs += time - a->track_get_key_time(i, idx);
  731. float end_ofs = a->audio_track_get_key_end_offset(i, idx);
  732. float len = stream->get_length();
  733. if (start_ofs > len - end_ofs) {
  734. t->object->call("stop");
  735. t->playing = false;
  736. playing_caches.erase(t);
  737. continue;
  738. }
  739. t->object->call("set_stream", stream);
  740. t->object->call("play", start_ofs);
  741. t->playing = true;
  742. playing_caches.insert(t);
  743. if (len && end_ofs > 0) { //force a end at a time
  744. t->len = len - start_ofs - end_ofs;
  745. } else {
  746. t->len = 0;
  747. }
  748. t->start = time;
  749. }
  750. } else {
  751. //find stuff to play
  752. List<int> to_play;
  753. a->track_get_key_indices_in_range(i, time, delta, &to_play);
  754. if (to_play.size()) {
  755. int idx = to_play.back()->get();
  756. Ref<AudioStream> stream = a->audio_track_get_key_stream(i, idx);
  757. if (!stream.is_valid()) {
  758. t->object->call("stop");
  759. t->playing = false;
  760. playing_caches.erase(t);
  761. } else {
  762. float start_ofs = a->audio_track_get_key_start_offset(i, idx);
  763. float end_ofs = a->audio_track_get_key_end_offset(i, idx);
  764. float len = stream->get_length();
  765. t->object->call("set_stream", stream);
  766. t->object->call("play", start_ofs);
  767. t->playing = true;
  768. playing_caches.insert(t);
  769. if (len && end_ofs > 0) { //force a end at a time
  770. t->len = len - start_ofs - end_ofs;
  771. } else {
  772. t->len = 0;
  773. }
  774. t->start = time;
  775. }
  776. } else if (t->playing) {
  777. if (t->start > time || (t->len > 0 && time - t->start < t->len)) {
  778. //time to stop
  779. t->object->call("stop");
  780. t->playing = false;
  781. playing_caches.erase(t);
  782. }
  783. }
  784. }
  785. } break;
  786. case Animation::TYPE_ANIMATION: {
  787. TrackCacheAnimation *t = static_cast<TrackCacheAnimation *>(track);
  788. AnimationPlayer *player = Object::cast_to<AnimationPlayer>(t->object);
  789. if (!player)
  790. continue;
  791. if (delta == 0 || seeked) {
  792. //seek
  793. int idx = a->track_find_key(i, time);
  794. if (idx < 0)
  795. continue;
  796. float pos = a->track_get_key_time(i, idx);
  797. StringName anim_name = a->animation_track_get_key_animation(i, idx);
  798. if (String(anim_name) == "[stop]" || !player->has_animation(anim_name))
  799. continue;
  800. Ref<Animation> anim = player->get_animation(anim_name);
  801. float at_anim_pos;
  802. if (anim->has_loop()) {
  803. at_anim_pos = Math::fposmod(time - pos, anim->get_length()); //seek to loop
  804. } else {
  805. at_anim_pos = MAX(anim->get_length(), time - pos); //seek to end
  806. }
  807. if (player->is_playing() || seeked) {
  808. player->play(anim_name);
  809. player->seek(at_anim_pos);
  810. t->playing = true;
  811. playing_caches.insert(t);
  812. } else {
  813. player->set_assigned_animation(anim_name);
  814. player->seek(at_anim_pos, true);
  815. }
  816. } else {
  817. //find stuff to play
  818. List<int> to_play;
  819. a->track_get_key_indices_in_range(i, time, delta, &to_play);
  820. if (to_play.size()) {
  821. int idx = to_play.back()->get();
  822. StringName anim_name = a->animation_track_get_key_animation(i, idx);
  823. if (String(anim_name) == "[stop]" || !player->has_animation(anim_name)) {
  824. if (playing_caches.has(t)) {
  825. playing_caches.erase(t);
  826. player->stop();
  827. t->playing = false;
  828. }
  829. } else {
  830. player->play(anim_name);
  831. t->playing = true;
  832. playing_caches.insert(t);
  833. }
  834. }
  835. }
  836. } break;
  837. }
  838. }
  839. }
  840. }
  841. {
  842. // finally, set the tracks
  843. const NodePath *K = NULL;
  844. while ((K = track_cache.next(K))) {
  845. TrackCache *track = track_cache[*K];
  846. if (track->process_pass != process_pass)
  847. continue; //not processed, ignore
  848. switch (track->type) {
  849. case Animation::TYPE_TRANSFORM: {
  850. TrackCacheTransform *t = static_cast<TrackCacheTransform *>(track);
  851. Transform xform;
  852. xform.origin = t->loc;
  853. t->scale += Vector3(1.0, 1.0, 1.0); //helps make it work properly with Add nodes and root motion
  854. xform.basis.set_quat_scale(t->rot, t->scale);
  855. if (t->root_motion) {
  856. root_motion_transform = xform;
  857. if (t->skeleton && t->bone_idx >= 0) {
  858. root_motion_transform = (t->skeleton->get_bone_rest(t->bone_idx) * root_motion_transform) * t->skeleton->get_bone_rest(t->bone_idx).affine_inverse();
  859. }
  860. } else if (t->skeleton && t->bone_idx >= 0) {
  861. t->skeleton->set_bone_pose(t->bone_idx, xform);
  862. } else {
  863. t->spatial->set_transform(xform);
  864. }
  865. } break;
  866. case Animation::TYPE_VALUE: {
  867. TrackCacheValue *t = static_cast<TrackCacheValue *>(track);
  868. t->object->set_indexed(t->subpath, t->value);
  869. } break;
  870. case Animation::TYPE_BEZIER: {
  871. TrackCacheBezier *t = static_cast<TrackCacheBezier *>(track);
  872. t->object->set_indexed(t->subpath, t->value);
  873. } break;
  874. default: {} //the rest dont matter
  875. }
  876. }
  877. }
  878. }
  879. void AnimationTree::_notification(int p_what) {
  880. if (active && p_what == NOTIFICATION_INTERNAL_PHYSICS_PROCESS && process_mode == ANIMATION_PROCESS_PHYSICS) {
  881. _process_graph(get_physics_process_delta_time());
  882. }
  883. if (active && p_what == NOTIFICATION_INTERNAL_PROCESS && process_mode == ANIMATION_PROCESS_IDLE) {
  884. _process_graph(get_process_delta_time());
  885. }
  886. if (p_what == NOTIFICATION_EXIT_TREE) {
  887. _clear_caches();
  888. }
  889. }
  890. void AnimationTree::set_animation_player(const NodePath &p_player) {
  891. animation_player = p_player;
  892. update_configuration_warning();
  893. }
  894. NodePath AnimationTree::get_animation_player() const {
  895. return animation_player;
  896. }
  897. bool AnimationTree::is_state_invalid() const {
  898. return !state.valid;
  899. }
  900. String AnimationTree::get_invalid_state_reason() const {
  901. return state.invalid_reasons;
  902. }
  903. uint64_t AnimationTree::get_last_process_pass() const {
  904. return process_pass;
  905. }
  906. String AnimationTree::get_configuration_warning() const {
  907. String warning = Node::get_configuration_warning();
  908. if (!root.is_valid()) {
  909. if (warning != String()) {
  910. warning += "\n";
  911. }
  912. warning += TTR("A root AnimationNode for the graph is not set.");
  913. }
  914. if (!has_node(animation_player)) {
  915. if (warning != String()) {
  916. warning += "\n";
  917. }
  918. warning += TTR("Path to an AnimationPlayer node containing animations is not set.");
  919. return warning;
  920. }
  921. AnimationPlayer *player = Object::cast_to<AnimationPlayer>(get_node(animation_player));
  922. if (!player) {
  923. if (warning != String()) {
  924. warning += "\n";
  925. }
  926. warning += TTR("Path set for AnimationPlayer does not lead to an AnimationPlayer node.");
  927. return warning;
  928. }
  929. if (!player->has_node(player->get_root())) {
  930. if (warning != String()) {
  931. warning += "\n";
  932. }
  933. warning += TTR("AnimationPlayer root is not a valid node.");
  934. return warning;
  935. }
  936. return warning;
  937. }
  938. void AnimationTree::set_root_motion_track(const NodePath &p_track) {
  939. root_motion_track = p_track;
  940. }
  941. NodePath AnimationTree::get_root_motion_track() const {
  942. return root_motion_track;
  943. }
  944. Transform AnimationTree::get_root_motion_transform() const {
  945. return root_motion_transform;
  946. }
  947. void AnimationTree::_bind_methods() {
  948. ClassDB::bind_method(D_METHOD("set_active", "active"), &AnimationTree::set_active);
  949. ClassDB::bind_method(D_METHOD("is_active"), &AnimationTree::is_active);
  950. ClassDB::bind_method(D_METHOD("set_tree_root", "root"), &AnimationTree::set_tree_root);
  951. ClassDB::bind_method(D_METHOD("get_tree_root"), &AnimationTree::get_tree_root);
  952. ClassDB::bind_method(D_METHOD("set_process_mode", "mode"), &AnimationTree::set_process_mode);
  953. ClassDB::bind_method(D_METHOD("get_process_mode"), &AnimationTree::get_process_mode);
  954. ClassDB::bind_method(D_METHOD("set_animation_player", "root"), &AnimationTree::set_animation_player);
  955. ClassDB::bind_method(D_METHOD("get_animation_player"), &AnimationTree::get_animation_player);
  956. ClassDB::bind_method(D_METHOD("set_root_motion_track", "path"), &AnimationTree::set_root_motion_track);
  957. ClassDB::bind_method(D_METHOD("get_root_motion_track"), &AnimationTree::get_root_motion_track);
  958. ClassDB::bind_method(D_METHOD("get_root_motion_transform"), &AnimationTree::get_root_motion_transform);
  959. ClassDB::bind_method(D_METHOD("_node_removed"), &AnimationTree::_node_removed);
  960. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "tree_root", PROPERTY_HINT_RESOURCE_TYPE, "AnimationRootNode", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_DO_NOT_SHARE_ON_DUPLICATE), "set_tree_root", "get_tree_root");
  961. ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "anim_player",PROPERTY_HINT_NODE_PATH_VALID_TYPES,"AnimationPlayer"), "set_animation_player", "get_animation_player");
  962. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "active"), "set_active", "is_active");
  963. ADD_PROPERTY(PropertyInfo(Variant::INT, "process_mode", PROPERTY_HINT_ENUM, "Physics,Idle"), "set_process_mode", "get_process_mode");
  964. ADD_GROUP("Root Motion", "root_motion_");
  965. ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "root_motion_track"), "set_root_motion_track", "get_root_motion_track");
  966. }
  967. AnimationTree::AnimationTree() {
  968. process_mode = ANIMATION_PROCESS_IDLE;
  969. active = false;
  970. cache_valid = false;
  971. setup_pass = 1;
  972. started = true;
  973. }
  974. AnimationTree::~AnimationTree() {
  975. if (root.is_valid()) {
  976. root->player = NULL;
  977. }
  978. }