载入中...
搜索中...
未找到
ProcgenScriptSupport.h
浏览该文件的文档.
1#pragma once
2
3#include "procgen/Procgen.h"
9
10#include "common/Result.h"
13
14#include "image/ImageData.h"
15
16#include <simplesquirrel/simplesquirrel.hpp>
17
18#include <any>
19#include <string>
20#include <functional>
21#include <mutex>
22#include <optional>
23#include <unordered_map>
24#include <utility>
25
26namespace eve::procgen {
27
28template <class T>
30
31template <class T>
33 struct Record {
34 std::any reference;
35 std::function<eve::Result<void>()> release;
36 // Borrowed C-API instance identity, valid until its release hook removes this record.
37 // Access and invalidation run on the owning VM thread; this does not root the instance.
39 HSQOBJECT instance;
40 };
41 static inline std::mutex mutex;
42 static inline std::unordered_map<T*, Record> records;
43};
44
45template <class Ref, class T>
46std::optional<Ref> nativeProxyReference(T* native);
47
48template <class T>
49SQInteger releaseNativeProxy(SQUserPointer pointer, SQInteger);
50
51template <class T, class Ref, class Resolve, class Release>
52ssq::Table makeOwnedNativeProxy(HSQUIRRELVM vm, eve::Result<Ref>&& reference, Resolve&& resolve, Release&& release);
53
54template <class T>
55ssq::Table projectBorrowedResult(HSQUIRRELVM vm, eve::script::Borrowed<T> borrowed, const char* objectName);
56
60
64
65template <class Ref, class Proxy, class Release>
66ssq::Table makeOwnedProxy(HSQUIRRELVM vm, eve::Result<Ref>&& reference, Release&& release);
67
70
71template <class T, class Tag>
74
75// ---- template implementations (header-only for TU sharing) ----
76
77template <class T>
80 eve::Diagnostic::error(code, std::move(message), std::move(path), {}, "procgen.squirrel"));
81}
82
83template <class Ref, class T>
84std::optional<Ref> nativeProxyReference(T* native) {
85 if (!native) return std::nullopt;
86 std::lock_guard lock(NativeProxyReleases<T>::mutex);
87 const auto found = NativeProxyReleases<T>::records.find(native);
88 if (found == NativeProxyReleases<T>::records.end()) return std::nullopt;
89 if (const auto* reference = std::any_cast<Ref>(&found->second.reference)) return *reference;
90 return std::nullopt;
91}
92
93template <class T>
94SQInteger releaseNativeProxy(SQUserPointer pointer, SQInteger) {
95 auto native = static_cast<T*>(pointer);
96 if (!native) return 0;
97
98 std::function<eve::Result<void>()> release;
99 {
100 std::lock_guard lock(NativeProxyReleases<T>::mutex);
101 const auto found = NativeProxyReleases<T>::records.find(native);
102 if (found == NativeProxyReleases<T>::records.end()) return 0;
103 release = std::move(found->second.release);
105 }
106 release().ignore("release Squirrel procgen native proxy");
107 return 0;
108}
109
110template <class T, class Ref, class Resolve, class Release>
111ssq::Table makeOwnedNativeProxy(HSQUIRRELVM vm, eve::Result<Ref>&& reference, Resolve&& resolve, Release&& release) {
113
114 const auto ref = std::move(reference).takeValue();
115 const auto view = std::invoke(std::forward<Resolve>(resolve), ref);
116 if (!view.isBound()) {
117 std::invoke(release, ref).ignore("rollback unbound Squirrel procgen proxy");
120 "procgen proxy could not resolve its owned object",
121 "procgen", {}, "procgen.squirrel"))
122 .status());
123 }
124
125 const SQInteger top = sq_gettop(vm);
126 const size_t hashCode = eve::script::detail::squirrelTypeHash<T*>();
127 sq_pushobject(vm, ssq::detail::getClassObj(vm, hashCode));
128 if (SQ_FAILED(sq_createinstance(vm, -1))) {
129 sq_settop(vm, top);
130 std::invoke(release, ref).ignore("rollback failed Squirrel procgen instance");
133 "failed to create Squirrel procgen proxy", "procgen",
134 {}, "procgen.squirrel"))
135 .status());
136 }
137 sq_remove(vm, -2);
138 auto native = view.get();
139 std::optional<typename NativeProxyReleases<T>::Record> retired;
140 {
141 std::lock_guard lock(NativeProxyReleases<T>::mutex);
142 auto& records = NativeProxyReleases<T>::records;
143 if (auto old = records.find(native); old != records.end()) {
144 retired.emplace(std::move(old->second));
145 records.erase(old);
146 }
147 }
148 if (retired) {
149 // An explicitly released allocation can be reused while its script proxy is still alive.
150 // Disarm that proxy before publishing the new generation at the same native address.
151 sq_pushobject(retired->vm, retired->instance);
152 sq_setreleasehook(retired->vm, -1, nullptr);
153 sq_setinstanceup(retired->vm, -1, nullptr);
154 sq_pop(retired->vm, 1);
155 }
156 HSQOBJECT instance;
157 sq_getstackobj(vm, -1, &instance);
158 {
159 std::lock_guard lock(NativeProxyReleases<T>::mutex);
161 native,
163 ref, [ref, release = std::forward<Release>(release)]() mutable { return std::invoke(release, ref); },
164 vm, instance});
165 }
166 sq_setinstanceup(vm, -1, native);
167 sq_settypetag(vm, -1, reinterpret_cast<SQUserPointer>(hashCode));
168 sq_setreleasehook(vm, -1, &releaseNativeProxy<T>);
169
170 ssq::Instance value(vm);
171 sq_getstackobj(vm, -1, &value.getRaw());
172 sq_addref(vm, &value.getRaw());
173 sq_settop(vm, top);
174
176 result.set("value", value);
178 result.set("ownership", std::string("owned"));
179 result.set("ownerEpoch", static_cast<std::int64_t>(ref.ownerEpoch));
180 result.set("handle", static_cast<std::int64_t>(ref.packed()));
181 return result;
182}
183
184template <class T>
186 if (!borrowed.isBound())
189 std::string(objectName) + " could not be produced",
190 objectName, {}, "procgen.squirrel"))
191 .status());
193 result.set("value", borrowed.get());
195 result.set("ownership", std::string("borrowed"));
196 return result;
197}
198
199template <class Ref, class Proxy, class Release>
200ssq::Table makeOwnedProxy(HSQUIRRELVM vm, eve::Result<Ref>&& reference, Release&& release) {
202 const Ref ref = std::move(reference).takeValue();
203 auto object = eve::script::makeOwnedSquirrelInstance<Proxy>(vm, std::make_unique<Proxy>(ref));
204 if (!object) {
205 const eve::Status status = object.status();
206 object.ignore("failed to create owned procgen proxy");
207 std::invoke(std::forward<Release>(release), ref).ignore("rollback failed owned procgen allocation");
209 }
210 ssq::Object owned = std::move(object).takeValue();
212 result.set("value", owned);
214 result.set("ownership", std::string("owned"));
215 result.set("ownerEpoch", static_cast<std::int64_t>(ref.ownerEpoch));
216 result.set("handle", static_cast<std::int64_t>(ref.packed()));
217 return result;
218}
219
220template <class T, class Tag>
225
226} // namespace eve::procgen
Capability-driven, transactional publication of generated artifacts.
ActiveSource owned
AuthorityStoreHandleRef reference
Definition Authority.cpp:24
std::vector< std::unique_ptr< ScriptClimbingEventSink > > retired
struct SQVM * HSQUIRRELVM
HSQUIRRELVM vm
Definition ECS.cpp:38
Owning, backend-neutral products published by procedural generation.
std::string message
DiagnosticCode code
wgpu::PopErrorScopeStatus status
Poco::JSON::Object::Ptr result
OceanSprayView view
const RuntimeTensor * borrowed
std::string path
Definition PlayHost.cpp:111
const eve::script::BindingContractRegistry & registry
Object::Ptr value
std::string pointer
Move-only, checked operation results for the common layer.
bool found
size_t end
The single Squirrel projection for common Result, Status and Value.
Explicit Value/Owned/Borrowed semantics at the Squirrel boundary.
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
Structured status and zero or more diagnostics for an operation.
Definition Status.h:70
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Definition Status.cpp:19
The canonical owning dynamic value used by data-facing protocols.
Definition Value.h:31
Non-owning observation of a registry-owned object.
Slot/generation registry whose objects are exclusively unique-owned.
SQInteger top
Definition Snapshot.cpp:115
ssq::Table makeOwnedPointSetProxy(HSQUIRRELVM vm, eve::Result< ProcgenPointSetHandleRef > &&reference)
SQInteger releaseNativeProxy(SQUserPointer pointer, SQInteger)
ssq::Table projectDecodedTerrainResult(HSQUIRRELVM vm, eve::Result< DecodedTerrainFile > &&decoded)
Projects a decoded terrain file as an owned heightmap proxy plus metadata.
ssq::Table makeOwnedSpatialProxy(HSQUIRRELVM vm, eve::Result< ProcgenSpatialDataHandleRef > &&reference)
ssq::Table makeOwnedGridProxy(HSQUIRRELVM vm, eve::Result< ProcgenGridHandleRef > &&reference)
eve::Value artifactProjection(GeneratedArtifact &&artifact)
eve::Result< T > procgenBindingFailure(eve::DiagnosticCode code, std::string message, std::string path={})
ssq::Table makeOwnedNativeProxy(HSQUIRRELVM vm, eve::Result< Ref > &&reference, Resolve &&resolve, Release &&release)
std::optional< Ref > nativeProxyReference(T *native)
eve::Value boundsValue(const Bounds &bounds)
eve::Result< eve::script::RuntimeHandleRef< Tag > > ownProcgenObject(eve::script::RuntimeObjectRegistry< T, Tag > &registry, eve::script::Owned< T > object)
ssq::Table projectRecipeDescriptorResult(HSQUIRRELVM vm, eve::Result< RecipeDescriptor > &&result)
Projects one native recipe schema through the canonical Result table.
ssq::Table projectBorrowedResult(HSQUIRRELVM vm, eve::script::Borrowed< T > borrowed, const char *objectName)
ssq::Table makeOwnedProxy(HSQUIRRELVM vm, eve::Result< Ref > &&reference, Release &&release)
eve::Value publishReceiptProjection(ArtifactPublishReceipt &&receipt)
void markResultHasValue(ssq::Table &result)
Declare that a projected table received a payload the caller attached itself.
ssq::Table projectStatusResult(HSQUIRRELVM vm, const Status &status)
Project a checked native status that carries no payload.
std::unique_ptr< T > Owned
C++ owning storage used by an object factory.
DiagnosticCode
Stable machine-readable diagnostic codes.
Definition Diagnostic.h:47
Compatibility receipt retaining procgen ArtifactId at this boundary.
Axis-aligned bounds in the artifact's declared world coordinate space.
Complete immutable-once-published artifact record.
std::function< eve::Result< void >()> release
static std::unordered_map< T *, Record > records
glm::vec4 bounds