infra: Base Instance classes

This commit is contained in:
maelstrom 2025-01-12 17:18:03 +01:00
parent 051ce6e89d
commit ca22b4438f
4 changed files with 73 additions and 1 deletions

4
src/objects/base.h Normal file
View file

@ -0,0 +1,4 @@
#pragma once
#include "base/metadata.h"
#include "base/instance.h"

View file

@ -0,0 +1,37 @@
#include "instance.h"
#include <algorithm>
#include <memory>
#include <optional>
// Static so that this variable name is "local" to this source file
static InstanceType TYPE_ {
.super = NULL,
.className = "Instance",
.constructor = NULL, // Instance is abstract and therefore not creatable
};
InstanceType* Instance::TYPE = &TYPE_;
InstanceType* GetClass() {
return &TYPE_;
}
void Instance::SetParent(std::optional<std::shared_ptr<Instance>> newParent) {
// If we currently have a parent, remove ourselves from it before adding ourselves to the new one
if (this->parent.has_value() && !this->parent.value().expired()) {
auto oldParent = this->parent.value().lock();
oldParent->children.erase(std::find(oldParent->children.begin(), oldParent->children.end(), this->shared_from_this()));
}
// Add ourselves to the new parent
if (newParent.has_value()) {
newParent.value()->children.push_back(this->shared_from_this());
}
this->parent = newParent;
// TODO: Add code for sending signals for parent updates
}
std::optional<std::shared_ptr<Instance>> Instance::GetParent() {
if (!parent.has_value()) return std::nullopt;
if (parent.value().expired()) return std::nullopt;
return parent.value().lock();
}

View file

@ -0,0 +1,30 @@
#pragma once
#include "metadata.h"
#include <memory>
#include <string>
// Struct describing information about an instance
struct InstanceType {
InstanceType* super; // May be null
std::string className;
InstanceConstructor constructor;
};
// Base class for all instances in the data model
class Instance : std::enable_shared_from_this<Instance> {
private:
std::optional<std::weak_ptr<Instance>> parent;
std::vector<std::shared_ptr<Instance>> children;
public:
static InstanceType* TYPE;
std::string name;
InstanceType* GetClass();
void SetParent(std::optional<std::shared_ptr<Instance>> newParent);
std::optional<std::shared_ptr<Instance>> GetParent();
inline const std::vector<std::shared_ptr<Instance>> GetChildren() { return children; }
};
typedef std::shared_ptr<Instance> InstanceRef;
typedef std::weak_ptr<Instance> InstanceRefWeak;

View file

@ -1,5 +1,6 @@
#pragma once
#include <memory>
#include <optional>
#include <string>
#include <variant>
@ -9,7 +10,7 @@
#include "../../datatype.h"
class Instance;
typedef Instance(*InstanceConstructor)();
typedef std::shared_ptr<Instance>(*InstanceConstructor)();
const uint INST_NOT_CREATABLE = 1;
// const uint INST_SINGLETON = 2;