Path: blob/master/modules/objectdb_profiler/editor/snapshot_data.cpp
11323 views
/**************************************************************************/1/* snapshot_data.cpp */2/**************************************************************************/3/* This file is part of: */4/* GODOT ENGINE */5/* https://godotengine.org */6/**************************************************************************/7/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */8/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */9/* */10/* Permission is hereby granted, free of charge, to any person obtaining */11/* a copy of this software and associated documentation files (the */12/* "Software"), to deal in the Software without restriction, including */13/* without limitation the rights to use, copy, modify, merge, publish, */14/* distribute, sublicense, and/or sell copies of the Software, and to */15/* permit persons to whom the Software is furnished to do so, subject to */16/* the following conditions: */17/* */18/* The above copyright notice and this permission notice shall be */19/* included in all copies or substantial portions of the Software. */20/* */21/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */22/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */23/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */24/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */25/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */26/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */27/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */28/**************************************************************************/2930#include "snapshot_data.h"3132#include "core/core_bind.h"33#include "core/object/script_language.h"34#include "scene/debugger/scene_debugger.h"3536#if defined(MODULE_GDSCRIPT_ENABLED) && defined(DEBUG_ENABLED)37#include "modules/gdscript/gdscript.h"38#endif3940SnapshotDataObject::SnapshotDataObject(SceneDebuggerObject &p_obj, GameStateSnapshot *p_snapshot, ResourceCache &resource_cache) :41snapshot(p_snapshot) {42remote_object_id = p_obj.id;43type_name = p_obj.class_name;4445for (const SceneDebuggerObject::SceneDebuggerProperty &prop : p_obj.properties) {46PropertyInfo pinfo = prop.first;47Variant pvalue = prop.second;4849if (pinfo.type == Variant::OBJECT && pvalue.is_string()) {50String path = pvalue;51// If a resource is followed by a ::, it is a nested resource (like a sub_resource in a .tscn file).52// To get a reference to it, first we load the parent resource (the .tscn, for example), then,53// we load the child resource. The parent resource (dependency) should not be destroyed before the child54// resource (pvalue) is loaded.55if (path.is_resource_file()) {56// Built-in resource.57String base_path = path.get_slice("::", 0);58if (!resource_cache.cache.has(base_path)) {59resource_cache.cache[base_path] = ResourceLoader::load(base_path);60resource_cache.misses++;61} else {62resource_cache.hits++;63}64}65if (!resource_cache.cache.has(path)) {66resource_cache.cache[path] = ResourceLoader::load(path);67resource_cache.misses++;68} else {69resource_cache.hits++;70}71pvalue = resource_cache.cache[path];7273if (pinfo.hint_string == "Script") {74if (get_script() != pvalue) {75set_script(Ref<RefCounted>());76Ref<Script> scr(pvalue);77if (scr.is_valid()) {78ScriptInstance *scr_instance = scr->placeholder_instance_create(this);79if (scr_instance) {80set_script_and_instance(pvalue, scr_instance);81}82}83}84}85}86prop_list.push_back(pinfo);87prop_values[pinfo.name] = pvalue;88}89}9091bool SnapshotDataObject::_get(const StringName &p_name, Variant &r_ret) const {92String name = p_name;9394if (name.begins_with("Metadata/")) {95name = name.replace_first("Metadata/", "metadata/");96}97if (!prop_values.has(name)) {98return false;99}100101r_ret = prop_values[p_name];102return true;103}104105void SnapshotDataObject::_get_property_list(List<PropertyInfo> *p_list) const {106p_list->clear(); // Sorry, don't want any categories.107for (const PropertyInfo &prop : prop_list) {108if (prop.name == "script") {109// Skip the script property, it's always added by the non-virtual method.110continue;111}112113p_list->push_back(prop);114}115}116117void SnapshotDataObject::_bind_methods() {118ClassDB::bind_method(D_METHOD("_is_read_only"), &SnapshotDataObject::_is_read_only);119}120121String SnapshotDataObject::get_node_path() {122if (!is_node()) {123return "";124}125SnapshotDataObject *current = this;126String path;127128while (true) {129String current_node_name = current->extra_debug_data["node_name"];130if (current_node_name != "") {131if (path != "") {132path = current_node_name + "/" + path;133} else {134path = current_node_name;135}136}137if (!current->extra_debug_data.has("node_parent")) {138break;139}140current = snapshot->objects[current->extra_debug_data["node_parent"]];141}142return path;143}144145String SnapshotDataObject::_get_script_name(Ref<Script> p_script) {146#if defined(MODULE_GDSCRIPT_ENABLED) && defined(DEBUG_ENABLED)147// GDScripts have more specific names than base scripts, so use those names if possible.148return GDScript::debug_get_script_name(p_script);149#else150// Otherwise fallback to the base script's name.151return p_script->get_global_name();152#endif153}154155String SnapshotDataObject::get_name() {156String found_type_name = type_name;157158// Ideally, we will name it after the script attached to it.159Ref<Script> maybe_script = get_script();160if (maybe_script.is_valid()) {161String full_name;162while (maybe_script.is_valid()) {163String global_name = _get_script_name(maybe_script);164if (global_name != "") {165if (full_name != "") {166full_name = global_name + "/" + full_name;167} else {168full_name = global_name;169}170}171maybe_script = maybe_script->get_base_script().ptr();172}173174found_type_name = type_name + "/" + full_name;175}176177return found_type_name + "_" + uitos(remote_object_id);178}179180bool SnapshotDataObject::is_refcounted() {181return is_class(RefCounted::get_class_static());182}183184bool SnapshotDataObject::is_node() {185return is_class(Node::get_class_static());186}187188bool SnapshotDataObject::is_class(const String &p_base_class) {189return ClassDB::is_parent_class(type_name, p_base_class);190}191192HashSet<ObjectID> SnapshotDataObject::_unique_references(const HashMap<String, ObjectID> &p_refs) {193HashSet<ObjectID> obj_set;194195for (const KeyValue<String, ObjectID> &pair : p_refs) {196obj_set.insert(pair.value);197}198199return obj_set;200}201202HashSet<ObjectID> SnapshotDataObject::get_unique_outbound_refernces() {203return _unique_references(outbound_references);204}205206HashSet<ObjectID> SnapshotDataObject::get_unique_inbound_references() {207return _unique_references(inbound_references);208}209210void GameStateSnapshot::_get_outbound_references(Variant &p_var, HashMap<String, ObjectID> &r_ret_val, const String &p_current_path) {211String path_divider = p_current_path.size() > 0 ? "/" : ""; // Make sure we don't start with a /.212switch (p_var.get_type()) {213case Variant::Type::INT:214case Variant::Type::OBJECT: { // Means ObjectID.215ObjectID as_id = ObjectID((uint64_t)p_var);216if (!objects.has(as_id)) {217return;218}219r_ret_val[p_current_path] = as_id;220break;221}222case Variant::Type::DICTIONARY: {223Dictionary dict = (Dictionary)p_var;224LocalVector<Variant> keys = dict.get_key_list();225for (Variant &k : keys) {226// 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.227_get_outbound_references(k, r_ret_val, p_current_path + path_divider + (String)k + "_key");228Variant v = dict.get(k, Variant());229_get_outbound_references(v, r_ret_val, p_current_path + path_divider + (String)k);230}231break;232}233case Variant::Type::ARRAY: {234Array arr = (Array)p_var;235int i = 0;236for (Variant &v : arr) {237_get_outbound_references(v, r_ret_val, p_current_path + path_divider + itos(i));238i++;239}240break;241}242default: {243break;244}245}246}247248void GameStateSnapshot::_get_rc_cycles(249SnapshotDataObject *p_obj,250SnapshotDataObject *p_source_obj,251HashSet<SnapshotDataObject *> p_traversed_objs,252LocalVector<String> &r_ret_val,253const String &p_current_path) {254// We're at the end of this branch and it was a cycle.255if (p_obj == p_source_obj && p_current_path != "") {256r_ret_val.push_back(p_current_path);257return;258}259260// Go through each of our children and try traversing them.261for (const KeyValue<String, ObjectID> &next_child : p_obj->outbound_references) {262SnapshotDataObject *next_obj = p_obj->snapshot->objects[next_child.value];263String next_name = next_obj == p_source_obj ? "self" : next_obj->get_name();264String current_name = p_obj == p_source_obj ? "self" : p_obj->get_name();265String child_path = current_name + "[\"" + next_child.key + "\"] -> " + next_name;266if (p_current_path != "") {267child_path = p_current_path + "\n" + child_path;268}269270SnapshotDataObject *next = objects[next_child.value];271if (next != nullptr && next->is_class(RefCounted::get_class_static()) && !next->is_class(WeakRef::get_class_static()) && !p_traversed_objs.has(next)) {272HashSet<SnapshotDataObject *> traversed_copy = p_traversed_objs;273if (p_obj != p_source_obj) {274traversed_copy.insert(p_obj);275}276_get_rc_cycles(next, p_source_obj, traversed_copy, r_ret_val, child_path);277}278}279}280281void GameStateSnapshot::recompute_references() {282for (const KeyValue<ObjectID, SnapshotDataObject *> &obj : objects) {283Dictionary values;284for (const KeyValue<StringName, Variant> &kv : obj.value->prop_values) {285// Should only ever be one entry in this context.286values[kv.key] = kv.value;287}288289Variant values_variant(values);290HashMap<String, ObjectID> refs;291_get_outbound_references(values_variant, refs);292293obj.value->outbound_references = refs;294295for (const KeyValue<String, ObjectID> &kv : refs) {296// Get the guy we are pointing to, and indicate the name of _our_ property that is pointing to them.297if (objects.has(kv.value)) {298objects[kv.value]->inbound_references[kv.key] = obj.key;299}300}301}302303for (const KeyValue<ObjectID, SnapshotDataObject *> &obj : objects) {304if (!obj.value->is_class(RefCounted::get_class_static()) || obj.value->is_class(WeakRef::get_class_static())) {305continue;306}307HashSet<SnapshotDataObject *> traversed_objs;308LocalVector<String> cycles;309310_get_rc_cycles(obj.value, obj.value, traversed_objs, cycles, "");311Array cycles_array;312for (const String &cycle : cycles) {313cycles_array.push_back(cycle);314}315obj.value->extra_debug_data["ref_cycles"] = cycles_array;316}317}318319Ref<GameStateSnapshotRef> GameStateSnapshot::create_ref(const String &p_snapshot_name, const Vector<uint8_t> &p_snapshot_buffer) {320// A ref to a refcounted object which is a wrapper of a non-refcounted object.321Ref<GameStateSnapshotRef> sn;322sn.instantiate(memnew(GameStateSnapshot));323GameStateSnapshot *snapshot = sn->get_snapshot();324snapshot->name = p_snapshot_name;325326// Snapshots may have been created by an older version of the editor. Handle parsing old snapshot versions here based on the version number.327328Vector<uint8_t> snapshot_buffer_decompressed;329int success = Compression::decompress_dynamic(&snapshot_buffer_decompressed, -1, p_snapshot_buffer.ptr(), p_snapshot_buffer.size(), Compression::MODE_DEFLATE);330ERR_FAIL_COND_V_MSG(success != Z_OK, nullptr, "ObjectDB Snapshot could not be parsed. Failed to decompress snapshot.");331CoreBind::Marshalls *m = CoreBind::Marshalls::get_singleton();332Array snapshot_data = m->base64_to_variant(m->raw_to_base64(snapshot_buffer_decompressed));333ERR_FAIL_COND_V_MSG(snapshot_data.is_empty(), nullptr, "ObjectDB Snapshot could not be parsed. Variant array is empty.");334const Variant &first_item = snapshot_data[0];335ERR_FAIL_COND_V_MSG(first_item.get_type() != Variant::DICTIONARY, nullptr, "ObjectDB Snapshot could not be parsed. First item is not a Dictionary.");336snapshot->snapshot_context = first_item;337338SnapshotDataObject::ResourceCache resource_cache;339for (int i = 1; i < snapshot_data.size(); i += 4) {340SceneDebuggerObject obj;341obj.deserialize(uint64_t(snapshot_data[i + 0]), snapshot_data[i + 1], snapshot_data[i + 2]);342ERR_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.");343344if (obj.id.is_null()) {345continue;346}347348snapshot->objects[obj.id] = memnew(SnapshotDataObject(obj, snapshot, resource_cache));349snapshot->objects[obj.id]->extra_debug_data = (Dictionary)snapshot_data[i + 3];350}351352snapshot->recompute_references();353print_verbose("Resource cache hits: " + String::num(resource_cache.hits) + ". Resource cache misses: " + String::num(resource_cache.misses));354return sn;355}356357GameStateSnapshot::~GameStateSnapshot() {358for (const KeyValue<ObjectID, SnapshotDataObject *> &item : objects) {359memdelete(item.value);360}361}362363bool GameStateSnapshotRef::unreference() {364bool die = RefCounted::unreference();365if (die) {366memdelete(gamestate_snapshot);367}368return die;369}370371GameStateSnapshot *GameStateSnapshotRef::get_snapshot() {372return gamestate_snapshot;373}374375376