Compare commits

...

5 commits

41 changed files with 507 additions and 156 deletions

View file

@ -15,24 +15,8 @@ Handles editorToolHandles;
std::vector<std::shared_ptr<Instance>> currentSelection;
std::vector<SelectionUpdateHandler> selectionUpdateListeners;
std::vector<PropertyUpdateHandler> propertyUpdatelisteners;
void setSelection(std::vector<std::shared_ptr<Instance>> newSelection, bool fromExplorer) {
for (SelectionUpdateHandler handler : selectionUpdateListeners) {
handler(currentSelection, newSelection, fromExplorer);
}
currentSelection = newSelection;
}
const std::vector<std::shared_ptr<Instance>> getSelection() {
return currentSelection;
}
void addSelectionListener(SelectionUpdateHandler handler) {
selectionUpdateListeners.push_back(handler);
}
void sendPropertyUpdatedSignal(std::shared_ptr<Instance> instance, std::string property, Variant newValue) {
for (PropertyUpdateHandler handler : propertyUpdatelisteners) {

View file

@ -1,7 +1,7 @@
#pragma once
#include "objects/base/instance.h"
#include "handles.h"
#include "objects/workspace.h"
#include "objects/service/workspace.h"
#include "objects/datamodel.h"
#include "camera.h"
#include <functional>
@ -11,7 +11,6 @@ class Instance;
// typedef std::function<void(std::shared_ptr<Instance> element, std::optional<std::shared_ptr<Instance>> newParent)> HierarchyUpdateHandler;
typedef std::function<void(std::shared_ptr<Instance> object, std::optional<std::shared_ptr<Instance>> oldParent, std::optional<std::shared_ptr<Instance>> newParent)> HierarchyPreUpdateHandler;
typedef std::function<void(std::shared_ptr<Instance> object, std::optional<std::shared_ptr<Instance>> oldParent, std::optional<std::shared_ptr<Instance>> newParent)> HierarchyPostUpdateHandler;
typedef std::function<void(std::vector<std::shared_ptr<Instance>> oldSelection, std::vector<std::shared_ptr<Instance>> newSelection, bool fromExplorer)> SelectionUpdateHandler;
typedef std::function<void(std::shared_ptr<Instance> instance, std::string property, Variant newValue)> PropertyUpdateHandler;
// TEMPORARY COMMON DATA FOR VARIOUS INTERNAL COMPONENTS
@ -24,9 +23,5 @@ extern std::optional<HierarchyPreUpdateHandler> hierarchyPreUpdateHandler;
extern std::optional<HierarchyPostUpdateHandler> hierarchyPostUpdateHandler;
extern Handles editorToolHandles;
void setSelection(std::vector<std::shared_ptr<Instance>> newSelection, bool fromExplorer = false);
const std::vector<std::shared_ptr<Instance>> getSelection();
void addSelectionListener(SelectionUpdateHandler handler);
void sendPropertyUpdatedSignal(std::shared_ptr<Instance> instance, std::string property, Variant newValue);
void addPropertyUpdateListener(PropertyUpdateHandler handler);

View file

@ -2,12 +2,13 @@
#include "base.h"
#include "error/data.h"
#include "utils.h"
#include <memory>
class Instance;
class InstanceRef {
std::shared_ptr<Instance> ref;
nullable std::shared_ptr<Instance> ref;
public:
InstanceRef();
InstanceRef(std::weak_ptr<Instance>);

View file

@ -3,6 +3,7 @@
#include "datatypes/cframe.h"
#include "datatypes/vector.h"
#include "math_helper.h"
#include "objects/service/selection.h"
#include "partassembly.h"
#include <glm/ext/scalar_common.hpp>
#include <memory>
@ -27,7 +28,8 @@ static rp3d::PhysicsCommon common;
static rp3d::PhysicsWorld* world = common.createPhysicsWorld();
std::shared_ptr<Part> getHandleAdornee() {
for (std::weak_ptr<Instance> inst : getSelection()) {
std::shared_ptr<Selection> selection = gDataModel->GetService<Selection>();
for (std::weak_ptr<Instance> inst : selection->Get()) {
if (!inst.expired() && inst.lock()->IsA<Part>())
return inst.lock()->CastTo<Part>().expect();
}
@ -78,7 +80,8 @@ Vector3 handleSize(HandleFace face) {
static int getAABBOfSelection(glm::vec3& pos, glm::vec3& size, glm::vec3& min, glm::vec3& max) {
int count = 0;
for (std::weak_ptr<Instance> inst : getSelection()) {
std::shared_ptr<Selection> selection = gDataModel->GetService<Selection>();
for (std::weak_ptr<Instance> inst : selection->Get()) {
if (inst.expired() || !inst.lock()->IsA<Part>()) continue;
std::shared_ptr<Part> part = inst.lock()->CastTo<Part>().expect();
@ -97,7 +100,8 @@ static int getAABBOfSelection(glm::vec3& pos, glm::vec3& size, glm::vec3& min, g
}
static std::shared_ptr<Part> getFirstSelectedPart() {
for (std::weak_ptr<Instance> inst : getSelection()) {
std::shared_ptr<Selection> selection = gDataModel->GetService<Selection>();
for (std::weak_ptr<Instance> inst : selection->Get()) {
if (inst.expired() || !inst.lock()->IsA<Part>()) continue;
return inst.lock()->CastTo<Part>().expect();
@ -107,7 +111,7 @@ static std::shared_ptr<Part> getFirstSelectedPart() {
}
CFrame getLocalHandleCFrame(HandleFace face) {
PartAssembly assembly = PartAssembly::FromSelection();
PartAssembly assembly = PartAssembly::FromSelection(gDataModel->GetService<Selection>());
Vector3 size;
if (editorToolHandles.worldMode)
@ -125,7 +129,7 @@ CFrame getLocalHandleCFrame(HandleFace face) {
}
CFrame getHandleCFrame(HandleFace face) {
PartAssembly assembly = PartAssembly::FromSelection();
PartAssembly assembly = PartAssembly::FromSelection(gDataModel->GetService<Selection>());
if (editorToolHandles.worldMode) {
return getLocalHandleCFrame(face) + assembly.assemblyOrigin().Position();

View file

@ -1,12 +1,12 @@
#include "datamodel.h"
#include "base/service.h"
#include "objects/base/service.h"
#include "objects/base/instance.h"
#include "objects/base/refstate.h"
#include "objects/base/service.h"
#include "objects/meta.h"
#include "objects/script/serverscriptservice.h"
#include "objects/service/script/serverscriptservice.h"
#include "datatypes/variant.h"
#include "workspace.h"
#include "objects/service/workspace.h"
#include "logger.h"
#include "panic.h"
#include <pugixml.hpp>

View file

@ -3,9 +3,9 @@
#include "datatypes/cframe.h"
#include "datatypes/ref.h"
#include "objects/datamodel.h"
#include "objects/jointsservice.h"
#include "objects/service/jointsservice.h"
#include "objects/part.h"
#include "objects/workspace.h"
#include "objects/service/workspace.h"
#include <memory>
#include <reactphysics3d/constraint/FixedJoint.h>
#include <reactphysics3d/engine/PhysicsWorld.h>

View file

@ -1,7 +1,7 @@
#include "rotate.h"
#include "objects/jointsservice.h"
#include "objects/service/jointsservice.h"
#include "objects/part.h"
#include "objects/workspace.h"
#include "objects/service/workspace.h"
#include "rendering/renderer.h"
#include <reactphysics3d/constraint/HingeJoint.h>

View file

@ -1,7 +1,7 @@
#include "rotatev.h"
#include "objects/jointsservice.h"
#include "objects/service/jointsservice.h"
#include "objects/part.h"
#include "objects/workspace.h"
#include "objects/service/workspace.h"
#include "rendering/renderer.h"
#include <reactphysics3d/constraint/HingeJoint.h>

View file

@ -3,9 +3,9 @@
#include "datatypes/cframe.h"
#include "objects/datamodel.h"
#include "objects/joint/jointinstance.h"
#include "objects/jointsservice.h"
#include "objects/service/jointsservice.h"
#include "objects/part.h"
#include "objects/workspace.h"
#include "objects/service/workspace.h"
#include <memory>
#include <reactphysics3d/constraint/FixedJoint.h>
#include <reactphysics3d/engine/PhysicsWorld.h>

View file

@ -3,9 +3,9 @@
#include "datatypes/cframe.h"
#include "objects/datamodel.h"
#include "objects/joint/jointinstance.h"
#include "objects/jointsservice.h"
#include "objects/service/jointsservice.h"
#include "objects/part.h"
#include "objects/workspace.h"
#include "objects/service/workspace.h"
#include <memory>
#include <reactphysics3d/constraint/FixedJoint.h>
#include <reactphysics3d/engine/PhysicsWorld.h>

View file

@ -4,14 +4,15 @@
#include "objects/joint/rotate.h"
#include "objects/joint/rotatev.h"
#include "objects/joint/weld.h"
#include "objects/jointsservice.h"
#include "objects/service/jointsservice.h"
#include "objects/model.h"
#include "objects/part.h"
#include "objects/joint/snap.h"
#include "objects/script.h"
#include "objects/script/scriptcontext.h"
#include "objects/script/serverscriptservice.h"
#include "objects/workspace.h"
#include "objects/service/script/scriptcontext.h"
#include "objects/service/script/serverscriptservice.h"
#include "objects/service/selection.h"
#include "objects/service/workspace.h"
#include "objects/datamodel.h"
std::map<std::string, const InstanceType*> INSTANCE_MAP = {
@ -34,4 +35,5 @@ std::map<std::string, const InstanceType*> INSTANCE_MAP = {
{ "JointsService", &JointsService::TYPE },
{ "ScriptContext", &ScriptContext::TYPE },
{ "ServerScriptService", &ServerScriptService::TYPE },
{ "Selection", &Selection::TYPE },
};

View file

@ -9,7 +9,7 @@
#include "objects/joint/rotate.h"
#include "objects/joint/rotatev.h"
#include "objects/joint/weld.h"
#include "objects/jointsservice.h"
#include "objects/service/jointsservice.h"
#include "objects/joint/jointinstance.h"
#include "objects/joint/snap.h"
#include "rendering/renderer.h"

View file

@ -66,7 +66,6 @@ public:
DEF_PROP_CATEGORY(APPEARANCE)
DEF_PROP Color3 color;
DEF_PROP float transparency = 0.f;
bool selected = false;
DEF_PROP_CATEGORY(BEHAVIOR)
DEF_PROP_(on_update=onUpdated) bool anchored = false;

View file

@ -3,8 +3,8 @@
#include "logger.h"
#include "objects/base/instance.h"
#include "objects/base/member.h"
#include "objects/script/scriptcontext.h"
#include "objects/workspace.h"
#include "objects/service/script/scriptcontext.h"
#include "objects/service/workspace.h"
#include "objects/datamodel.h"
#include "datatypes/ref.h"
#include "lua.h" // IWYU pragma: keep

View file

@ -1,6 +1,6 @@
#include "jointsservice.h"
#include "workspace.h"
#include "datamodel.h"
#include "objects/service/workspace.h"
#include "objects/datamodel.h"
#include <memory>
JointsService::JointsService(): Service(&TYPE) {

View file

@ -1,6 +1,6 @@
#include "serverscriptservice.h"
#include "objects/script.h"
#include "objects/workspace.h"
#include "objects/service/workspace.h"
#include "objects/datamodel.h"
ServerScriptService::ServerScriptService(): Service(&TYPE) {

View file

@ -0,0 +1,42 @@
#include "selection.h"
#include "objects/datamodel.h"
#include <algorithm>
#include <memory>
Selection::Selection(): Service(&TYPE) {
}
Selection::~Selection() = default;
void Selection::InitService() {
if (initialized) return;
initialized = true;
}
std::vector<std::shared_ptr<Instance>> Selection::Get() {
return selection;
}
void Selection::Set(std::vector<std::shared_ptr<Instance>> newSelection) {
selection = newSelection;
SelectionChanged->Fire();
}
void Selection::Add(std::vector<std::shared_ptr<Instance>> instances) {
for (auto inst : instances) {
if (std::find(selection.begin(), selection.end(), inst) == selection.end()) {
selection.push_back(inst);
}
}
SelectionChanged->Fire();
}
void Selection::Remove(std::vector<std::shared_ptr<Instance>> instances) {
for (auto inst : instances) {
std::vector<std::shared_ptr<Instance>>::iterator p;
if ((p = std::find(selection.begin(), selection.end(), inst)) != selection.end()) {
selection.erase(p);
}
}
SelectionChanged->Fire();
}

View file

@ -0,0 +1,28 @@
#pragma once
#include "datatypes/signal.h"
#include "objects/annotation.h"
#include "objects/base/service.h"
#include <memory>
#include <vector>
class DEF_INST_SERVICE Selection : public Service {
AUTOGEN_PREAMBLE
private:
std::vector<std::shared_ptr<Instance>> selection;
protected:
void InitService() override;
bool initialized = false;
public:
Selection();
~Selection();
static inline std::shared_ptr<Instance> Create() { return std::make_shared<Selection>(); };
std::vector<std::shared_ptr<Instance>> Get();
void Set(std::vector<std::shared_ptr<Instance>> newSelection);
void Add(std::vector<std::shared_ptr<Instance>> instances);
void Remove(std::vector<std::shared_ptr<Instance>> instances);
SignalSource SelectionChanged;
};

View file

@ -3,7 +3,7 @@
#include "datatypes/ref.h"
#include "datatypes/vector.h"
#include "objects/base/instance.h"
#include "objects/jointsservice.h"
#include "objects/service/jointsservice.h"
#include "objects/joint/jointinstance.h"
#include "objects/datamodel.h"
#include "physics/util.h"

View file

@ -6,6 +6,7 @@
#include "math_helper.h"
#include "objects/base/instance.h"
#include "objects/part.h"
#include "objects/service/selection.h"
#include <glm/common.hpp>
#include <memory>
#include <vector>
@ -54,6 +55,10 @@ PartAssembly PartAssembly::FromSelection(std::vector<std::shared_ptr<Instance>>
return PartAssembly(selection, editorToolHandles.worldMode);
}
PartAssembly PartAssembly::FromSelection(std::shared_ptr<Selection> selection) {
return FromSelection(selection->Get());
}
void PartAssembly::SetCollisionsEnabled(bool enabled) {
for (auto part : parts) {
part->rigidBody->getCollider(0)->setIsWorldQueryCollider(enabled);
@ -112,4 +117,18 @@ void PartAssembly::Scale(Vector3 newSize, bool scaleUp) {
}
_bounds = _bounds * factor;
}
std::vector<PartTransformState> PartAssembly::GetCurrentTransforms() {
std::vector<PartTransformState> transforms;
for (auto part : parts) {
PartTransformState t;
t.part = part;
t.cframe = part->cframe;
t.size = part->size;
transforms.push_back(t);
}
return transforms;
}

View file

@ -6,8 +6,13 @@
class Part;
class Instance;
class Selection;
const std::vector<std::shared_ptr<Instance>> getSelection();
struct PartTransformState {
std::shared_ptr<Part> part;
Vector3 size;
CFrame cframe;
};
class PartAssembly {
CFrame _assemblyOrigin;
@ -18,13 +23,17 @@ class PartAssembly {
public:
PartAssembly(std::vector<std::shared_ptr<Part>>, bool worldMode = false);
static PartAssembly FromSelection(std::vector<std::shared_ptr<Instance>> selection = getSelection());
static PartAssembly FromSelection(std::vector<std::shared_ptr<Instance>> selection);
static PartAssembly FromSelection(std::shared_ptr<Selection> selection);
inline CFrame assemblyOrigin() { return _assemblyOrigin; };
inline Vector3 bounds() { return _bounds; };
inline Vector3 size() { return _size; };
inline bool multipleSelected() { return parts.size() > 1; }
// Gets the current transform state of all the parts in the assembly
std::vector<PartTransformState> GetCurrentTransforms();
// Transforms the assembly such that newOrigin is now this assembly's new assemblyOrigin
void SetOrigin(CFrame newOrigin);

View file

@ -19,6 +19,7 @@
#include "datatypes/vector.h"
#include "handles.h"
#include "math_helper.h"
#include "objects/service/selection.h"
#include "partassembly.h"
#include "rendering/torus.h"
#include "shader.h"
@ -270,7 +271,7 @@ static CFrame XYZToZXY(glm::vec3(0, 0, 0), -glm::vec3(1, 0, 0), glm::vec3(0, 0,
void renderHandles() {
if (!editorToolHandles.active) return;
auto assembly = PartAssembly::FromSelection();
auto assembly = PartAssembly::FromSelection(gDataModel->GetService<Selection>());
if (assembly.size() == Vector3::ZERO) return;
glDepthMask(GL_TRUE);
@ -448,15 +449,12 @@ void renderOutlines() {
glm::vec3 min, max;
bool first = true;
int count = 0;
for (auto it = gWorkspace()->GetDescendantsStart(); it != gWorkspace()->GetDescendantsEnd(); it++) {
std::shared_ptr<Instance> inst = *it;
std::shared_ptr<Selection> selection = gDataModel->GetService<Selection>();
for (auto inst : selection->Get()) {
if (inst->GetClass() != &Part::TYPE) continue;
std::shared_ptr<Part> part = std::dynamic_pointer_cast<Part>(inst);
if (!part->selected) continue;
count++;
if (first)
min = part->position(), max = part->position();
first = false;
@ -475,7 +473,7 @@ void renderOutlines() {
}
// Render AABB of selected parts
PartAssembly selectionAssembly = PartAssembly::FromSelection();
PartAssembly selectionAssembly = PartAssembly::FromSelection(gDataModel->GetService<Selection>());
if (selectionAssembly.size() == Vector3()) return;
glm::vec3 outlineSize = selectionAssembly.bounds();
glm::vec3 outlinePos = selectionAssembly.assemblyOrigin().Position();
@ -498,7 +496,7 @@ void renderSelectionAssembly() {
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
PartAssembly selectionAssembly = PartAssembly::FromSelection();
PartAssembly selectionAssembly = PartAssembly::FromSelection(gDataModel->GetService<Selection>());
// Use shader
outlineShader->use();
@ -555,7 +553,7 @@ void renderRotationArcs() {
// Pass in the camera position
handleShader->set("viewPos", camera.cameraPos);
PartAssembly assembly = PartAssembly::FromSelection();
PartAssembly assembly = PartAssembly::FromSelection(gDataModel->GetService<Selection>());
for (HandleFace face : HandleFace::Faces) {
if (glm::any(glm::lessThan(face.normal, glm::vec3(0)))) continue;

10
core/src/utils.h Normal file
View file

@ -0,0 +1,10 @@
#pragma once
#ifdef __clang__
#pragma clang diagnostic ignored "-Wnullability-extension"
#define nullable _Nullable
#define notnull _Nonnull
#else
#define nullable
#define notnull
#endif

View file

@ -26,6 +26,8 @@ set(PROJECT_SOURCES
mainglwidget.cpp
placedocument.h
placedocument.cpp
undohistory.h
undohistory.cpp
panes/explorerview.h
panes/explorerview.cpp
panes/explorermodel.h

View file

@ -15,11 +15,13 @@
#include "math_helper.h"
#include "objects/base/instance.h"
#include "objects/pvinstance.h"
#include "objects/service/selection.h"
#include "partassembly.h"
#include "physics/util.h"
#include "rendering/renderer.h"
#include "rendering/shader.h"
#include "datatypes/variant.h"
#include "undohistory.h"
#define PI 3.14159
#define M_mainWindow dynamic_cast<MainWindow*>(window())
@ -119,6 +121,8 @@ CFrame snapCFrame(CFrame frame) {
return CFrame(frame.Position(), frame.Position() + closestVec1, closestVec2);
}
std::vector<PartTransformState> initialTransforms;
bool tryMouseContextMenu = false;
bool isMouseDragging = false;
std::weak_ptr<Part> draggingObject;
@ -217,7 +221,7 @@ void MainGLWidget::handleLinearTransform(QMouseEvent* evt) {
absDiff = handleCFrame.Rotation() * Vector3(0, 0, diff);
}
PartAssembly selectionAssembly = PartAssembly::FromSelection();
PartAssembly selectionAssembly = PartAssembly::FromSelection(gDataModel->GetService<Selection>());
if (editorToolHandles.handlesType == MoveHandles) {
selectionAssembly.TransformBy(CFrame() + absDiff);
@ -358,6 +362,7 @@ void MainGLWidget::mouseMoveEvent(QMouseEvent* evt) {
}
void MainGLWidget::mousePressEvent(QMouseEvent* evt) {
initialTransforms = {};
tryMouseContextMenu = evt->button() == Qt::RightButton;
switch(evt->button()) {
// Camera drag
@ -374,8 +379,10 @@ void MainGLWidget::mousePressEvent(QMouseEvent* evt) {
auto handle = raycastHandle(pointDir);
if (handle.has_value()) {
startPoint = glm::vec2(evt->pos().x(), evt->pos().y());
initialAssembly = PartAssembly::FromSelection();
initialAssembly = PartAssembly::FromSelection(gDataModel->GetService<Selection>());
initialFrame = initialAssembly.assemblyOrigin();
initialTransforms = PartAssembly::FromSelection(gDataModel->GetService<Selection>()).GetCurrentTransforms();
printf("%ld\n", initialTransforms.size());
isMouseDragging = true;
draggingHandle = handle;
startLinearTransform(evt);
@ -383,10 +390,11 @@ void MainGLWidget::mousePressEvent(QMouseEvent* evt) {
}
// raycast part
std::shared_ptr<Selection> selection = gDataModel->GetService<Selection>();
std::optional<const RaycastResult> rayHit = gWorkspace()->CastRayNearest(camera.cameraPos, pointDir, 50000);
if (!rayHit || !partFromBody(rayHit->body)) { setSelection({}); return; }
if (!rayHit || !partFromBody(rayHit->body)) { selection->Set({}); return; }
std::shared_ptr<Part> part = partFromBody(rayHit->body);
if (part->locked) { setSelection({}); return; }
if (part->locked) { selection->Set({}); return; }
std::shared_ptr<PVInstance> selObject = part;
@ -428,20 +436,16 @@ void MainGLWidget::mousePressEvent(QMouseEvent* evt) {
//part.selected = true;
isMouseDragging = true;
draggingObject = part;
initialTransforms = PartAssembly::FromSelection({part}).GetCurrentTransforms();
if (evt->modifiers() & (Qt::ControlModifier | Qt::ShiftModifier)) {
std::vector<std::shared_ptr<Instance>> currentSelection = getSelection();
for (size_t i = 0; i < currentSelection.size(); i++) {
std::shared_ptr<Instance> inst = currentSelection[i];
if (inst == selObject) {
currentSelection.erase(currentSelection.begin() + i);
goto skipAddPart;
}
}
currentSelection.push_back(selObject);
skipAddPart:
setSelection(currentSelection);
} else
setSelection({ selObject });
auto sel = selection->Get();
if (std::find(sel.begin(), sel.end(), selObject) == sel.end())
selection->Add({ selObject });
else
selection->Remove({ selObject });
} else {
selection->Set({ selObject });
}
// Disable bit so that we can ignore the part while raycasting
// part->rigidBody->getCollider(0)->setCollisionCategoryBits(0b10);
@ -458,6 +462,17 @@ void MainGLWidget::mouseReleaseEvent(QMouseEvent* evt) {
draggingObject = {};
draggingHandle = std::nullopt;
if (!initialTransforms.empty()) {
UndoState historyState;
for (auto t : initialTransforms) {
historyState.push_back(UndoStatePropertyChanged { t.part, "CFrame", t.cframe, t.part->cframe });
historyState.push_back(UndoStatePropertyChanged { t.part, "Size", t.size, t.part->size });
}
M_mainWindow->undoManager.PushState(historyState);
}
// Open context menu
if (tryMouseContextMenu)
contextMenu.exec(QCursor::pos());
@ -508,20 +523,8 @@ void MainGLWidget::keyPressEvent(QKeyEvent* evt) {
}));
gWorkspace()->SyncPartPhysics(lastPart);
lastPart->name = "Part" + std::to_string(partId++);
M_mainWindow->undoManager.PushState({ UndoStateInstanceCreated { lastPart, gWorkspace() } });
}
if (evt->key() == Qt::Key_U)
Logger::info("info message");
if (evt->key() == Qt::Key_I)
Logger::warning("warning message");
if (evt->key() == Qt::Key_O)
Logger::error("error message");
if (evt->key() == Qt::Key_C && getSelection().size() > 0)
getSelection()[0]->Clone().value()->SetParent(gWorkspace());
if (evt->key() == Qt::Key_H && getSelection().size() > 0)
Logger::infof("Object at: 0x%x\n", getSelection()[0].get());
}
void MainGLWidget::keyReleaseEvent(QKeyEvent* evt) {

View file

@ -5,12 +5,15 @@
#include "logger.h"
#include "objects/datamodel.h"
#include "objects/model.h"
#include "objects/service/selection.h"
#include "placedocument.h"
#include "script/scriptdocument.h"
#include "undohistory.h"
#include <memory>
#include <qclipboard.h>
#include <qevent.h>
#include <qglobal.h>
#include <qkeysequence.h>
#include <qmessagebox.h>
#include <qmimedata.h>
#include <qnamespace.h>
@ -44,15 +47,6 @@ inline bool isDarkMode() {
QtMessageHandler defaultMessageHandler = nullptr;
// std::map<QtMsgType, Logger::LogLevel> QT_MESSAGE_TYPE_TO_LOG_LEVEL = {
// { QtMsgType::QtInfoMsg, Logger::LogLevel::INFO },
// { QtMsgType::QtSystemMsg, Logger::LogLevel::INFO },
// { QtMsgType::QtDebugMsg, Logger::LogLevel::DEBUG },
// { QtMsgType::QtWarningMsg, Logger::LogLevel::WARNING },
// { QtMsgType::QtCriticalMsg, Logger::LogLevel::ERROR },
// { QtMsgType::QtFatalMsg, Logger::LogLevel::FATAL_ERROR },
// };
void logQtMessage(QtMsgType type, const QMessageLogContext &context, const QString &msg) {
// Logger::log("[Qt] " + msg.toStdString(), QT_MESSAGE_TYPE_TO_LOG_LEVEL[type]);
Logger::LogLevel logLevel = type == QtMsgType::QtFatalMsg ? Logger::LogLevel::FATAL_ERROR : Logger::LogLevel::DEBUG;
@ -77,6 +71,8 @@ MainWindow::MainWindow(QWidget *parent)
ui->setupUi(this);
setMouseTracking(true);
ui->actionRedo->setShortcuts({QKeySequence("Ctrl+Shift+Z"), QKeySequence("Ctrl+Y")});
QIcon::setThemeSearchPaths(QIcon::themeSearchPaths() + QStringList { "./assets/icons" });
if (isDarkMode())
QIcon::setFallbackThemeName("editor-dark");
@ -97,28 +93,6 @@ MainWindow::MainWindow(QWidget *parent)
connectActionHandlers();
// Update properties
addSelectionListener([&](auto oldSelection, auto newSelection, bool fromExplorer) {
if (newSelection.size() == 0) return;
if (newSelection.size() > 1)
ui->propertiesView->setSelected(std::nullopt);
ui->propertiesView->setSelected(newSelection[0]);
});
addSelectionListener([&](auto oldSelection, auto newSelection, bool __) {
for (std::weak_ptr<Instance> inst : oldSelection) {
if (inst.expired() || inst.lock()->GetClass() != &Part::TYPE) continue;
std::shared_ptr<Part> part = std::dynamic_pointer_cast<Part>(inst.lock());
part->selected = false;
}
for (std::weak_ptr<Instance> inst : newSelection) {
if (inst.expired() || inst.lock()->GetClass() != &Part::TYPE) continue;
std::shared_ptr<Part> part = std::dynamic_pointer_cast<Part>(inst.lock());
part->selected = true;
}
});
// ui->explorerView->Init(ui);
placeDocument = new PlaceDocument(this);
placeDocument->setAttribute(Qt::WA_DeleteOnClose, true);
@ -126,8 +100,18 @@ MainWindow::MainWindow(QWidget *parent)
ui->mdiArea->currentSubWindow()->showMaximized();
ui->mdiArea->findChild<QTabBar*>()->setExpanding(false);
placeDocument->init();
ui->propertiesView->init();
ui->mdiArea->setTabsClosable(true);
// Undo/Redo
ui->actionUndo->setEnabled(false);
ui->actionRedo->setEnabled(false);
undoManager.SetUndoStateListener([&](bool canUndo, bool canRedo) {
ui->actionUndo->setEnabled(canUndo);
ui->actionRedo->setEnabled(canRedo);
});
}
void MainWindow::closeEvent(QCloseEvent* evt) {
@ -299,16 +283,22 @@ void MainWindow::connectActionHandlers() {
});
connect(ui->actionDelete, &QAction::triggered, this, [&]() {
for (std::weak_ptr<Instance> inst : getSelection()) {
UndoState historyState;
std::shared_ptr<Selection> selection = gDataModel->GetService<Selection>();
for (std::weak_ptr<Instance> inst : selection->Get()) {
if (inst.expired()) continue;
historyState.push_back(UndoStateInstanceRemoved { inst.lock(), inst.lock()->GetParent().value() });
inst.lock()->SetParent(std::nullopt);
}
setSelection({});
selection->Set({});
historyState.push_back(UndoStateSelectionChanged {selection->Get(), {}});
undoManager.PushState(historyState);
});
connect(ui->actionCopy, &QAction::triggered, this, [&]() {
pugi::xml_document rootDoc;
for (std::weak_ptr<Instance> inst : getSelection()) {
std::shared_ptr<Selection> selection = gDataModel->GetService<Selection>();
for (std::weak_ptr<Instance> inst : selection->Get()) {
if (inst.expired()) continue;
inst.lock()->Serialize(rootDoc);
}
@ -320,13 +310,20 @@ void MainWindow::connectActionHandlers() {
mimeData->setData("application/xml", QByteArray::fromStdString(encoded.str()));
QApplication::clipboard()->setMimeData(mimeData);
});
connect(ui->actionCut, &QAction::triggered, this, [&]() {
UndoState historyState;
pugi::xml_document rootDoc;
for (std::weak_ptr<Instance> inst : getSelection()) {
std::shared_ptr<Selection> selection = gDataModel->GetService<Selection>();
for (std::weak_ptr<Instance> inst : selection->Get()) {
if (inst.expired()) continue;
historyState.push_back(UndoStateInstanceRemoved { inst.lock(), inst.lock()->GetParent().value() });
inst.lock()->Serialize(rootDoc);
inst.lock()->SetParent(std::nullopt);
}
selection->Set({});
historyState.push_back(UndoStateSelectionChanged {selection->Get(), {}});
undoManager.PushState(historyState);
std::ostringstream encoded;
rootDoc.save(encoded);
@ -337,6 +334,7 @@ void MainWindow::connectActionHandlers() {
});
connect(ui->actionPaste, &QAction::triggered, this, [&]() {
UndoState historyState;
const QMimeData* mimeData = QApplication::clipboard()->mimeData();
if (!mimeData || !mimeData->hasFormat("application/xml")) return;
QByteArray bytes = mimeData->data("application/xml");
@ -348,14 +346,19 @@ void MainWindow::connectActionHandlers() {
for (pugi::xml_node instNode : rootDoc.children()) {
result<std::shared_ptr<Instance>, NoSuchInstance> inst = Instance::Deserialize(instNode);
if (!inst) { inst.logError(); continue; }
historyState.push_back(UndoStateInstanceCreated { inst.expect(), gWorkspace() });
gWorkspace()->AddChild(inst.expect());
}
undoManager.PushState(historyState);
});
connect(ui->actionPasteInto, &QAction::triggered, this, [&]() {
if (getSelection().size() != 1) return;
UndoState historyState;
std::shared_ptr<Selection> selection = gDataModel->GetService<Selection>();
if (selection->Get().size() != 1) return;
std::shared_ptr<Instance> selectedParent = getSelection()[0];
std::shared_ptr<Instance> selectedParent = selection->Get()[0];
const QMimeData* mimeData = QApplication::clipboard()->mimeData();
if (!mimeData || !mimeData->hasFormat("application/xml")) return;
@ -368,16 +371,22 @@ void MainWindow::connectActionHandlers() {
for (pugi::xml_node instNode : rootDoc.children()) {
result<std::shared_ptr<Instance>, NoSuchInstance> inst = Instance::Deserialize(instNode);
if (!inst) { inst.logError(); continue; }
historyState.push_back(UndoStateInstanceCreated { inst.expect(), selectedParent });
selectedParent->AddChild(inst.expect());
}
undoManager.PushState(historyState);
});
connect(ui->actionGroupObjects, &QAction::triggered, this, [&]() {
UndoState historyState;
auto model = Model::New();
std::shared_ptr<Instance> firstParent;
for (auto object : getSelection()) {
std::shared_ptr<Selection> selection = gDataModel->GetService<Selection>();
for (auto object : selection->Get()) {
if (firstParent == nullptr && object->GetParent().has_value()) firstParent = object->GetParent().value();
historyState.push_back(UndoStateInstanceReparented { object, object->GetParent().value(), model });
object->SetParent(model);
}
@ -387,28 +396,35 @@ void MainWindow::connectActionHandlers() {
// Technically not how it works in the actual studio, but it's not an API-breaking change
// and I think this implementation is more useful so I'm sticking with it
if (firstParent == nullptr) firstParent = gWorkspace();
historyState.push_back(UndoStateInstanceCreated { model, firstParent });
model->SetParent(firstParent);
setSelection({ model });
historyState.push_back(UndoStateSelectionChanged { selection->Get(), { model } });
selection->Set({ model });
playSound("./assets/excluded/electronicpingshort.wav");
});
connect(ui->actionUngroupObjects, &QAction::triggered, this, [&]() {
UndoState historyState;
std::vector<std::shared_ptr<Instance>> newSelection;
for (auto model : getSelection()) {
std::shared_ptr<Selection> selection = gDataModel->GetService<Selection>();
for (auto model : selection->Get()) {
// Not a model, skip
if (!model->IsA<Model>()) { newSelection.push_back(model); continue; }
for (auto object : model->GetChildren()) {
historyState.push_back(UndoStateInstanceReparented { object, object->GetParent().value(), model->GetParent().value() });
object->SetParent(model->GetParent());
newSelection.push_back(object);
}
model->Destroy();
historyState.push_back(UndoStateInstanceRemoved { model, model->GetParent().value() });
model->SetParent(std::nullopt);
}
setSelection(newSelection);
historyState.push_back(UndoStateSelectionChanged { selection->Get(), newSelection });
selection->Set(newSelection);
playSound("./assets/excluded/electronicpingshort.wav");
});
@ -421,7 +437,8 @@ void MainWindow::connectActionHandlers() {
pugi::xml_document modelDoc;
pugi::xml_node modelRoot = modelDoc.append_child("openblocks");
for (std::weak_ptr<Instance> inst : getSelection()) {
std::shared_ptr<Selection> selection = gDataModel->GetService<Selection>();
for (std::weak_ptr<Instance> inst : selection->Get()) {
if (inst.expired()) continue;
inst.lock()->Serialize(modelRoot);
}
@ -430,8 +447,10 @@ void MainWindow::connectActionHandlers() {
});
connect(ui->actionInsertModel, &QAction::triggered, this, [&]() {
if (getSelection().size() != 1) return;
std::shared_ptr<Instance> selectedParent = getSelection()[0];
UndoState historyState;
std::shared_ptr<Selection> selection = gDataModel->GetService<Selection>();
if (selection->Get().size() != 1) return;
std::shared_ptr<Instance> selectedParent = selection->Get()[0];
std::optional<std::string> path = openFileDialog("Openblocks Model (*.obm)", ".obm", QFileDialog::AcceptOpen);
if (!path) return;
@ -443,10 +462,19 @@ void MainWindow::connectActionHandlers() {
for (pugi::xml_node instNode : modelDoc.child("openblocks").children("Item")) {
result<std::shared_ptr<Instance>, NoSuchInstance> inst = Instance::Deserialize(instNode);
if (!inst) { inst.logError(); continue; }
historyState.push_back(UndoStateInstanceCreated { inst.expect(), selectedParent });
selectedParent->AddChild(inst.expect());
}
});
connect(ui->actionUndo, &QAction::triggered, this, [&]() {
undoManager.Undo();
});
connect(ui->actionRedo, &QAction::triggered, this, [&]() {
undoManager.Redo();
});
connect(ui->actionAbout, &QAction::triggered, this, [this]() {
AboutDialog* aboutDialog = new AboutDialog(this);
aboutDialog->open();

View file

@ -6,6 +6,7 @@
#include "qbasictimer.h"
#include "qcoreevent.h"
#include "script/scriptdocument.h"
#include "undohistory.h"
#include <QMainWindow>
#include <QLineEdit>
#include <map>
@ -49,6 +50,8 @@ class MainWindow : public QMainWindow
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
UndoHistory undoManager;
SelectedTool selectedTool;
GridSnappingMode snappingMode;
@ -60,6 +63,8 @@ public:
void openFile(std::string path);
Ui::MainWindow *ui;
friend PlaceDocument;
private:
PlaceDocument* placeDocument;
std::map<std::shared_ptr<Script>, ScriptDocument*> scriptDocuments;

View file

@ -151,6 +151,8 @@
<addaction name="actionNew"/>
<addaction name="actionOpen"/>
<addaction name="actionSave"/>
<addaction name="actionUndo"/>
<addaction name="actionRedo"/>
</widget>
<widget class="QToolBar" name="transformTools">
<property name="windowTitle">
@ -816,6 +818,34 @@
<string>About...</string>
</property>
</action>
<action name="actionUndo">
<property name="icon">
<iconset theme="edit-undo"/>
</property>
<property name="text">
<string>Undo</string>
</property>
<property name="shortcut">
<string>Ctrl+Z</string>
</property>
<property name="menuRole">
<enum>QAction::MenuRole::NoRole</enum>
</property>
</action>
<action name="actionRedo">
<property name="icon">
<iconset theme="edit-redo"/>
</property>
<property name="text">
<string>Redo</string>
</property>
<property name="shortcut">
<string>Ctrl+Y</string>
</property>
<property name="menuRole">
<enum>QAction::MenuRole::NoRole</enum>
</property>
</action>
</widget>
<customwidgets>
<customwidget>

View file

@ -5,6 +5,8 @@
#include "objects/base/instance.h"
#include "objects/meta.h"
#include "objects/script.h"
#include "objects/service/selection.h"
#include "undohistory.h"
#include <memory>
#include <qaction.h>
#include <qtreeview.h>
@ -37,6 +39,10 @@ ExplorerView::ExplorerView(QWidget* parent):
});
connect(selectionModel(), &QItemSelectionModel::selectionChanged, this, [&](const QItemSelection &selected, const QItemSelection &deselected) {
// Simple, good old debounce.
if (handlingSelectionUpdate)
return;
std::vector<std::shared_ptr<Instance>> selectedInstances;
selectedInstances.reserve(selectedIndexes().count()); // This doesn't reserve everything, but should enhance things anyway
@ -44,20 +50,23 @@ ExplorerView::ExplorerView(QWidget* parent):
selectedInstances.push_back(reinterpret_cast<Instance*>(index.internalPointer())->shared_from_this());
}
::setSelection(selectedInstances, true);
std::shared_ptr<Selection> selection = gDataModel->GetService<Selection>();
selection->Set(selectedInstances);
});
addSelectionListener([&](auto oldSelection, auto newSelection, bool fromExplorer) {
// It's from us, ignore it.
if (fromExplorer) return;
}
this->clearSelection();
for (std::weak_ptr<Instance> inst : newSelection) {
if (inst.expired()) continue;
QModelIndex index = this->model.ObjectToIndex(inst.lock());
this->selectionModel()->select(index, QItemSelectionModel::SelectionFlag::Select);
}
});
void ExplorerView::setSelectedObjects(std::vector<std::shared_ptr<Instance>> selection) {
handlingSelectionUpdate = true;
this->clearSelection();
for (std::weak_ptr<Instance> inst : selection) {
if (inst.expired()) continue;
QModelIndex index = this->model.ObjectToIndex(inst.lock());
this->selectionModel()->select(index, QItemSelectionModel::SelectionFlag::Select);
}
handlingSelectionUpdate = false;
}
ExplorerView::~ExplorerView() {
@ -103,10 +112,12 @@ void ExplorerView::buildContextMenu() {
QAction* instAction = new QAction(model.iconOf(type), QString::fromStdString(type->className));
insertObjectMenu->addAction(instAction);
connect(instAction, &QAction::triggered, this, [&]() {
if (getSelection().size() == 0) return;
std::shared_ptr<Instance> instParent = getSelection()[0];
std::shared_ptr<Selection> selection = gDataModel->GetService<Selection>();
if (selection->Get().size() == 0) return;
std::shared_ptr<Instance> instParent = selection->Get()[0];
std::shared_ptr<Instance> newInst = type->constructor();
newInst->SetParent(instParent);
M_mainWindow->undoManager.PushState({ UndoStateInstanceCreated { newInst, instParent } });
});
}
}

View file

@ -1,12 +1,14 @@
#pragma once
#include "panes/explorermodel.h"
#include <memory>
#include <qmenu.h>
#include <qtreeview.h>
class Ui_MainWindow;
class ExplorerView : public QTreeView {
bool handlingSelectionUpdate = false;
public:
ExplorerView(QWidget* parent = nullptr);
~ExplorerView() override;
@ -17,6 +19,8 @@ public:
void buildContextMenu();
void updateRoot(std::shared_ptr<Instance> newRoot);
void setSelectedObjects(std::vector<std::shared_ptr<Instance>> selection);
private:
ExplorerModel model;
QMenu contextMenu;

View file

@ -4,7 +4,9 @@
#include "datatypes/variant.h"
#include "datatypes/primitives.h"
#include "error/data.h"
#include "mainwindow.h"
#include "objects/base/member.h"
#include "undohistory.h"
#include <QColorDialog>
#include <QComboBox>
@ -206,6 +208,8 @@ public:
: view->itemFromIndex(index.parent())->data(0, Qt::DisplayRole).toString().toStdString();
PropertyMeta meta = inst->GetPropertyMeta(propertyName).expect();
Variant oldValue = inst->GetProperty(propertyName).expect();
if (isComposite) {
if (meta.type.descriptor == &Vector3::TYPE) {
QDoubleSpinBox* spinBox = dynamic_cast<QDoubleSpinBox*>(editor);
@ -264,12 +268,15 @@ public:
model->setData(index, QString::fromStdString(parsedValue.ToString()));
view->rebuildCompositeProperty(view->itemFromIndex(index), meta.type.descriptor, parsedValue);
}
Variant newValue = inst->GetProperty(propertyName).expect();
view->undoManager->PushState({ UndoStatePropertyChanged { inst, propertyName, oldValue, newValue } });
}
};
PropertiesView::PropertiesView(QWidget* parent):
QTreeWidget(parent) {
clear();
setHeaderHidden(true);
setColumnCount(2);
@ -300,6 +307,10 @@ QStringList PROPERTY_CATEGORY_NAMES {
"Surface Inputs",
};
void PropertiesView::init() {
undoManager = &dynamic_cast<MainWindow*>(window())->undoManager;
}
QModelIndex PropertiesView::indexAt(const QPoint &point) const {
return QTreeWidget::indexAt(point + QPoint(indentation(), 0));
}
@ -402,6 +413,7 @@ void PropertiesView::propertyChanged(QTreeWidgetItem *item, int column) {
if (meta.type.descriptor == &BOOL_TYPE) {
inst->SetProperty(propertyName, item->checkState(1) == Qt::Checked).expect();
undoManager->PushState({ UndoStatePropertyChanged { inst, propertyName, item->checkState(1) != Qt::Checked, item->checkState(1) == Qt::Checked } });
}
}

View file

@ -3,6 +3,7 @@
#include <QTreeWidget>
#include "datatypes/base.h"
#include "objects/base/instance.h"
#include "undohistory.h"
class Ui_MainWindow;
class PropertiesItemDelegate;
@ -18,6 +19,8 @@ class PropertiesView : public QTreeWidget {
void rebuildCompositeProperty(QTreeWidgetItem *item, const TypeDesc*, Variant);
void onPropertyUpdated(std::shared_ptr<Instance> instance, std::string property, Variant newValue);
UndoHistory* undoManager;
friend PropertiesItemDelegate;
protected:
void drawBranches(QPainter *painter, const QRect &rect, const QModelIndex &index) const override;
@ -26,5 +29,7 @@ public:
PropertiesView(QWidget* parent = nullptr);
~PropertiesView() override;
void init();
void setSelected(std::optional<std::shared_ptr<Instance>> instance);
};

View file

@ -1,10 +1,11 @@
#include "placedocument.h"
#include "common.h"
#include "datatypes/variant.h"
#include "mainglwidget.h"
#include "mainwindow.h"
#include "objects/joint/snap.h"
#include "objects/script.h"
#include "objects/script/scriptcontext.h"
#include "objects/service/script/scriptcontext.h"
#include "enum/surface.h"
#include <cstdio>
#include <memory>
@ -15,6 +16,8 @@
#include <qmdisubwindow.h>
#include <qlayout.h>
#include <qmimedata.h>
#include "../ui_mainwindow.h"
#include "objects/service/selection.h"
PlaceDocument::PlaceDocument(QWidget* parent):
QMdiSubWindow(parent) {
@ -24,6 +27,7 @@ PlaceDocument::PlaceDocument(QWidget* parent):
setWindowTitle("Place");
_runState = RUN_STOPPED;
updateSelectionListeners(gDataModel->GetService<Selection>());
}
PlaceDocument::~PlaceDocument() {
@ -41,7 +45,7 @@ void PlaceDocument::setRunState(RunState newState) {
std::shared_ptr<DataModel> newModel = editModeDataModel->CloneModel();
gDataModel = newModel;
gDataModel->Init(true);
setSelection({});
updateSelectionListeners(gDataModel->GetService<Selection>());
} else if (newState == RUN_PAUSED && _runState == RUN_RUNNING) {
_runState = RUN_PAUSED;
} else if (newState == RUN_STOPPED) {
@ -49,10 +53,28 @@ void PlaceDocument::setRunState(RunState newState) {
// TODO: GC: Check to make sure gDataModel gets properly garbage collected prior to this
gDataModel = editModeDataModel;
setSelection({});
updateSelectionListeners(gDataModel->GetService<Selection>());
}
}
void PlaceDocument::updateSelectionListeners(std::shared_ptr<Selection> selection) {
MainWindow* mainWnd = dynamic_cast<MainWindow*>(window());
if (!selectionConnection.expired())
selectionConnection.lock()->Disconnect();
selectionConnection = selection->SelectionChanged->Connect([selection, mainWnd](std::vector<Variant> _){
// Update properties
if (selection->Get().size() != 1)
mainWnd->ui->propertiesView->setSelected(std::nullopt);
else
mainWnd->ui->propertiesView->setSelected(selection->Get()[0]);
// Update explorer
mainWnd->ui->explorerView->setSelectedObjects(selection->Get());
});
}
void PlaceDocument::closeEvent(QCloseEvent *closeEvent) {
// Placeholder
closeEvent->ignore();

View file

@ -1,10 +1,13 @@
#pragma once
#include "datatypes/signal.h"
#include "mainglwidget.h"
#include <qevent.h>
#include <qmdisubwindow.h>
#include <QBasicTimer>
class Selection;
enum RunState {
RUN_STOPPED,
RUN_RUNNING,
@ -15,7 +18,10 @@ class PlaceDocument : public QMdiSubWindow {
QBasicTimer timer;
RunState _runState;
std::weak_ptr<SignalConnection> selectionConnection;
void timerEvent(QTimerEvent*) override;
void updateSelectionListeners(std::shared_ptr<Selection>);
public:
MainGLWidget* placeWidget;
PlaceDocument(QWidget* parent = nullptr);

74
editor/undohistory.cpp Normal file
View file

@ -0,0 +1,74 @@
#include "undohistory.h"
#include "common.h"
#include "objects/service/selection.h"
void UndoHistory::PushState(UndoState state) {
if (processingUndo) return; // Ignore PushState requests when changes are initiated by us
redoHistory = {};
if (maxBufferSize != -1 && (int)undoHistory.size() > maxBufferSize)
undoHistory.erase(undoHistory.begin(), undoHistory.begin()+maxBufferSize-(int)undoHistory.size()-1);
undoHistory.push_back(state);
undoStateListener(!undoHistory.empty(), !redoHistory.empty());
}
void UndoHistory::Undo() {
if (undoHistory.size() == 0) return;
UndoState state = undoHistory.back();
undoHistory.pop_back();
redoHistory.push(state);
processingUndo = true;
for (UndoStateChange& change : state) {
// https://stackoverflow.com/a/63483353
if (auto v = std::get_if<UndoStatePropertyChanged>(&change)) {
// The old value used to be valid, so it still should be...
v->affectedInstance->SetProperty(v->property, v->oldValue).expect();
} else if (auto v = std::get_if<UndoStateInstanceCreated>(&change)) {
v->instance->SetParent(std::nullopt);
} else if (auto v = std::get_if<UndoStateInstanceRemoved>(&change)) {
v->instance->SetParent(v->oldParent);
} else if (auto v = std::get_if<UndoStateInstanceReparented>(&change)) {
v->instance->SetParent(v->oldParent);
} else if (auto v = std::get_if<UndoStateSelectionChanged>(&change)) {
gDataModel->GetService<Selection>()->Set(v->oldSelection);
}
}
processingUndo = false;
undoStateListener(!undoHistory.empty(), !redoHistory.empty());
}
void UndoHistory::Redo() {
if (redoHistory.size() == 0) return;
UndoState state = redoHistory.top();
redoHistory.pop();
undoHistory.push_back(state);
processingUndo = true;
for (UndoStateChange& change : state) {
// https://stackoverflow.com/a/63483353
if (auto v = std::get_if<UndoStatePropertyChanged>(&change)) {
// The old value used to be valid, so it still should be...
v->affectedInstance->SetProperty(v->property, v->newValue).expect();
} else if (auto v = std::get_if<UndoStateInstanceCreated>(&change)) {
v->instance->SetParent(v->newParent);
} else if (auto v = std::get_if<UndoStateInstanceRemoved>(&change)) {
v->instance->SetParent(std::nullopt);
} else if (auto v = std::get_if<UndoStateInstanceReparented>(&change)) {
v->instance->SetParent(v->newParent);
} else if (auto v = std::get_if<UndoStateSelectionChanged>(&change)) {
gDataModel->GetService<Selection>()->Set(v->newSelection);
}
}
processingUndo = false;
undoStateListener(!undoHistory.empty(), !redoHistory.empty());
}
void UndoHistory::SetUndoStateListener(UndoStateChangedListener listener) {
undoStateListener = listener;
}

58
editor/undohistory.h Normal file
View file

@ -0,0 +1,58 @@
#pragma once
#include "datatypes/signal.h"
#include "datatypes/variant.h"
#include "objects/base/instance.h"
#include "utils.h"
#include <deque>
#include <memory>
#include <stack>
struct UndoStatePropertyChanged {
std::shared_ptr<Instance> affectedInstance;
std::string property;
Variant oldValue;
Variant newValue;
};
struct UndoStateInstanceCreated {
std::shared_ptr<Instance> instance;
std::shared_ptr<Instance> newParent;
};
struct UndoStateInstanceRemoved {
std::shared_ptr<Instance> instance;
std::shared_ptr<Instance> oldParent;
};
struct UndoStateInstanceReparented {
std::shared_ptr<Instance> instance;
nullable std::shared_ptr<Instance> oldParent;
nullable std::shared_ptr<Instance> newParent;
};
struct UndoStateSelectionChanged {
std::vector<std::shared_ptr<Instance>> oldSelection;
std::vector<std::shared_ptr<Instance>> newSelection;
};
typedef std::variant<UndoStatePropertyChanged, UndoStateInstanceCreated, UndoStateInstanceRemoved, UndoStateInstanceReparented, UndoStateSelectionChanged> UndoStateChange;
typedef std::vector<UndoStateChange> UndoState;
typedef std::function<void(bool canUndo, bool canRedo)> UndoStateChangedListener;
class UndoHistory {
// Ignore PushState requests
bool processingUndo = false;
std::deque<UndoState> undoHistory;
std::stack<UndoState> redoHistory;
UndoStateChangedListener undoStateListener;
public:
int maxBufferSize = 100;
void PushState(UndoState);
void Undo();
void Redo();
void SetUndoStateListener(UndoStateChangedListener listener);
};