载入中...
搜索中...
未找到
ScriptLinks.cpp
浏览该文件的文档.
1// The scene link kind backed by user script.
2//
3// A node can already carry a renderable, a physics body, a camera or an audio
4// source and have it follow the node's transform. This adds the kind that lets a
5// *script* object do the same, so a user can attach their own object to the
6// transform pipeline without a C++ build:
7//
8// local follower = Follower()
9// eve.provider.publish("my.follower", follower)
10// scene.linkScriptAt("host", "node", "my.follower", "node")
11//
12// Two directions, matching the two link sync modes:
13//
14// syncMode 0 ("node") -- for every dirty node, TransformSystem calls
15// `onNodeTransform(nodeId, worldX, worldY, worldZ, yaw, pitch, roll,
16// scaleX, scaleY, scaleZ)` on the published instance.
17// syncMode 1 ("body") -- before world propagation, the instance's
18// `nodeTransform()` returns `[x, y, z, yaw, pitch, roll]` in local space and
19// the node is moved to it.
20//
21// Dispatch stays a function-pointer table (scene/SceneLink.h), so the transform
22// pipeline still never learns what the target is.
23//
24// Ownership: `SceneLink::target` points at a process-lifetime `ScriptLinkTarget`
25// record, never at a script object. The record holds a generation-qualified
26// provider handle, which gives three properties the pipeline needs:
27//
28// * a retired generation is reported as a dead link instead of resolving to
29// whatever was published under that name next;
30// * the scene may still ask `alive()` about a record whose provider is gone,
31// so records are retained (moved to `retired`) rather than freed;
32// * no VM reference is held here at all -- `ScriptProviderRegistry` owns those,
33// and it drops them before the VM is destroyed.
34
35#include "common/CrashLog.h"
38#include "scene/Scene.h"
39#include "scene/SceneHost.h"
40#include "scene/SceneInternal.h"
41#include "scene/SceneLink.h"
43
44#include <glm/glm.hpp>
45
46#include <cstddef>
47#include <memory>
48#include <string>
49#include <utility>
50#include <vector>
51
52namespace eve::scene {
53
54namespace {
55
57constexpr const char* kScriptKind = "script";
58
60constexpr const char* kPushMethod = "onNodeTransform";
61
63constexpr const char* kPullMethod = "nodeTransform";
64
66constexpr std::size_t kPullElementCount = 6;
67
74struct ScriptLinkTarget {
75 ScriptProviderHandle provider;
77 bool reported = false;
78};
79
88struct ScriptLinkTargets {
89 std::vector<std::unique_ptr<ScriptLinkTarget>> live;
90 std::vector<std::unique_ptr<ScriptLinkTarget>> retired;
91};
92
93ScriptLinkTargets& targets() {
94 static ScriptLinkTargets state;
95 return state;
96}
97
99bool targetIsLive(const ScriptLinkTarget& target) {
100 const ScriptProviderRegistry& registry = ScriptProviderRegistry::instance();
101 return registry.generationOf(target.provider.name) == target.provider.generation;
102}
103
110bool isStaleHandle(const Status& status) {
111 const auto& diagnostics = status.diagnostics();
112 return !diagnostics.empty() && diagnostics.front().code() == DiagnosticCode::StaleHandle;
113}
114
122void reportScriptLinkFailure(ScriptLinkTarget& link, const std::string& method, const Status& status) {
123 if (link.reported) return;
124 link.reported = true;
125 recordLogEvent("error", "script link target '" + link.provider.name + "' method '" + method +
126 "' failed; the link was skipped this frame: " + status.describe());
127}
128
135ScriptLinkTarget* acquireTarget(const ScriptProviderHandle& provider) {
136 ScriptLinkTargets& pool = targets();
137 for (const auto& candidate : pool.live) {
138 if (candidate->provider == provider) return candidate.get();
139 }
140
141 // Drop records whose generation is gone so `live` tracks published providers.
142 for (auto it = pool.live.begin(); it != pool.live.end();) {
143 if (targetIsLive(**it)) {
144 ++it;
145 continue;
146 }
147 pool.retired.push_back(std::move(*it));
148 it = pool.live.erase(it);
149 }
150
151 pool.live.push_back(std::make_unique<ScriptLinkTarget>(ScriptLinkTarget{provider}));
152 return pool.live.back().get();
153}
154
165void pushNodeTransform(const SceneNode& node, void* target) {
166 auto* link = static_cast<ScriptLinkTarget*>(target);
167 if (!link) return;
168
169 glm::vec3 position(0.f), euler(0.f), scale(1.f); // euler = yaw, pitch, roll
170 decomposeWorld(node.world, position, euler, scale);
171
172 const ScriptArg args[] = {
177 };
178
179 const ScriptProviderRegistry& registry = ScriptProviderRegistry::instance();
180 auto pushed = registry.call(link->provider, kPushMethod, args);
181 if (pushed) return;
182 // A link whose provider was retired between the dirty marking and this call is
183 // already on its way out; anything else is a real script error worth one line.
184 if (isStaleHandle(pushed.status())) return;
185 reportScriptLinkFailure(*link, kPushMethod, pushed.status());
186}
187
193void pullNodeTransform(SceneNode& node, void* target) {
194 auto* link = static_cast<ScriptLinkTarget*>(target);
195 if (!link) return;
196
197 const ScriptProviderRegistry& registry = ScriptProviderRegistry::instance();
198 auto values = registry.callNumbers(link->provider, kPullMethod);
199 if (!values) {
200 if (isStaleHandle(values.status())) return;
201 reportScriptLinkFailure(*link, kPullMethod, values.status());
202 return;
203 }
204 if (values.value().size() < kPullElementCount) {
205 reportScriptLinkFailure(
206 *link, kPullMethod,
208 "script link method '" + std::string(kPullMethod) + "' returned " +
209 std::to_string(values.value().size()) + " numbers; six are required",
210 link->provider.name)));
211 return;
212 }
213
214 node.x = float(values.value()[0]);
215 node.y = float(values.value()[1]);
216 node.z = float(values.value()[2]);
217 node.yaw = float(values.value()[3]);
218 node.pitch = float(values.value()[4]);
219 node.roll = float(values.value()[5]);
220}
221
223bool aliveScriptTarget(const void* target) {
224 const auto* link = static_cast<const ScriptLinkTarget*>(target);
225 return link != nullptr && targetIsLive(*link);
226}
227
228struct Register {
229 Register() { registerLinkKind({kScriptKind, &pushNodeTransform, &pullNodeTransform, &aliveScriptTarget}); }
230} g_register;
231
232} // namespace
233
234void exposeScriptLinkBindings(ssq::Class& cls) {
235 cls.addFunc("linkScriptAt",
236 [vm = cls.getHandle()](Scene* self, const std::string& hostName, const std::string& nodeId,
237 const std::string& providerName, const std::string& mode) -> ssq::Table {
238 if (self == nullptr) {
239 return script::projectResult(vm, Result<void>::failure(Diagnostic::error(
240 DiagnosticCode::InvalidArgument,
241 "linkScriptAt needs a live Scene instance", nodeId)));
242 }
243 return script::projectResult(vm, self->linkScriptAt(hostName, nodeId, providerName, mode));
244 });
245}
246
247Result<void> Scene::linkScriptAt(const std::string& hostName, const std::string& nodeId,
248 const std::string& providerName, const std::string& mode) {
249 SceneHost* host = resolveHost(hostName);
250 if (!host) {
252 Diagnostic::error(DiagnosticCode::NotFound, "no scene host named '" + hostName + "'", providerName));
253 }
254
255 const ScriptProviderRegistry& registry = ScriptProviderRegistry::instance();
256 const std::uint64_t generation = registry.generationOf(providerName);
257 if (generation == 0) {
258 return Result<void>::failure(Diagnostic::error(
259 DiagnosticCode::NotFound, "no script provider published as '" + providerName + "'", providerName));
260 }
261
262 const int kind = findLinkKind(kScriptKind);
263 if (kind < 0) {
264 // Cannot happen while this translation unit is linked, but a trimmed build
265 // that dropped it must say so instead of linking nothing.
267 Diagnostic::error(DiagnosticCode::Unsupported, "the 'script' link kind is not registered", providerName));
268 }
269
270 const ScriptProviderHandle provider{providerName, generation};
271 if (!host->link(nodeId, kind, acquireTarget(provider), syncModeFromString(mode))) {
273 Diagnostic::error(DiagnosticCode::NotFound, "no node named '" + nodeId + "'", nodeId));
274 }
275 TransformSystem::updateHost(host);
276 return Result<void>::success();
277}
278
279} // namespace eve::scene
LogicalId target
std::vector< std::unique_ptr< ScriptClimbingEventSink > > live
std::vector< std::unique_ptr< ScriptClimbingEventSink > > retired
Persistent, thread-safe record of engine crash and problem events.
std::string nodeId
HSQUIRRELVM vm
Definition ECS.cpp:38
HSQOBJECT cls
Definition ECS.cpp:39
Generation generation
Definition ECS.cpp:40
std::uint16_t method
std::vector< FieldTarget > targets
wgpu::PopErrorScopeStatus status
PhysicsJointLink link
std::array< float, 3 > position
std::array< float, 3 > scale
std::set< std::string > values
const eve::script::BindingContractRegistry & registry
const RoadNode * node
std::string kind
The single Squirrel projection for common Result, Status and Value.
UIHostHandle host
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
Named script objects that native systems drive through named methods.
static ScriptProviderRegistry & instance()
Process-lifetime registry; clearAll is the only reset.
static Status failure(StatusCode code, Diagnostic diagnostic)
Construct a failed status with one diagnostic.
Definition Status.cpp:28
ECS mount point for one scene graph (full scene or nested subtree root). Isomorphic to eve::ui::UIHos...
Definition SceneHost.h:89
Declarative scene module (eve.Scene).
Definition Scene.h:52
Result< void > linkScriptAt(const std::string &hostName, const std::string &nodeId, const std::string &providerName, const std::string &mode)
Link a published script provider to a node as the "script" link kind.
EVENGINE_API_PLATFORM void exposeScriptLinkBindings(ssq::Class &cls)
Register eve.Scene's script-link surface.
int registerLinkKind(const LinkOps &ops)
Registers link kind.
int findLinkKind(const char *kind)
Finds link kind.
ssq::Table projectResult(HSQUIRRELVM vm, Result< void > &&result)
Consume and project a void native Result using the common schema.
void recordLogEvent(const std::string &level, const std::string &message)
Appends a timestamped event line to the crash/error log.
Definition CrashLog.cpp:70
static ScriptArg fromText(std::string value)
static ScriptArg fromNumber(double value)
Generation-qualified identity of one published script provider.