snapshot_data.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. /**************************************************************************/
  2. /* snapshot_data.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  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 "snapshot_data.h"
  31. #include "core/core_bind.h"
  32. #include "core/io/compression.h"
  33. #include "core/object/script_language.h"
  34. #include "scene/debugger/scene_debugger.h"
  35. #if defined(MODULE_GDSCRIPT_ENABLED) && defined(DEBUG_ENABLED)
  36. #include "modules/gdscript/gdscript.h"
  37. #endif
  38. SnapshotDataObject::SnapshotDataObject(SceneDebuggerObject &p_obj, GameStateSnapshot *p_snapshot, ResourceCache &resource_cache) :
  39. snapshot(p_snapshot) {
  40. remote_object_id = p_obj.id;
  41. type_name = p_obj.class_name;
  42. for (const SceneDebuggerObject::SceneDebuggerProperty &prop : p_obj.properties) {
  43. PropertyInfo pinfo = prop.first;
  44. Variant pvalue = prop.second;
  45. if (pinfo.type == Variant::OBJECT && pvalue.is_string()) {
  46. String path = pvalue;
  47. // If a resource is followed by a ::, it is a nested resource (like a sub_resource in a .tscn file).
  48. // To get a reference to it, first we load the parent resource (the .tscn, for example), then,
  49. // we load the child resource. The parent resource (dependency) should not be destroyed before the child
  50. // resource (pvalue) is loaded.
  51. if (path.is_resource_file()) {
  52. // Built-in resource.
  53. String base_path = path.get_slice("::", 0);
  54. if (!resource_cache.cache.has(base_path)) {
  55. resource_cache.cache[base_path] = ResourceLoader::load(base_path);
  56. resource_cache.misses++;
  57. } else {
  58. resource_cache.hits++;
  59. }
  60. }
  61. if (!resource_cache.cache.has(path)) {
  62. resource_cache.cache[path] = ResourceLoader::load(path);
  63. resource_cache.misses++;
  64. } else {
  65. resource_cache.hits++;
  66. }
  67. pvalue = resource_cache.cache[path];
  68. if (pinfo.hint_string == "Script") {
  69. if (get_script() != pvalue) {
  70. set_script(Ref<RefCounted>());
  71. Ref<Script> scr(pvalue);
  72. if (scr.is_valid()) {
  73. ScriptInstance *scr_instance = scr->placeholder_instance_create(this);
  74. if (scr_instance) {
  75. set_script_instance(scr_instance);
  76. }
  77. }
  78. }
  79. }
  80. }
  81. prop_list.push_back(pinfo);
  82. prop_values[pinfo.name] = pvalue;
  83. }
  84. }
  85. bool SnapshotDataObject::_get(const StringName &p_name, Variant &r_ret) const {
  86. String name = p_name;
  87. if (name.begins_with("Metadata/")) {
  88. name = name.replace_first("Metadata/", "metadata/");
  89. }
  90. if (!prop_values.has(name)) {
  91. return false;
  92. }
  93. r_ret = prop_values[p_name];
  94. return true;
  95. }
  96. void SnapshotDataObject::_get_property_list(List<PropertyInfo> *p_list) const {
  97. p_list->clear(); // Sorry, don't want any categories.
  98. for (const PropertyInfo &prop : prop_list) {
  99. if (prop.name == "script") {
  100. // Skip the script property, it's always added by the non-virtual method.
  101. continue;
  102. }
  103. p_list->push_back(prop);
  104. }
  105. }
  106. void SnapshotDataObject::_bind_methods() {
  107. ClassDB::bind_method(D_METHOD("_is_read_only"), &SnapshotDataObject::_is_read_only);
  108. }
  109. String SnapshotDataObject::get_node_path() {
  110. if (!is_node()) {
  111. return "";
  112. }
  113. SnapshotDataObject *current = this;
  114. String path;
  115. while (true) {
  116. String current_node_name = current->extra_debug_data["node_name"];
  117. if (current_node_name != "") {
  118. if (path != "") {
  119. path = current_node_name + "/" + path;
  120. } else {
  121. path = current_node_name;
  122. }
  123. }
  124. if (!current->extra_debug_data.has("node_parent")) {
  125. break;
  126. }
  127. current = snapshot->objects[current->extra_debug_data["node_parent"]];
  128. }
  129. return path;
  130. }
  131. String SnapshotDataObject::_get_script_name(Ref<Script> p_script) {
  132. #if defined(MODULE_GDSCRIPT_ENABLED) && defined(DEBUG_ENABLED)
  133. // GDScripts have more specific names than base scripts, so use those names if possible.
  134. return GDScript::debug_get_script_name(p_script);
  135. #else
  136. // Otherwise fallback to the base script's name.
  137. return p_script->get_global_name();
  138. #endif
  139. }
  140. String SnapshotDataObject::get_name() {
  141. String found_type_name = type_name;
  142. // Ideally, we will name it after the script attached to it.
  143. Ref<Script> maybe_script = get_script();
  144. if (maybe_script.is_valid()) {
  145. String full_name;
  146. while (maybe_script.is_valid()) {
  147. String global_name = _get_script_name(maybe_script);
  148. if (global_name != "") {
  149. if (full_name != "") {
  150. full_name = global_name + "/" + full_name;
  151. } else {
  152. full_name = global_name;
  153. }
  154. }
  155. maybe_script = maybe_script->get_base_script().ptr();
  156. }
  157. found_type_name = type_name + "/" + full_name;
  158. }
  159. return found_type_name + "_" + uitos(remote_object_id);
  160. }
  161. bool SnapshotDataObject::is_refcounted() {
  162. return is_class(RefCounted::get_class_static());
  163. }
  164. bool SnapshotDataObject::is_node() {
  165. return is_class(Node::get_class_static());
  166. }
  167. bool SnapshotDataObject::is_class(const String &p_base_class) {
  168. return ClassDB::is_parent_class(type_name, p_base_class);
  169. }
  170. HashSet<ObjectID> SnapshotDataObject::_unique_references(const HashMap<String, ObjectID> &p_refs) {
  171. HashSet<ObjectID> obj_set;
  172. for (const KeyValue<String, ObjectID> &pair : p_refs) {
  173. obj_set.insert(pair.value);
  174. }
  175. return obj_set;
  176. }
  177. HashSet<ObjectID> SnapshotDataObject::get_unique_outbound_refernces() {
  178. return _unique_references(outbound_references);
  179. }
  180. HashSet<ObjectID> SnapshotDataObject::get_unique_inbound_references() {
  181. return _unique_references(inbound_references);
  182. }
  183. void GameStateSnapshot::_get_outbound_references(Variant &p_var, HashMap<String, ObjectID> &r_ret_val, const String &p_current_path) {
  184. String path_divider = p_current_path.size() > 0 ? "/" : ""; // Make sure we don't start with a /.
  185. switch (p_var.get_type()) {
  186. case Variant::Type::INT:
  187. case Variant::Type::OBJECT: { // Means ObjectID.
  188. ObjectID as_id = ObjectID((uint64_t)p_var);
  189. if (!objects.has(as_id)) {
  190. return;
  191. }
  192. r_ret_val[p_current_path] = as_id;
  193. break;
  194. }
  195. case Variant::Type::DICTIONARY: {
  196. Dictionary dict = (Dictionary)p_var;
  197. LocalVector<Variant> keys = dict.get_key_list();
  198. for (Variant &k : keys) {
  199. // The dictionary key _could be_ an object. If it is, we name the key property with the same name as the value, but with _key appended to it.
  200. _get_outbound_references(k, r_ret_val, p_current_path + path_divider + (String)k + "_key");
  201. Variant v = dict.get(k, Variant());
  202. _get_outbound_references(v, r_ret_val, p_current_path + path_divider + (String)k);
  203. }
  204. break;
  205. }
  206. case Variant::Type::ARRAY: {
  207. Array arr = (Array)p_var;
  208. int i = 0;
  209. for (Variant &v : arr) {
  210. _get_outbound_references(v, r_ret_val, p_current_path + path_divider + itos(i));
  211. i++;
  212. }
  213. break;
  214. }
  215. default: {
  216. break;
  217. }
  218. }
  219. }
  220. void GameStateSnapshot::_get_rc_cycles(
  221. SnapshotDataObject *p_obj,
  222. SnapshotDataObject *p_source_obj,
  223. HashSet<SnapshotDataObject *> p_traversed_objs,
  224. LocalVector<String> &r_ret_val,
  225. const String &p_current_path) {
  226. // We're at the end of this branch and it was a cycle.
  227. if (p_obj == p_source_obj && p_current_path != "") {
  228. r_ret_val.push_back(p_current_path);
  229. return;
  230. }
  231. // Go through each of our children and try traversing them.
  232. for (const KeyValue<String, ObjectID> &next_child : p_obj->outbound_references) {
  233. SnapshotDataObject *next_obj = p_obj->snapshot->objects[next_child.value];
  234. String next_name = next_obj == p_source_obj ? "self" : next_obj->get_name();
  235. String current_name = p_obj == p_source_obj ? "self" : p_obj->get_name();
  236. String child_path = current_name + "[\"" + next_child.key + U"\"] → " + next_name;
  237. if (p_current_path != "") {
  238. child_path = p_current_path + "\n" + child_path;
  239. }
  240. SnapshotDataObject *next = objects[next_child.value];
  241. if (next != nullptr && next->is_class(RefCounted::get_class_static()) && !next->is_class(WeakRef::get_class_static()) && !p_traversed_objs.has(next)) {
  242. HashSet<SnapshotDataObject *> traversed_copy = p_traversed_objs;
  243. if (p_obj != p_source_obj) {
  244. traversed_copy.insert(p_obj);
  245. }
  246. _get_rc_cycles(next, p_source_obj, traversed_copy, r_ret_val, child_path);
  247. }
  248. }
  249. }
  250. void GameStateSnapshot::recompute_references() {
  251. for (const KeyValue<ObjectID, SnapshotDataObject *> &obj : objects) {
  252. Dictionary values;
  253. for (const KeyValue<StringName, Variant> &kv : obj.value->prop_values) {
  254. // Should only ever be one entry in this context.
  255. values[kv.key] = kv.value;
  256. }
  257. Variant values_variant(values);
  258. HashMap<String, ObjectID> refs;
  259. _get_outbound_references(values_variant, refs);
  260. obj.value->outbound_references = refs;
  261. for (const KeyValue<String, ObjectID> &kv : refs) {
  262. // Get the guy we are pointing to, and indicate the name of _our_ property that is pointing to them.
  263. if (objects.has(kv.value)) {
  264. objects[kv.value]->inbound_references[kv.key] = obj.key;
  265. }
  266. }
  267. }
  268. for (const KeyValue<ObjectID, SnapshotDataObject *> &obj : objects) {
  269. if (!obj.value->is_class(RefCounted::get_class_static()) || obj.value->is_class(WeakRef::get_class_static())) {
  270. continue;
  271. }
  272. HashSet<SnapshotDataObject *> traversed_objs;
  273. LocalVector<String> cycles;
  274. _get_rc_cycles(obj.value, obj.value, traversed_objs, cycles, "");
  275. Array cycles_array;
  276. for (const String &cycle : cycles) {
  277. cycles_array.push_back(cycle);
  278. }
  279. obj.value->extra_debug_data["ref_cycles"] = cycles_array;
  280. }
  281. }
  282. Ref<GameStateSnapshot> GameStateSnapshot::create_ref(const String &p_snapshot_name, const Vector<uint8_t> &p_snapshot_buffer) {
  283. Ref<GameStateSnapshot> snapshot;
  284. snapshot.instantiate();
  285. snapshot->name = p_snapshot_name;
  286. // Snapshots may have been created by an older version of the editor. Handle parsing old snapshot versions here based on the version number.
  287. Vector<uint8_t> snapshot_buffer_decompressed;
  288. int success = Compression::decompress_dynamic(&snapshot_buffer_decompressed, -1, p_snapshot_buffer.ptr(), p_snapshot_buffer.size(), Compression::MODE_DEFLATE);
  289. ERR_FAIL_COND_V_MSG(success != Z_OK, nullptr, "ObjectDB Snapshot could not be parsed. Failed to decompress snapshot.");
  290. CoreBind::Marshalls *m = CoreBind::Marshalls::get_singleton();
  291. Array snapshot_data = m->base64_to_variant(m->raw_to_base64(snapshot_buffer_decompressed));
  292. ERR_FAIL_COND_V_MSG(snapshot_data.is_empty(), nullptr, "ObjectDB Snapshot could not be parsed. Variant array is empty.");
  293. const Variant &first_item = snapshot_data[0];
  294. ERR_FAIL_COND_V_MSG(first_item.get_type() != Variant::DICTIONARY, nullptr, "ObjectDB Snapshot could not be parsed. First item is not a Dictionary.");
  295. snapshot->snapshot_context = first_item;
  296. SnapshotDataObject::ResourceCache resource_cache;
  297. for (int i = 1; i < snapshot_data.size(); i += 4) {
  298. SceneDebuggerObject obj;
  299. obj.deserialize(uint64_t(snapshot_data[i + 0]), snapshot_data[i + 1], snapshot_data[i + 2]);
  300. ERR_FAIL_COND_V_MSG(snapshot_data[i + 3].get_type() != Variant::DICTIONARY, nullptr, "ObjectDB Snapshot could not be parsed. Extra debug data is not a Dictionary.");
  301. if (obj.id.is_null()) {
  302. continue;
  303. }
  304. snapshot->objects[obj.id] = memnew(SnapshotDataObject(obj, snapshot.ptr(), resource_cache));
  305. snapshot->objects[obj.id]->extra_debug_data = (Dictionary)snapshot_data[i + 3];
  306. }
  307. snapshot->recompute_references();
  308. print_verbose("Resource cache hits: " + String::num(resource_cache.hits) + ". Resource cache misses: " + String::num(resource_cache.misses));
  309. return snapshot;
  310. }
  311. GameStateSnapshot::~GameStateSnapshot() {
  312. for (const KeyValue<ObjectID, SnapshotDataObject *> &item : objects) {
  313. memdelete(item.value);
  314. }
  315. }