From 45ae2f2164c7df89721dd1fbbca1eceb95247470 Mon Sep 17 00:00:00 2001 From: Jean Philippe Date: Wed, 18 Nov 2026 11:35:29 +0900 Subject: [PATCH] feat(editor): suspend retained authoring sessions --- Tetragrama/Editor.h | 4 +- Tetragrama/EditorPlayCoordinator.cpp | 170 ++++++++++++++++++ Tetragrama/EditorPlayCoordinator.h | 83 +++++++++ Tetragrama/EditorSession.cpp | 48 ++++- Tetragrama/EditorSession.h | 17 +- Tetragrama/tests/CMakeLists.txt | 1 + .../tests/EditorPlayCoordinator_test.cpp | 155 ++++++++++++++++ Tetragrama/tests/EditorSession_test.cpp | 62 +++++++ docs/design/future-plan/editor-play-mode.md | 2 + .../future-plan/m3-service-inventory.md | 34 ++++ 10 files changed, 568 insertions(+), 8 deletions(-) create mode 100644 Tetragrama/EditorPlayCoordinator.cpp create mode 100644 Tetragrama/EditorPlayCoordinator.h create mode 100644 Tetragrama/tests/EditorPlayCoordinator_test.cpp create mode 100644 docs/design/future-plan/m3-service-inventory.md diff --git a/Tetragrama/Editor.h b/Tetragrama/Editor.h index d047164d3..86cbc920f 100644 --- a/Tetragrama/Editor.h +++ b/Tetragrama/Editor.h @@ -193,8 +193,8 @@ namespace Tetragrama virtual void OnClosed() override; void OnWorldShutdown(ZEngine::EngineContext& engine) override; bool OnCloseRequested() override; - /// The authoring world never simulates. Play requires a separate, complete - /// snapshot/restore lifecycle before this policy can be changed. + /// The authoring world never simulates. Play requires a separate runtime + /// world and a complete retained-authoring lifecycle before this policy changes. [[nodiscard]] bool ShouldSimulate() const final { return false; diff --git a/Tetragrama/EditorPlayCoordinator.cpp b/Tetragrama/EditorPlayCoordinator.cpp new file mode 100644 index 000000000..bdc486620 --- /dev/null +++ b/Tetragrama/EditorPlayCoordinator.cpp @@ -0,0 +1,170 @@ +#include +#include + +namespace Tetragrama +{ + using namespace ZEngine::ECS; + + bool EditorPlayCoordinator::OnOwnerThread() const noexcept + { + return m_owner == std::this_thread::get_id(); + } + + bool EditorPlayCoordinator::BeginTransition(Mode next, SceneRequestId* output) noexcept + { + if (!OnOwnerThread() || !output || m_active || !m_requests.Drained() || m_generation == std::numeric_limits::max()) + return false; + SceneRequestId request = {}; + if (!m_requests.Admit(m_generation, &request)) + return false; + // Drained admission has no outstanding asynchronous owner, so the + // freshly admitted request can always enter preparation on this thread. + if (!m_requests.TryStart(request)) + { + (void) m_requests.Fail(request, SceneLoadStage::Admission, SceneLoadError::Unavailable); + (void) m_requests.Acknowledge(request); + return false; + } + m_active = request; + m_mode = next; + *output = request; + return true; + } + + bool EditorPlayCoordinator::BeginEnter(SceneRequestId* output) noexcept + { + if (!OnOwnerThread() || m_mode != Mode::Edit || !BeginTransition(Mode::Starting, output)) + return false; + m_last_enter = *output; + return true; + } + + SceneCancelResult EditorPlayCoordinator::CancelEnter(SceneRequestId request) noexcept + { + if (!OnOwnerThread() || !request || request != m_last_enter) + return SceneCancelResult::NotFound; + const auto result = m_requests.Cancel(request); + if (result == SceneCancelResult::Cancelled && m_mode == Mode::Starting && request == m_active) + { + m_active = {}; + m_mode = Mode::Edit; + } + return result; + } + + bool EditorPlayCoordinator::FailTransition(Mode expected, Mode next, SceneRequestId request, SceneLoadStage stage, SceneLoadError error) noexcept + { + if (!OnOwnerThread() || m_mode != expected || request != m_active || !m_requests.Fail(request, stage, error)) + return false; + m_active = {}; + m_mode = next; + return true; + } + + bool EditorPlayCoordinator::FailEnter(SceneRequestId request, SceneLoadStage stage, SceneLoadError error) noexcept + { + return FailTransition(Mode::Starting, Mode::Edit, request, stage, error); + } + + bool EditorPlayCoordinator::BeginCommit(Mode expected, SceneRequestId request, uint64_t generation) noexcept + { + return OnOwnerThread() && m_mode == expected && request == m_active && generation == m_generation && m_requests.BeginCommit(request, generation); + } + + bool EditorPlayCoordinator::FinishCommit(Mode expected, Mode next, SceneRequestId request) noexcept + { + if (!OnOwnerThread() || m_mode != expected || request != m_active || m_generation == std::numeric_limits::max() || !m_requests.Commit(request, m_generation + 1)) + return false; + ++m_generation; + m_active = {}; + m_mode = next; + return true; + } + + bool EditorPlayCoordinator::BeginEnterCommit(SceneRequestId request, uint64_t generation) noexcept + { + return BeginCommit(Mode::Starting, request, generation); + } + + bool EditorPlayCoordinator::FinishEnterCommit(SceneRequestId request) noexcept + { + return FinishCommit(Mode::Starting, Mode::Play, request); + } + + bool EditorPlayCoordinator::Pause() noexcept + { + if (!OnOwnerThread() || m_mode != Mode::Play) + return false; + m_mode = Mode::Paused; + return true; + } + + bool EditorPlayCoordinator::Resume() noexcept + { + if (!OnOwnerThread() || m_mode != Mode::Paused) + return false; + m_mode = Mode::Play; + return true; + } + + bool EditorPlayCoordinator::BeginStep() noexcept + { + if (!OnOwnerThread() || m_mode != Mode::Paused) + return false; + m_mode = Mode::Stepping; + return true; + } + + bool EditorPlayCoordinator::FinishStep() noexcept + { + if (!OnOwnerThread() || m_mode != Mode::Stepping) + return false; + m_mode = Mode::Paused; + return true; + } + + bool EditorPlayCoordinator::BeginStop(SceneRequestId* output) noexcept + { + return OnOwnerThread() && (m_mode == Mode::Play || m_mode == Mode::Paused || m_mode == Mode::ReturnError) && BeginTransition(Mode::Stopping, output); + } + + bool EditorPlayCoordinator::FailStop(SceneRequestId request, SceneLoadStage stage, SceneLoadError error) noexcept + { + return FailTransition(Mode::Stopping, Mode::ReturnError, request, stage, error); + } + + bool EditorPlayCoordinator::BeginStopCommit(SceneRequestId request, uint64_t generation) noexcept + { + return BeginCommit(Mode::Stopping, request, generation); + } + + bool EditorPlayCoordinator::FinishStopCommit(SceneRequestId request) noexcept + { + return FinishCommit(Mode::Stopping, Mode::Edit, request); + } + + bool EditorPlayCoordinator::Poll(SceneRequestId request, SceneLoadResult* output) const noexcept + { + return m_requests.Poll(request, output); + } + + bool EditorPlayCoordinator::Acknowledge(SceneRequestId request) noexcept + { + return m_requests.Acknowledge(request); + } + + bool EditorPlayCoordinator::FinishCleanup(SceneRequestId request) noexcept + { + return m_requests.FinishCleanup(request); + } + + EditorPlayCoordinator::Mode EditorPlayCoordinator::CurrentMode() const noexcept + { + return m_mode; + } + + uint64_t EditorPlayCoordinator::Generation() const noexcept + { + return m_generation; + } +} // namespace Tetragrama diff --git a/Tetragrama/EditorPlayCoordinator.h b/Tetragrama/EditorPlayCoordinator.h new file mode 100644 index 000000000..5978d27fa --- /dev/null +++ b/Tetragrama/EditorPlayCoordinator.h @@ -0,0 +1,83 @@ +#pragma once +#include +#include +#include + +namespace Tetragrama +{ + /// @brief Main-thread transition ledger for retained-authoring Play. + /// @details This ledger owns no worlds and performs no simulation or binding + /// switches. The host must prepare and guard those operations before commit, + /// and must drain worker/GPU owners before reporting cleanup complete. + class EditorPlayCoordinator final + { + public: + enum class Mode : uint8_t + { + Edit, + Starting, + Play, + Paused, + Stepping, + Stopping, + ReturnError + }; + + EditorPlayCoordinator() = default; + EditorPlayCoordinator(const EditorPlayCoordinator&) = delete; + EditorPlayCoordinator& operator=(const EditorPlayCoordinator&) = delete; + + /// @brief Admit one Enter request; outstanding cleanup blocks admission. + [[nodiscard]] bool BeginEnter(ZEngine::ECS::SceneRequestId* output) noexcept; + /// @brief Cancel Enter before commit; cleanup remains independently owned. + [[nodiscard]] ZEngine::ECS::SceneCancelResult CancelEnter(ZEngine::ECS::SceneRequestId request) noexcept; + /// @brief Fail Enter before commit, retaining the terminal result. + [[nodiscard]] bool FailEnter(ZEngine::ECS::SceneRequestId request, ZEngine::ECS::SceneLoadStage stage, ZEngine::ECS::SceneLoadError error) noexcept; + /// @brief Seal a prepared Enter against cancellation and reentrant transitions. + [[nodiscard]] bool BeginEnterCommit(ZEngine::ECS::SceneRequestId request, uint64_t expected_generation) noexcept; + /// @brief Record a successfully published Enter after the host switches bindings. + [[nodiscard]] bool FinishEnterCommit(ZEngine::ECS::SceneRequestId request) noexcept; + /// @brief Pause simulation without restoring authoring. + [[nodiscard]] bool Pause() noexcept; + /// @brief Resume continuous simulation from Paused. + [[nodiscard]] bool Resume() noexcept; + /// @brief Reserve a single paused step; the host executes it separately. + [[nodiscard]] bool BeginStep() noexcept; + /// @brief Finish a reserved step and return to Paused. + [[nodiscard]] bool FinishStep() noexcept; + /// @brief Admit Stop from Play, Paused, or a failed-return recovery state. + [[nodiscard]] bool BeginStop(ZEngine::ECS::SceneRequestId* output) noexcept; + /// @brief Record a failed return; retry remains possible after cleanup. + [[nodiscard]] bool FailStop(ZEngine::ECS::SceneRequestId request, ZEngine::ECS::SceneLoadStage stage, ZEngine::ECS::SceneLoadError error) noexcept; + /// @brief Seal a prepared return against reentrant transitions. + [[nodiscard]] bool BeginStopCommit(ZEngine::ECS::SceneRequestId request, uint64_t expected_generation) noexcept; + /// @brief Record the successful switch back to the retained authoring world. + [[nodiscard]] bool FinishStopCommit(ZEngine::ECS::SceneRequestId request) noexcept; + /// @brief Read a retained transition outcome on the owner thread. + [[nodiscard]] bool Poll(ZEngine::ECS::SceneRequestId request, ZEngine::ECS::SceneLoadResult* output) const noexcept; + /// @brief Release a terminal outcome; this does not imply cleanup is done. + [[nodiscard]] bool Acknowledge(ZEngine::ECS::SceneRequestId request) noexcept; + /// @brief Release request cleanup ownership after transfer or retirement. + /// @details A successful Enter may release its preparation record after + /// ownership transfers to the active host. Cancelled work and retired + /// worlds retain it until their external CPU/GPU users have drained. + [[nodiscard]] bool FinishCleanup(ZEngine::ECS::SceneRequestId request) noexcept; + /// @brief Return the owner-thread mode without enabling simulation. + [[nodiscard]] Mode CurrentMode() const noexcept; + /// @brief Return the owner-thread activation generation. + [[nodiscard]] uint64_t Generation() const noexcept; + + private: + [[nodiscard]] bool OnOwnerThread() const noexcept; + [[nodiscard]] bool BeginTransition(Mode next, ZEngine::ECS::SceneRequestId* output) noexcept; + [[nodiscard]] bool BeginCommit(Mode expected, ZEngine::ECS::SceneRequestId request, uint64_t generation) noexcept; + [[nodiscard]] bool FinishCommit(Mode expected, Mode next, ZEngine::ECS::SceneRequestId request) noexcept; + [[nodiscard]] bool FailTransition(Mode expected, Mode next, ZEngine::ECS::SceneRequestId request, ZEngine::ECS::SceneLoadStage stage, ZEngine::ECS::SceneLoadError error) noexcept; + const std::thread::id m_owner = std::this_thread::get_id(); + ZEngine::ECS::SceneLoadCoordinator m_requests = {}; + ZEngine::ECS::SceneRequestId m_active = {}; + ZEngine::ECS::SceneRequestId m_last_enter = {}; + Mode m_mode = Mode::Edit; + uint64_t m_generation = 1; + }; +} // namespace Tetragrama diff --git a/Tetragrama/EditorSession.cpp b/Tetragrama/EditorSession.cpp index 927cce65f..ed7d66ec8 100644 --- a/Tetragrama/EditorSession.cpp +++ b/Tetragrama/EditorSession.cpp @@ -302,7 +302,7 @@ namespace Tetragrama { // Owner identity is stable for the initialized lifetime. Reject other // threads before reading the main-thread-only mutable phase flag. - return m_owner == std::this_thread::get_id() && m_initialized && m_in_phase && !m_replacing; + return m_owner == std::this_thread::get_id() && m_initialized && m_in_phase && !m_replacing && !m_authoring_suspended; } EntityTarget EditorSession::TargetFor(EntityID entity) @@ -328,7 +328,7 @@ namespace Tetragrama bool EditorSession::Enqueue(const PendingRequest& request) { - if (!m_initialized || m_owner != std::this_thread::get_id() || m_replacing) + if (!m_initialized || m_owner != std::this_thread::get_id() || m_replacing || m_authoring_suspended) { return false; } @@ -1046,11 +1046,13 @@ namespace Tetragrama m_request_first = m_request_count = 0; m_in_phase = false; m_initialized = false; + m_authoring_suspended = false; + m_suspended_scene = nullptr; } bool EditorSession::BeginMutationPhase(bool editable) { - if (!m_initialized || m_in_phase || m_owner != std::this_thread::get_id() || m_replacing) + if (!m_initialized || m_in_phase || m_owner != std::this_thread::get_id() || m_replacing || m_authoring_suspended) { return false; } @@ -1084,6 +1086,42 @@ namespace Tetragrama } } + bool EditorSession::SuspendAuthoring() + { + if (!Allowed() || !m_editable || !m_scene) + return false; + + // Cancel before suspending: rollback must still have an editable owner. + Cancel(); + if (m_hierarchy_pending) + SynchronizeHierarchy(); + DiscardRequests(); + m_suspended_scene = m_scene; + m_suspended_epoch = m_epoch; + m_suspended_revision = m_document_revision; + m_suspended_structural = m_scene->StructuralRevision(); + m_suspended_hierarchy = m_scene->Hierarchy().Revision(); + m_editable = false; + m_in_phase = false; + m_authoring_suspended = true; + return true; + } + + bool EditorSession::ResumeAuthoring() + { + if (!m_initialized || m_owner != std::this_thread::get_id() || !m_authoring_suspended || m_in_phase || m_replacing || !m_scene || m_scene != m_suspended_scene || m_epoch != m_suspended_epoch || m_document_revision != m_suspended_revision || m_scene->StructuralRevision() != m_suspended_structural || m_scene->Hierarchy().Revision() != m_suspended_hierarchy) + return false; + m_suspended_scene = nullptr; + m_authoring_suspended = false; + m_editable = true; + return true; + } + + bool EditorSession::AuthoringSuspended() const noexcept + { + return m_authoring_suspended; + } + void EditorSession::SynchronizeHierarchy() { if (m_scene) @@ -1312,12 +1350,12 @@ namespace Tetragrama bool EditorSession::SetHovered(EntityID entity) { - return OnOwnerThread() && m_selection.SetHovered(m_targets, entity); + return OnOwnerThread() && !m_authoring_suspended && m_selection.SetHovered(m_targets, entity); } void EditorSession::ClearHovered() { - if (OnOwnerThread()) + if (OnOwnerThread() && !m_authoring_suspended) { m_selection.ClearHovered(); } diff --git a/Tetragrama/EditorSession.h b/Tetragrama/EditorSession.h index e75a731bc..4962d42db 100644 --- a/Tetragrama/EditorSession.h +++ b/Tetragrama/EditorSession.h @@ -128,6 +128,15 @@ namespace Tetragrama void Shutdown(); [[nodiscard]] bool BeginMutationPhase(bool editable = true); void EndMutationPhase(); + /// @brief Cancel transient edits and suspend authoring without replacing the scene or clearing history. + /// @details Owner-thread only, during an editable mutation phase. Pending + /// requests are discarded and new requests are rejected until resume. + [[nodiscard]] bool SuspendAuthoring(); + /// @brief Resume the retained scene if its identity and tracked revisions still match. + /// @details Failure leaves authoring suspended for recovery; it never reloads a scene. + [[nodiscard]] bool ResumeAuthoring(); + /// @brief Report on the owner thread whether authoring is suspended for a world transition. + [[nodiscard]] bool AuthoringSuspended() const noexcept; [[nodiscard]] bool BindScene(ZEngine::ECS::Scene* scene, bool saved = true); [[nodiscard]] bool SetSceneMutationHooks(const EditorSceneMutationHooks& hooks); [[nodiscard]] bool SetSceneSettingsHooks(const EditorSceneSettingsHooks& hooks); @@ -352,7 +361,7 @@ namespace Tetragrama } [[nodiscard]] bool Editable() const { - return m_initialized && !m_replacing && m_editable && m_scene; + return m_initialized && !m_replacing && !m_authoring_suspended && m_editable && m_scene; } [[nodiscard]] bool CanUndo() const { @@ -571,6 +580,12 @@ namespace Tetragrama bool m_initialized = false; bool m_in_phase = false; bool m_editable = true; + bool m_authoring_suspended = false; + ZEngine::ECS::Scene* m_suspended_scene = nullptr; + uint64_t m_suspended_epoch = 0; + uint64_t m_suspended_revision = 0; + uint64_t m_suspended_structural = 0; + uint64_t m_suspended_hierarchy = 0; bool m_preview_changed = false; bool m_hierarchy_pending = false; bool m_replacing = false; diff --git a/Tetragrama/tests/CMakeLists.txt b/Tetragrama/tests/CMakeLists.txt index 432ff2190..a98655f2b 100644 --- a/Tetragrama/tests/CMakeLists.txt +++ b/Tetragrama/tests/CMakeLists.txt @@ -6,6 +6,7 @@ target_sources(TetragramaTests PRIVATE GizmoCamera_test.cpp) target_sources(TetragramaTests PRIVATE SelectedRootCache_test.cpp) target_sources(TetragramaTests PRIVATE GizmoBatch_test.cpp) target_sources(TetragramaTests PRIVATE EditorGrid_test.cpp) +target_sources(TetragramaTests PRIVATE EditorPlayCoordinator_test.cpp) target_sources(TetragramaTests PRIVATE EditorRenderHandoff_test.cpp) target_sources(TetragramaTests PRIVATE GizmoGrid_test.cpp) target_sources(TetragramaTests PRIVATE ThumbnailService_test.cpp) diff --git a/Tetragrama/tests/EditorPlayCoordinator_test.cpp b/Tetragrama/tests/EditorPlayCoordinator_test.cpp new file mode 100644 index 000000000..65b1f7689 --- /dev/null +++ b/Tetragrama/tests/EditorPlayCoordinator_test.cpp @@ -0,0 +1,155 @@ +#include +#include +#include + +using Tetragrama::EditorPlayCoordinator; +using namespace ZEngine::ECS; + +namespace +{ + using Mode = EditorPlayCoordinator::Mode; + + /// @brief Commit an Enter and transfer its prepared payload to the host. + SceneRequestId Enter(EditorPlayCoordinator& coordinator) + { + SceneRequestId request = {}; + EXPECT_TRUE(coordinator.BeginEnter(&request)); + EXPECT_TRUE(coordinator.BeginEnterCommit(request, coordinator.Generation())); + EXPECT_TRUE(coordinator.FinishEnterCommit(request)); + EXPECT_TRUE(coordinator.FinishCleanup(request)); + return request; + } +} // namespace + +TEST(EditorPlayCoordinatorTest, EnterPauseStepAndStopAdvanceOnlyOnCommittedSwitches) +{ + EditorPlayCoordinator coordinator = {}; + EXPECT_EQ(coordinator.CurrentMode(), Mode::Edit); + EXPECT_EQ(coordinator.Generation(), 1u); + EXPECT_FALSE(coordinator.Pause()); + EXPECT_FALSE(coordinator.BeginStep()); + const auto enter = Enter(coordinator); + EXPECT_EQ(coordinator.CurrentMode(), Mode::Play); + EXPECT_EQ(coordinator.Generation(), 2u); + EXPECT_EQ(coordinator.CancelEnter(enter), SceneCancelResult::TooLate); + ASSERT_TRUE(coordinator.Pause()); + ASSERT_TRUE(coordinator.BeginStep()); + EXPECT_EQ(coordinator.CurrentMode(), Mode::Stepping); + EXPECT_FALSE(coordinator.BeginStep()); + EXPECT_FALSE(coordinator.Resume()); + SceneRequestId stop = {}; + EXPECT_FALSE(coordinator.BeginStop(&stop)); + ASSERT_TRUE(coordinator.FinishStep()); + EXPECT_EQ(coordinator.CurrentMode(), Mode::Paused); + ASSERT_TRUE(coordinator.Resume()); + ASSERT_TRUE(coordinator.BeginStop(&stop)); + EXPECT_EQ(coordinator.CancelEnter(stop), SceneCancelResult::NotFound); + EXPECT_FALSE(coordinator.BeginStopCommit(stop, 1)); + ASSERT_TRUE(coordinator.BeginStopCommit(stop, 2)); + ASSERT_TRUE(coordinator.FinishStopCommit(stop)); + EXPECT_EQ(coordinator.CurrentMode(), Mode::Edit); + EXPECT_EQ(coordinator.Generation(), 3u); + EXPECT_TRUE(coordinator.FinishCleanup(stop)); + EXPECT_TRUE(coordinator.Acknowledge(stop)); + EXPECT_TRUE(coordinator.Acknowledge(enter)); +} + +TEST(EditorPlayCoordinatorTest, CancelledEnterRetainsCleanupAfterAcknowledgement) +{ + EditorPlayCoordinator coordinator = {}; + SceneRequestId request = {}; + ASSERT_TRUE(coordinator.BeginEnter(&request)); + EXPECT_EQ(coordinator.CancelEnter(request), SceneCancelResult::Cancelled); + SceneLoadResult result = {}; + ASSERT_TRUE(coordinator.Poll(request, &result)); + EXPECT_EQ(result.Outcome, SceneLoadOutcome::Cancelled); + EXPECT_TRUE(result.CleanupPending); + ASSERT_TRUE(coordinator.Acknowledge(request)); + SceneRequestId unchanged{9, 9}; + EXPECT_FALSE(coordinator.BeginEnter(&unchanged)); + EXPECT_EQ(unchanged, (SceneRequestId{9, 9})); + ASSERT_TRUE(coordinator.FinishCleanup(request)); + EXPECT_FALSE(coordinator.FinishCleanup(request)); + ASSERT_TRUE(coordinator.BeginEnter(&unchanged)); + EXPECT_NE(unchanged, request); +} + +TEST(EditorPlayCoordinatorTest, CommitGuardRejectsStaleGenerationAndMakesCancellationTooLate) +{ + EditorPlayCoordinator coordinator = {}; + SceneRequestId request = {}; + ASSERT_TRUE(coordinator.BeginEnter(&request)); + EXPECT_FALSE(coordinator.FinishEnterCommit(request)); + EXPECT_FALSE(coordinator.BeginEnterCommit(request, 2)); + ASSERT_TRUE(coordinator.BeginEnterCommit(request, 1)); + EXPECT_EQ(coordinator.CancelEnter(request), SceneCancelResult::TooLate); + EXPECT_FALSE(coordinator.FailEnter(request, SceneLoadStage::Publication, SceneLoadError::Resources)); + EXPECT_FALSE(coordinator.BeginEnterCommit(request, 1)); + ASSERT_TRUE(coordinator.FinishEnterCommit(request)); + EXPECT_FALSE(coordinator.FinishEnterCommit(request)); + SceneLoadResult result = {}; + ASSERT_TRUE(coordinator.Poll(request, &result)); + EXPECT_EQ(result.Outcome, SceneLoadOutcome::Committed); + EXPECT_EQ(result.CommittedGeneration, 2u); +} + +TEST(EditorPlayCoordinatorTest, FailedStopRequiresCleanupBeforeRetry) +{ + EditorPlayCoordinator coordinator = {}; + const auto enter = Enter(coordinator); + SceneRequestId stop = {}; + ASSERT_TRUE(coordinator.BeginStop(&stop)); + ASSERT_TRUE(coordinator.FailStop(stop, SceneLoadStage::Preparation, SceneLoadError::Resources)); + EXPECT_EQ(coordinator.CurrentMode(), Mode::ReturnError); + EXPECT_EQ(coordinator.Generation(), 2u); + EXPECT_FALSE(coordinator.Pause()); + SceneRequestId rejected_enter = {}; + EXPECT_FALSE(coordinator.BeginEnter(&rejected_enter)); + SceneRequestId retry = {}; + EXPECT_FALSE(coordinator.BeginStop(&retry)); + ASSERT_TRUE(coordinator.FinishCleanup(stop)); + ASSERT_TRUE(coordinator.BeginStop(&retry)); + EXPECT_NE(retry, stop); + EXPECT_FALSE(coordinator.FinishStopCommit(stop)); + ASSERT_TRUE(coordinator.BeginStopCommit(retry, 2)); + ASSERT_TRUE(coordinator.FinishStopCommit(retry)); + EXPECT_EQ(coordinator.CurrentMode(), Mode::Edit); + EXPECT_EQ(coordinator.Generation(), 3u); +} + +TEST(EditorPlayCoordinatorTest, UnsupportedEnterAndForeignThreadLeaveStateUnchanged) +{ + EditorPlayCoordinator coordinator = {}; + SceneRequestId request = {}; + bool worker_accepted = true; + std::thread worker([&] { worker_accepted = coordinator.BeginEnter(&request); }); + worker.join(); + EXPECT_FALSE(worker_accepted); + ASSERT_TRUE(coordinator.BeginEnter(&request)); + EXPECT_FALSE(coordinator.FailEnter(request, SceneLoadStage::None, SceneLoadError::UnsupportedCapability)); + ASSERT_TRUE(coordinator.FailEnter(request, SceneLoadStage::Admission, SceneLoadError::UnsupportedCapability)); + SceneLoadResult result = {}; + ASSERT_TRUE(coordinator.Poll(request, &result)); + EXPECT_EQ(result.Outcome, SceneLoadOutcome::Failed); + EXPECT_EQ(result.Error, SceneLoadError::UnsupportedCapability); + EXPECT_EQ(coordinator.CurrentMode(), Mode::Edit); + EXPECT_EQ(coordinator.Generation(), 1u); +} + +TEST(EditorPlayCoordinatorTest, UnacknowledgedResultsApplyBoundedBackpressure) +{ + EditorPlayCoordinator coordinator = {}; + SceneRequestId requests[SceneLoadCoordinator::ResultCapacity] = {}; + for (auto& request : requests) + { + ASSERT_TRUE(coordinator.BeginEnter(&request)); + ASSERT_EQ(coordinator.CancelEnter(request), SceneCancelResult::Cancelled); + ASSERT_TRUE(coordinator.FinishCleanup(request)); + } + SceneRequestId output{7, 7}; + EXPECT_FALSE(coordinator.BeginEnter(&output)); + EXPECT_EQ(output, (SceneRequestId{7, 7})); + EXPECT_EQ(coordinator.CurrentMode(), Mode::Edit); + ASSERT_TRUE(coordinator.Acknowledge(requests[0])); + EXPECT_TRUE(coordinator.BeginEnter(&output)); +} diff --git a/Tetragrama/tests/EditorSession_test.cpp b/Tetragrama/tests/EditorSession_test.cpp index b7a16658e..3f1611516 100644 --- a/Tetragrama/tests/EditorSession_test.cpp +++ b/Tetragrama/tests/EditorSession_test.cpp @@ -2411,3 +2411,65 @@ TEST_F(EditorSessionTest, SelectionRangeRejectsWrongThreadAndAllowsReadOnlySelec EXPECT_FALSE(session.Editable()); EXPECT_FALSE(session.Dirty()); } + +TEST_F(EditorSessionTest, SuspendedAuthoringCancelsPreviewDiscardsQueuedCommandsAndRetainsHistory) +{ + const auto entity = Entity(1); + ASSERT_TRUE(Begin(entity)); + ASSERT_TRUE(Preview(entity, 2.f)); + ASSERT_TRUE(session.Commit()); + ASSERT_TRUE(Begin(entity)); + ASSERT_TRUE(Preview(entity, 5.f)); + ASSERT_TRUE(session.Request(EditorCommand::Undo)); + const auto epoch = session.SceneEpoch(); + const auto history = session.History().UndoCount(); + bool worker_suspend = true; + std::thread worker_before([&] { worker_suspend = session.SuspendAuthoring(); }); + worker_before.join(); + EXPECT_FALSE(worker_suspend); + EXPECT_TRUE(session.Active()); + + ASSERT_TRUE(session.SuspendAuthoring()); + EXPECT_TRUE(session.AuthoringSuspended()); + EXPECT_FALSE(session.Active()); + EXPECT_FALSE(session.Editable()); + EXPECT_FALSE(session.CanUndo()); + EXPECT_FALSE(session.BeginMutationPhase()); + EXPECT_FALSE(session.Request(EditorCommand::Undo)); + EXPECT_FALSE(session.RequestSelection(entity)); + EXPECT_FALSE(session.SetHovered(entity)); + EXPECT_EQ(session.PendingRequestCount(), 0u); + EXPECT_EQ(session.Scene(), &scene); + EXPECT_EQ(session.SceneEpoch(), epoch); + EXPECT_EQ(session.History().UndoCount(), history); + EXPECT_TRUE(session.Dirty()); + EXPECT_FLOAT_EQ(Value(entity).Position.x, 2.f); + + bool worker_resume = true; + std::thread worker([&] { worker_resume = session.ResumeAuthoring(); }); + worker.join(); + EXPECT_FALSE(worker_resume); + ASSERT_TRUE(session.ResumeAuthoring()); + EXPECT_FALSE(session.AuthoringSuspended()); + EXPECT_FALSE(session.ResumeAuthoring()); + ASSERT_TRUE(session.BeginMutationPhase()); + ASSERT_TRUE(session.Undo()); + EXPECT_FLOAT_EQ(Value(entity).Position.x, 0.f); + ASSERT_TRUE(session.Redo()); + EXPECT_FLOAT_EQ(Value(entity).Position.x, 2.f); + EXPECT_EQ(session.SceneEpoch(), epoch); +} + +TEST_F(EditorSessionTest, ResumeRejectsUnexpectedStructuralChangesAndLeavesAuthoringSuspended) +{ + Entity(1); + ASSERT_TRUE(session.SuspendAuthoring()); + const auto epoch = session.SceneEpoch(); + const auto created = scene.CreateEntity(); + ASSERT_TRUE(created.IsValid()); + EXPECT_FALSE(session.ResumeAuthoring()); + EXPECT_TRUE(session.AuthoringSuspended()); + EXPECT_FALSE(session.BeginMutationPhase()); + EXPECT_EQ(session.Scene(), &scene); + EXPECT_EQ(session.SceneEpoch(), epoch); +} diff --git a/docs/design/future-plan/editor-play-mode.md b/docs/design/future-plan/editor-play-mode.md index 0c9d0dae7..3e98de593 100644 --- a/docs/design/future-plan/editor-play-mode.md +++ b/docs/design/future-plan/editor-play-mode.md @@ -3,6 +3,8 @@ **Priority:** P1 — required for safe gameplay iteration **Status:** Design; isolated retained-authoring Play approved on 2026-11-07; implementation and qualification remain outstanding + +Current simulation/service audit: [M3 service inventory](m3-service-inventory.md). **Depends on:** scene-serialization.md, editor-undo-redo.md, actor-ecs-architecture.md, game-runtime-boundary.md, rendering-flow.md **Blocks:** trustworthy Play, Pause, Stop workflow diff --git a/docs/design/future-plan/m3-service-inventory.md b/docs/design/future-plan/m3-service-inventory.md new file mode 100644 index 000000000..e87d4c542 --- /dev/null +++ b/docs/design/future-plan/m3-service-inventory.md @@ -0,0 +1,34 @@ +# M3 simulation service inventory + +This inventory records the current code boundaries for the first M3 slice. It +is not an approval to run Play or a claim that world-scoped service activation +is implemented. The approved ownership and transition requirements remain in +[Editor Play Mode](editor-play-mode.md) and issue [#874](https://github.com/JeanPhilippeKernel/RendererEngine/issues/874). + +| Area | Current behavior | M3 work before admitting Play | +|---|---|---| +| Fixed-step loop | `Engine::AdvanceSimulation` checks the application policy and active scene binding, resets its accumulator when simulation is disabled, then runs systems, flushes commands, ticks actors and snapshots transforms in that order. | Bind only world B; define pause, exactly-one-step, generation and reentrancy behavior. A must never be ticked. | +| ECS systems | `WorldTick` registers function pointers and a dependency graph; a committed wave may run tasks on the thread pool and waits for them before returning. | Define world-owned registration, preparation and quiescence; ensure systems cannot reach world A through globals. | +| Deferred commands | `WorldCommands` owns its queued commands and flushes them into the supplied scene. Commands can contain callbacks. | Bind commands and callbacks to B's lifetime and activation, reject stale work and drain before teardown. | +| Actors | `ActorManager` is bound to a scene. `Create` makes an entity and invokes `OnCreate`; `Destroy` invokes `OnDestroy` and may destroy its entity. | A separately reviewed authored-actor adapter is required before restoring actor types or invoking lifecycle callbacks. No actor factory or callbacks during unpublished scene preparation. | +| Physics and audio | The scene can contain authored data, but M2's renderer-only loader does not establish world-scoped live physics or audio services. | Define separate service ownership, preparation, activation, pause/step and teardown contracts before admitting either as required gameplay. | +| Authoring session | `EditorSession` owns scene identity, dirty checkpoint, transactions and history. `BindScene` resets history. | Suspend and resume the same A without rebinding; coordinate editor input, scene/save transitions and external changes. | + +The initial service policy is fail-closed: no gameplay, actor restoration, live +physics or audio capability is advertised by this slice. Pure ECS reconstruction +alone is not evidence that a Play session can run. A future admission path must +reject required unsupported services before publication and report a structured +outcome. Optional inactive data must be identified explicitly rather than silently +claimed as simulated. + +The first implementation slice adds a session suspension boundary and a main-thread +transition ledger. The ledger records legal modes and request outcomes but performs +no world switch, service activation or simulation; its generation is distinct from +the scene-publication generation. The +owner cancels any active preview, drops queued editor requests, and keeps the +same authoring scene, epoch, dirty checkpoint and history. Resume checks the +stored binding and tracked structural/hierarchy revisions; a mismatch remains +suspended for recovery. These guards do not detect arbitrary direct writes to +component data by external code. M3 still needs world-scoped service isolation, +external-change policy and a coordinator before the boundary can safely be used +for Play.