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<std::shared_ptr<Instance>> currentSelection;
std::vector<SelectionUpdateHandler> selectionUpdateListeners;
std::vector<PropertyUpdateHandler> propertyUpdatelisteners; 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) { void sendPropertyUpdatedSignal(std::shared_ptr<Instance> instance, std::string property, Variant newValue) {
for (PropertyUpdateHandler handler : propertyUpdatelisteners) { for (PropertyUpdateHandler handler : propertyUpdatelisteners) {

View file

@ -1,7 +1,7 @@
#pragma once #pragma once
#include "objects/base/instance.h" #include "objects/base/instance.h"
#include "handles.h" #include "handles.h"
#include "objects/workspace.h" #include "objects/service/workspace.h"
#include "objects/datamodel.h" #include "objects/datamodel.h"
#include "camera.h" #include "camera.h"
#include <functional> #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> 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)> 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::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; typedef std::function<void(std::shared_ptr<Instance> instance, std::string property, Variant newValue)> PropertyUpdateHandler;
// TEMPORARY COMMON DATA FOR VARIOUS INTERNAL COMPONENTS // TEMPORARY COMMON DATA FOR VARIOUS INTERNAL COMPONENTS
@ -24,9 +23,5 @@ extern std::optional<HierarchyPreUpdateHandler> hierarchyPreUpdateHandler;
extern std::optional<HierarchyPostUpdateHandler> hierarchyPostUpdateHandler; extern std::optional<HierarchyPostUpdateHandler> hierarchyPostUpdateHandler;
extern Handles editorToolHandles; 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 sendPropertyUpdatedSignal(std::shared_ptr<Instance> instance, std::string property, Variant newValue);
void addPropertyUpdateListener(PropertyUpdateHandler handler); void addPropertyUpdateListener(PropertyUpdateHandler handler);

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,6 +1,6 @@
#include "serverscriptservice.h" #include "serverscriptservice.h"
#include "objects/script.h" #include "objects/script.h"
#include "objects/workspace.h" #include "objects/service/workspace.h"
#include "objects/datamodel.h" #include "objects/datamodel.h"
ServerScriptService::ServerScriptService(): Service(&TYPE) { 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/ref.h"
#include "datatypes/vector.h" #include "datatypes/vector.h"
#include "objects/base/instance.h" #include "objects/base/instance.h"
#include "objects/jointsservice.h" #include "objects/service/jointsservice.h"
#include "objects/joint/jointinstance.h" #include "objects/joint/jointinstance.h"
#include "objects/datamodel.h" #include "objects/datamodel.h"
#include "physics/util.h" #include "physics/util.h"

View file

@ -6,6 +6,7 @@
#include "math_helper.h" #include "math_helper.h"
#include "objects/base/instance.h" #include "objects/base/instance.h"
#include "objects/part.h" #include "objects/part.h"
#include "objects/service/selection.h"
#include <glm/common.hpp> #include <glm/common.hpp>
#include <memory> #include <memory>
#include <vector> #include <vector>
@ -54,6 +55,10 @@ PartAssembly PartAssembly::FromSelection(std::vector<std::shared_ptr<Instance>>
return PartAssembly(selection, editorToolHandles.worldMode); return PartAssembly(selection, editorToolHandles.worldMode);
} }
PartAssembly PartAssembly::FromSelection(std::shared_ptr<Selection> selection) {
return FromSelection(selection->Get());
}
void PartAssembly::SetCollisionsEnabled(bool enabled) { void PartAssembly::SetCollisionsEnabled(bool enabled) {
for (auto part : parts) { for (auto part : parts) {
part->rigidBody->getCollider(0)->setIsWorldQueryCollider(enabled); part->rigidBody->getCollider(0)->setIsWorldQueryCollider(enabled);
@ -113,3 +118,17 @@ void PartAssembly::Scale(Vector3 newSize, bool scaleUp) {
_bounds = _bounds * factor; _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 Part;
class Instance; 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 { class PartAssembly {
CFrame _assemblyOrigin; CFrame _assemblyOrigin;
@ -18,13 +23,17 @@ class PartAssembly {
public: public:
PartAssembly(std::vector<std::shared_ptr<Part>>, bool worldMode = false); 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 CFrame assemblyOrigin() { return _assemblyOrigin; };
inline Vector3 bounds() { return _bounds; }; inline Vector3 bounds() { return _bounds; };
inline Vector3 size() { return _size; }; inline Vector3 size() { return _size; };
inline bool multipleSelected() { return parts.size() > 1; } 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 // Transforms the assembly such that newOrigin is now this assembly's new assemblyOrigin
void SetOrigin(CFrame newOrigin); void SetOrigin(CFrame newOrigin);

View file

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

View file

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

View file

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

View file

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

View file

@ -151,6 +151,8 @@
<addaction name="actionNew"/> <addaction name="actionNew"/>
<addaction name="actionOpen"/> <addaction name="actionOpen"/>
<addaction name="actionSave"/> <addaction name="actionSave"/>
<addaction name="actionUndo"/>
<addaction name="actionRedo"/>
</widget> </widget>
<widget class="QToolBar" name="transformTools"> <widget class="QToolBar" name="transformTools">
<property name="windowTitle"> <property name="windowTitle">
@ -816,6 +818,34 @@
<string>About...</string> <string>About...</string>
</property> </property>
</action> </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> </widget>
<customwidgets> <customwidgets>
<customwidget> <customwidget>

View file

@ -5,6 +5,8 @@
#include "objects/base/instance.h" #include "objects/base/instance.h"
#include "objects/meta.h" #include "objects/meta.h"
#include "objects/script.h" #include "objects/script.h"
#include "objects/service/selection.h"
#include "undohistory.h"
#include <memory> #include <memory>
#include <qaction.h> #include <qaction.h>
#include <qtreeview.h> #include <qtreeview.h>
@ -37,6 +39,10 @@ ExplorerView::ExplorerView(QWidget* parent):
}); });
connect(selectionModel(), &QItemSelectionModel::selectionChanged, this, [&](const QItemSelection &selected, const QItemSelection &deselected) { 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; std::vector<std::shared_ptr<Instance>> selectedInstances;
selectedInstances.reserve(selectedIndexes().count()); // This doesn't reserve everything, but should enhance things anyway 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()); 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(); void ExplorerView::setSelectedObjects(std::vector<std::shared_ptr<Instance>> selection) {
for (std::weak_ptr<Instance> inst : newSelection) { handlingSelectionUpdate = true;
if (inst.expired()) continue;
QModelIndex index = this->model.ObjectToIndex(inst.lock()); this->clearSelection();
this->selectionModel()->select(index, QItemSelectionModel::SelectionFlag::Select); 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() { ExplorerView::~ExplorerView() {
@ -103,10 +112,12 @@ void ExplorerView::buildContextMenu() {
QAction* instAction = new QAction(model.iconOf(type), QString::fromStdString(type->className)); QAction* instAction = new QAction(model.iconOf(type), QString::fromStdString(type->className));
insertObjectMenu->addAction(instAction); insertObjectMenu->addAction(instAction);
connect(instAction, &QAction::triggered, this, [&]() { connect(instAction, &QAction::triggered, this, [&]() {
if (getSelection().size() == 0) return; std::shared_ptr<Selection> selection = gDataModel->GetService<Selection>();
std::shared_ptr<Instance> instParent = getSelection()[0]; if (selection->Get().size() == 0) return;
std::shared_ptr<Instance> instParent = selection->Get()[0];
std::shared_ptr<Instance> newInst = type->constructor(); std::shared_ptr<Instance> newInst = type->constructor();
newInst->SetParent(instParent); newInst->SetParent(instParent);
M_mainWindow->undoManager.PushState({ UndoStateInstanceCreated { newInst, instParent } });
}); });
} }
} }

View file

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

View file

@ -4,7 +4,9 @@
#include "datatypes/variant.h" #include "datatypes/variant.h"
#include "datatypes/primitives.h" #include "datatypes/primitives.h"
#include "error/data.h" #include "error/data.h"
#include "mainwindow.h"
#include "objects/base/member.h" #include "objects/base/member.h"
#include "undohistory.h"
#include <QColorDialog> #include <QColorDialog>
#include <QComboBox> #include <QComboBox>
@ -206,6 +208,8 @@ public:
: view->itemFromIndex(index.parent())->data(0, Qt::DisplayRole).toString().toStdString(); : view->itemFromIndex(index.parent())->data(0, Qt::DisplayRole).toString().toStdString();
PropertyMeta meta = inst->GetPropertyMeta(propertyName).expect(); PropertyMeta meta = inst->GetPropertyMeta(propertyName).expect();
Variant oldValue = inst->GetProperty(propertyName).expect();
if (isComposite) { if (isComposite) {
if (meta.type.descriptor == &Vector3::TYPE) { if (meta.type.descriptor == &Vector3::TYPE) {
QDoubleSpinBox* spinBox = dynamic_cast<QDoubleSpinBox*>(editor); QDoubleSpinBox* spinBox = dynamic_cast<QDoubleSpinBox*>(editor);
@ -264,6 +268,9 @@ public:
model->setData(index, QString::fromStdString(parsedValue.ToString())); model->setData(index, QString::fromStdString(parsedValue.ToString()));
view->rebuildCompositeProperty(view->itemFromIndex(index), meta.type.descriptor, parsedValue); view->rebuildCompositeProperty(view->itemFromIndex(index), meta.type.descriptor, parsedValue);
} }
Variant newValue = inst->GetProperty(propertyName).expect();
view->undoManager->PushState({ UndoStatePropertyChanged { inst, propertyName, oldValue, newValue } });
} }
}; };
@ -300,6 +307,10 @@ QStringList PROPERTY_CATEGORY_NAMES {
"Surface Inputs", "Surface Inputs",
}; };
void PropertiesView::init() {
undoManager = &dynamic_cast<MainWindow*>(window())->undoManager;
}
QModelIndex PropertiesView::indexAt(const QPoint &point) const { QModelIndex PropertiesView::indexAt(const QPoint &point) const {
return QTreeWidget::indexAt(point + QPoint(indentation(), 0)); return QTreeWidget::indexAt(point + QPoint(indentation(), 0));
} }
@ -402,6 +413,7 @@ void PropertiesView::propertyChanged(QTreeWidgetItem *item, int column) {
if (meta.type.descriptor == &BOOL_TYPE) { if (meta.type.descriptor == &BOOL_TYPE) {
inst->SetProperty(propertyName, item->checkState(1) == Qt::Checked).expect(); 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 <QTreeWidget>
#include "datatypes/base.h" #include "datatypes/base.h"
#include "objects/base/instance.h" #include "objects/base/instance.h"
#include "undohistory.h"
class Ui_MainWindow; class Ui_MainWindow;
class PropertiesItemDelegate; class PropertiesItemDelegate;
@ -18,6 +19,8 @@ class PropertiesView : public QTreeWidget {
void rebuildCompositeProperty(QTreeWidgetItem *item, const TypeDesc*, Variant); void rebuildCompositeProperty(QTreeWidgetItem *item, const TypeDesc*, Variant);
void onPropertyUpdated(std::shared_ptr<Instance> instance, std::string property, Variant newValue); void onPropertyUpdated(std::shared_ptr<Instance> instance, std::string property, Variant newValue);
UndoHistory* undoManager;
friend PropertiesItemDelegate; friend PropertiesItemDelegate;
protected: protected:
void drawBranches(QPainter *painter, const QRect &rect, const QModelIndex &index) const override; void drawBranches(QPainter *painter, const QRect &rect, const QModelIndex &index) const override;
@ -26,5 +29,7 @@ public:
PropertiesView(QWidget* parent = nullptr); PropertiesView(QWidget* parent = nullptr);
~PropertiesView() override; ~PropertiesView() override;
void init();
void setSelected(std::optional<std::shared_ptr<Instance>> instance); void setSelected(std::optional<std::shared_ptr<Instance>> instance);
}; };

View file

@ -1,10 +1,11 @@
#include "placedocument.h" #include "placedocument.h"
#include "common.h" #include "common.h"
#include "datatypes/variant.h"
#include "mainglwidget.h" #include "mainglwidget.h"
#include "mainwindow.h" #include "mainwindow.h"
#include "objects/joint/snap.h" #include "objects/joint/snap.h"
#include "objects/script.h" #include "objects/script.h"
#include "objects/script/scriptcontext.h" #include "objects/service/script/scriptcontext.h"
#include "enum/surface.h" #include "enum/surface.h"
#include <cstdio> #include <cstdio>
#include <memory> #include <memory>
@ -15,6 +16,8 @@
#include <qmdisubwindow.h> #include <qmdisubwindow.h>
#include <qlayout.h> #include <qlayout.h>
#include <qmimedata.h> #include <qmimedata.h>
#include "../ui_mainwindow.h"
#include "objects/service/selection.h"
PlaceDocument::PlaceDocument(QWidget* parent): PlaceDocument::PlaceDocument(QWidget* parent):
QMdiSubWindow(parent) { QMdiSubWindow(parent) {
@ -24,6 +27,7 @@ PlaceDocument::PlaceDocument(QWidget* parent):
setWindowTitle("Place"); setWindowTitle("Place");
_runState = RUN_STOPPED; _runState = RUN_STOPPED;
updateSelectionListeners(gDataModel->GetService<Selection>());
} }
PlaceDocument::~PlaceDocument() { PlaceDocument::~PlaceDocument() {
@ -41,7 +45,7 @@ void PlaceDocument::setRunState(RunState newState) {
std::shared_ptr<DataModel> newModel = editModeDataModel->CloneModel(); std::shared_ptr<DataModel> newModel = editModeDataModel->CloneModel();
gDataModel = newModel; gDataModel = newModel;
gDataModel->Init(true); gDataModel->Init(true);
setSelection({}); updateSelectionListeners(gDataModel->GetService<Selection>());
} else if (newState == RUN_PAUSED && _runState == RUN_RUNNING) { } else if (newState == RUN_PAUSED && _runState == RUN_RUNNING) {
_runState = RUN_PAUSED; _runState = RUN_PAUSED;
} else if (newState == RUN_STOPPED) { } 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 // TODO: GC: Check to make sure gDataModel gets properly garbage collected prior to this
gDataModel = editModeDataModel; 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) { void PlaceDocument::closeEvent(QCloseEvent *closeEvent) {
// Placeholder // Placeholder
closeEvent->ignore(); closeEvent->ignore();

View file

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