载入中...
搜索中...
未找到
CombatCarrierScript.cpp
浏览该文件的文档.
2
3#include "common/Capability.h"
4#include "common/Diagnostic.h"
7#include "common/Time.h"
8#include "common/Value.h"
13#include "weapon/Weapon.h"
15
16#include <algorithm>
17#include <cmath>
18#include <cstdint>
19#include <limits>
20#include <map>
21#include <memory>
22#include <string>
23#include <utility>
24#include <vector>
25
26namespace eve::weapon {
27namespace {
28
29Result<Value> nullRuntime() {
31 "combat carrier runtime must not be null", "runtime", {},
32 "weapon.carrier.squirrel"));
33}
34
35class ScriptTargetProvider final : public IProjectileTargetProvider {
36public:
37 [[nodiscard]] Result<ProjectilePoint> position(ecs::EntityHandle target) const override {
38 const auto key = keyOf(target);
39 auto it = positions_.find(key);
40 if (it == positions_.end())
42 Diagnostic::error(DiagnosticCode::NotFound, "homing target position is not registered", "target", {},
43 "weapon.carrier.squirrel"));
44 return Result<ProjectilePoint>::success(it->second);
45 }
46
47 void set(ecs::EntityHandle target, ProjectilePoint point) { positions_[keyOf(target)] = point; }
48 void clear() { positions_.clear(); }
49 [[nodiscard]] bool empty() const noexcept { return positions_.empty(); }
50
51private:
52 [[nodiscard]] static std::uint64_t keyOf(ecs::EntityHandle target) {
53 return (static_cast<std::uint64_t>(target.generation) << 32) | target.id;
54 }
55
56 std::map<std::uint64_t, ProjectilePoint> positions_;
57};
58
59class ScriptCircleHitProbe final : public ICarrierHitProbe {
60public:
61 struct Target {
62 ecs::EntityHandle id{};
63 ProjectilePoint center{};
64 double radius = 0.5;
65 };
66
67 [[nodiscard]] Result<std::vector<Contact>> query(CarrierHandle, const CarrierMotion& previous,
68 const CarrierMotion& current) const override {
69 std::vector<Contact> contacts;
70 for (const auto& target : targets_) {
71 const double ax = previous.position.x - target.center.x;
72 const double ay = previous.position.y - target.center.y;
73 const double az = previous.position.z - target.center.z;
74 const double bx = current.position.x - target.center.x;
75 const double by = current.position.y - target.center.y;
76 const double bz = current.position.z - target.center.z;
77 const double abx = bx - ax;
78 const double aby = by - ay;
79 const double abz = bz - az;
80 const double ab2 = abx * abx + aby * aby + abz * abz;
81 const double radius2 = target.radius * target.radius;
82 const double startDistance = ax * ax + ay * ay + az * az;
83 const double projection = ax * abx + ay * aby + az * abz;
84 if (ab2 <= 1e-12) continue;
85 double t = 0.0;
86 if (startDistance >= radius2 - 1e-9) {
87 // At a surface while departing: do not bounce again on the next frame.
88 if (projection >= 0.0) continue;
89 const double discriminant = projection * projection - ab2 * (startDistance - radius2);
90 if (discriminant < 0.0) continue;
91 t = (-projection - std::sqrt(discriminant)) / ab2;
92 if (t < -1e-9 || t > 1.0) continue;
93 t = std::max(0.0, t);
94 }
95 const double cx = ax + abx * t;
96 const double cy = ay + aby * t;
97 const double cz = az + abz * t;
98 const double dist2 = cx * cx + cy * cy + cz * cz;
99 if (dist2 <= radius2 + 1e-9 * std::max(1.0, radius2)) {
100 Contact contact;
101 contact.fraction = t;
102 contact.target = target.id;
103 contact.point = {target.center.x + cx, target.center.y + cy, target.center.z + cz};
104 const double len = std::sqrt(dist2);
105 if (len > 1e-9) {
106 contact.normal = {cx / len, cy / len, cz / len};
107 } else {
108 contact.normal = {-1.0, 0.0, 0.0};
109 }
110 contacts.push_back(contact);
111 }
112 }
113 return Result<std::vector<Contact>>::success(std::move(contacts));
114 }
115
116 void add(Target target) { targets_.push_back(target); }
117 void clear() { targets_.clear(); }
118 [[nodiscard]] bool empty() const noexcept { return targets_.empty(); }
119
120private:
121 std::vector<Target> targets_;
122};
123
124Value encodeHandle(CarrierHandle handle) {
126 object.emplace("slot", Value(static_cast<std::int64_t>(handle.slot)));
127 object.emplace("generation", Value(static_cast<std::int64_t>(handle.generation)));
128 return Value(std::move(object));
129}
130
131const char* triggerKindName(CarrierTriggerKind kind) {
132 switch (kind) {
133 case CarrierTriggerKind::OnDistance: return "onDistance";
134 case CarrierTriggerKind::OnSpeedBelow: return "onSpeedBelow";
135 case CarrierTriggerKind::OnApex: return "onApex";
136 case CarrierTriggerKind::OnExpire: return "onExpire";
137 case CarrierTriggerKind::OnFuse: return "onFuse";
138 case CarrierTriggerKind::OnInterval: return "onInterval";
139 case CarrierTriggerKind::OnHit: return "onHit";
140 case CarrierTriggerKind::OnProximity: return "onProximity";
141 }
142 return "onExpire";
143}
144
145const char* impactKindName(CarrierImpactKind kind) {
146 switch (kind) {
147 case CarrierImpactKind::EmitHit: return "emitHit";
148 case CarrierImpactKind::Splash: return "splash";
149 case CarrierImpactKind::Pierce: return "pierce";
150 case CarrierImpactKind::Bounce: return "bounce";
151 case CarrierImpactKind::Release: return "release";
152 case CarrierImpactKind::SpawnChild: return "spawnChild";
153 case CarrierImpactKind::EmitTrigger: return "emitTrigger";
154 }
155 return "release";
156}
157
158Value encodeEvent(const CarrierEvent& event) {
160 object.emplace("slot", Value(static_cast<std::int64_t>(event.carrier.slot)));
161 object.emplace("generation", Value(static_cast<std::int64_t>(event.carrier.generation)));
162 object.emplace("recipeId", Value(event.recipeId.format()));
163 object.emplace("trigger", Value(std::string(triggerKindName(event.trigger))));
164 object.emplace("impact", Value(std::string(impactKindName(event.impact))));
165 object.emplace("age", Value(event.age.seconds()));
166 if (event.worldContact) {
167 const auto& hit = *event.worldContact;
168 object.emplace("bodyId", Value(static_cast<std::int64_t>(hit.bodyId)));
169 object.emplace("shapeId", Value(static_cast<std::int64_t>(hit.shapeId)));
170 object.emplace("bodyIndex", Value(static_cast<std::int64_t>(hit.identity.body & 0xffffffffu)));
171 object.emplace("bodyGeneration", Value(static_cast<std::int64_t>(hit.identity.body >> 32)));
172 object.emplace("worldIndex", Value(static_cast<std::int64_t>(hit.identity.world & 0xffffffffu)));
173 object.emplace("worldGeneration", Value(static_cast<std::int64_t>(hit.identity.world >> 32)));
174 object.emplace("fraction", Value(hit.fraction));
175 object.emplace("worldEpoch", Value(static_cast<std::int64_t>(hit.worldEpoch)));
176 }
177 object.emplace("damage", Value(event.damage));
178 object.emplace("splashRadius", Value(event.splashRadius));
179 object.emplace("damageType", Value(event.damageType));
180 object.emplace("element", Value(event.element));
181 object.emplace("x", Value(event.position.x));
182 object.emplace("y", Value(event.position.y));
183 object.emplace("z", Value(event.position.z));
184 object.emplace("nx", Value(event.normal.x));
185 object.emplace("ny", Value(event.normal.y));
186 object.emplace("nz", Value(event.normal.z));
187 object.emplace("sourceId", Value(static_cast<std::int64_t>(event.source.id)));
188 object.emplace("sourceGeneration", Value(static_cast<std::int64_t>(event.source.generation)));
189 object.emplace("targetId", Value(static_cast<std::int64_t>(event.target.id)));
190 object.emplace("targetGeneration", Value(static_cast<std::int64_t>(event.target.generation)));
191 return Value(std::move(object));
192}
193
194Value encodeFrame(const CarrierFrame& frame) {
196 Value::Array advanced;
197 for (const auto& handle : frame.advanced) advanced.push_back(encodeHandle(handle));
198 Value::Array released;
199 for (const auto& handle : frame.released) released.push_back(encodeHandle(handle));
201 for (const auto& event : frame.events) events.push_back(encodeEvent(event));
202 object.emplace("advanced", Value(std::move(advanced)));
203 object.emplace("released", Value(std::move(released)));
204 object.emplace("events", Value(std::move(events)));
205 object.emplace("eventCount", Value(static_cast<std::int64_t>(frame.events.size())));
206 object.emplace("activeAdvanced", Value(static_cast<std::int64_t>(frame.advanced.size())));
207 return Value(std::move(object));
208}
209
210Value encodePlan(const SpellCastPlan& plan) {
212 object.emplace("recipeId", Value(plan.recipe.id.format()));
213 object.emplace("hasVolley", Value(plan.volley.has_value()));
214 if (plan.volley.has_value()) {
215 object.emplace("volleyCount", Value(static_cast<std::int64_t>(plan.volley->count)));
216 object.emplace("volleyPattern",
217 Value(std::string(plan.volley->pattern == CarrierVolleyPattern::Ring ? "ring" : "fan")));
218 object.emplace("volleySpread", Value(plan.volley->spreadDegrees));
219 }
220 return Value(std::move(object));
221}
222
223class ScriptMotionFunction final : public ICarrierMotionFunction {
224public:
225 explicit ScriptMotionFunction(ssq::Function callback) : callback_(std::move(callback)) {}
226 Result<CarrierMotion> evaluate(const CarrierState& before, const CarrierMotion& proposed,
227 Duration step) const override {
228 const auto vm = callback_.getHandle();
229 const auto top = sq_gettop(vm);
230 struct StackGuard {
232 SQInteger top;
233 ~StackGuard() { sq_settop(vm, top); }
234 } guard{vm, top};
235 auto table = [vm](const CarrierMotion& motion) {
236 ssq::Table result(vm);
237 result.set("x", static_cast<float>(motion.position.x));
238 result.set("y", static_cast<float>(motion.position.y));
239 result.set("z", static_cast<float>(motion.position.z));
240 result.set("vx", static_cast<float>(motion.velocity.x));
241 result.set("vy", static_cast<float>(motion.velocity.y));
242 result.set("vz", static_cast<float>(motion.velocity.z));
243 return result;
244 };
245 auto state = table(before.motion);
246 state.set("age", static_cast<float>(before.age.seconds()));
247 state.set("lifetime", static_cast<float>(before.lifetime.seconds()));
248 state.set("distanceTravelled", static_cast<float>(before.distanceTravelled));
249 state.set("recipeId", before.recipeId.format());
250 state.set("slot", static_cast<std::int64_t>(before.handle.slot));
251 state.set("generation", static_cast<std::int64_t>(before.handle.generation));
252 if (SQ_FAILED(script::callFunctionResult(vm, callback_.getRaw(), script::rootTable, state, table(proposed),
253 static_cast<float>(step.seconds()))))
255 DiagnosticCode::Failed, "Custom motion callback threw; see script diagnostic", "motionFunction"));
256 if (sq_gettype(vm, -1) == OT_NULL) return Result<CarrierMotion>::success(proposed);
258 if (!value) return Result<CarrierMotion>::failure(value.status());
259 const auto* object = value.value().getIf<Value::Object>();
260 if (!object)
263 "Motion function must return null or a position/velocity table", "motionFunction"));
264 CarrierMotion output = proposed;
265 int positions = 0, velocities = 0;
266 for (const auto& [name, field] : *object) {
267 double number = 0.0;
268 if (const auto* real = field.getIf<double>())
269 number = *real;
270 else if (const auto* integer = field.getIf<std::int64_t>())
271 number = static_cast<double>(*integer);
272 else
274 Diagnostic::error(DiagnosticCode::InvalidArgument, "Motion coordinate must be a number", name));
275 if (name == "x") {
276 output.position.x = number;
277 ++positions;
278 } else if (name == "y") {
279 output.position.y = number;
280 ++positions;
281 } else if (name == "z") {
282 output.position.z = number;
283 ++positions;
284 } else if (name == "vx") {
285 output.velocity.x = number;
286 ++velocities;
287 } else if (name == "vy") {
288 output.velocity.y = number;
289 ++velocities;
290 } else if (name == "vz") {
291 output.velocity.z = number;
292 ++velocities;
293 } else
295 Diagnostic::error(DiagnosticCode::InvalidArgument, "Unknown motion output field", name));
296 }
297 if ((positions != 0 && positions != 3) || (velocities != 0 && velocities != 3) ||
298 (positions == 0 && velocities == 0))
300 DiagnosticCode::InvalidArgument, "Return complete x/y/z and/or vx/vy/vz groups", "motionFunction"));
301 // Returning the projected proposal is an identity operation despite the VM's float precision.
302 if (positions == 3 && velocities == 3 && output.position.x == static_cast<float>(proposed.position.x) &&
303 output.position.y == static_cast<float>(proposed.position.y) &&
304 output.position.z == static_cast<float>(proposed.position.z) &&
305 output.velocity.x == static_cast<float>(proposed.velocity.x) &&
306 output.velocity.y == static_cast<float>(proposed.velocity.y) &&
307 output.velocity.z == static_cast<float>(proposed.velocity.z))
308 return Result<CarrierMotion>::success(proposed);
309 const double dt = step.seconds();
310 if (positions == 0)
311 output.position = {before.motion.position.x + output.velocity.x * dt,
312 before.motion.position.y + output.velocity.y * dt,
313 before.motion.position.z + output.velocity.z * dt};
314 if (velocities == 0)
315 output.velocity = {(output.position.x - before.motion.position.x) / dt,
316 (output.position.y - before.motion.position.y) / dt,
317 (output.position.z - before.motion.position.z) / dt};
319 }
320
321private:
322 ssq::Function callback_;
323};
324
325class ScriptCombatCarrierRuntime {
326public:
327 ScriptCombatCarrierRuntime() = default;
328
329 [[nodiscard]] Result<Value> configurePool(std::int64_t capacity) {
330 if (evaluating_) return mutationConflict();
331 if (capacity < 1 || capacity > 1048576)
333 "pool capacity must be in 1..1048576", "capacity", {},
334 "weapon.carrier.squirrel"));
335 auto configured = runtime_.configurePool(static_cast<std::uint32_t>(capacity));
336 if (!configured) return Result<Value>::failure(configured.status());
338 object.emplace("capacity", Value(static_cast<std::int64_t>(runtime_.capacity())));
339 return Result<Value>::success(Value(std::move(object)));
340 }
341
342 [[nodiscard]] Result<Value> configureSimulation(double maxStepSeconds, std::int64_t maxIterations,
343 std::int64_t maxCollisions, std::int64_t maxTriggerFirings) {
344 if (evaluating_) return mutationConflict();
345 auto duration = Duration::fromSeconds(maxStepSeconds);
346 if (!duration) return Result<Value>::failure(duration.status());
347 if (maxIterations < 1 || maxIterations > 65536 || maxCollisions < 1 || maxCollisions > 65536 ||
348 maxTriggerFirings < 1 || maxTriggerFirings > 65536)
350 "Simulation budgets must be in 1..65536", "simulation"));
351 CarrierSimulationSettings settings{duration.value(), static_cast<std::uint32_t>(maxIterations),
352 static_cast<std::uint32_t>(maxCollisions),
353 static_cast<std::uint32_t>(maxTriggerFirings)};
354 auto configured = runtime_.configureSimulation(settings);
355 if (!configured) return Result<Value>::failure(configured.status());
357 }
358
359 [[nodiscard]] Result<Value> registerRecipeValue(const Value& value) {
360 if (evaluating_) return mutationConflict();
362 if (!recipe.ok()) return Result<Value>::failure(recipe.status());
363 CarrierRecipe owned = std::move(recipe).takeValue();
364 for (const auto& op : owned.motionOps) {
368 "SteerAvoidBody recipes are not supported by the script carrier runtime; omit avoidBody or use C++",
369 "motion", {}, "weapon.carrier.squirrel"));
370 }
371 }
372 const std::string id = owned.id.format();
373 auto registered = runtime_.registerRecipe(owned);
374 if (!registered) return Result<Value>::failure(registered.status());
376 object.emplace("recipeId", Value(id));
377 return Result<Value>::success(Value(std::move(object)));
378 }
379
380 [[nodiscard]] Result<Value> registerRecipeJson(const std::string& json) {
381 if (evaluating_) return mutationConflict();
382 auto parsed = Value::fromJson(json);
383 if (!parsed.ok()) return Result<Value>::failure(parsed.status());
384 return registerRecipeValue(parsed.value());
385 }
386
387 [[nodiscard]] Result<Value> compileFragmentsValue(const Value& fragments) {
388 if (evaluating_) return mutationConflict();
389 auto plan = compileSpellFragments(fragments);
390 if (!plan.ok()) return Result<Value>::failure(plan.status());
391 return registerPlan(std::move(plan).takeValue());
392 }
393
394 [[nodiscard]] Result<Value> compileFragmentsJson(const std::string& json) {
395 if (evaluating_) return mutationConflict();
396 auto plan = compileSpellFragmentsJson(json);
397 if (!plan.ok()) return Result<Value>::failure(plan.status());
398 return registerPlan(std::move(plan).takeValue());
399 }
400
401 [[nodiscard]] Result<Value> castValue(const Value& fragments, double x, double y, double z, double dx, double dy,
402 double dz, std::int64_t targetId, std::int64_t targetGeneration) {
403 if (evaluating_) return mutationConflict();
404 auto plan = compileSpellFragments(fragments);
405 if (!plan.ok()) return Result<Value>::failure(plan.status());
406 SpellCastPlan owned = std::move(plan).takeValue();
407 auto uniquified = uniquifyRecipeId(owned.recipe.id);
408 if (!uniquified.ok()) return Result<Value>::failure(uniquified.status());
409 owned.recipe.id = uniquified.value();
410
411 bool needsTarget = false;
412 for (const auto& op : owned.recipe.motionOps) {
415 needsTarget = true;
416 }
417 for (const auto& trigger : owned.recipe.triggers) {
418 if (trigger.kind == CarrierTriggerKind::OnProximity) needsTarget = true;
419 }
420 if (needsTarget && targetId <= 0) {
423 "Homing/proximity casts require castAtTarget with a positive target id", "target", {},
424 "weapon.carrier.squirrel"));
425 }
426
427 auto registered = registerPlan(owned);
428 if (!registered.ok()) return registered;
429 return spawnPlan(owned, x, y, z, dx, dy, dz, targetId, targetGeneration);
430 }
431
432 [[nodiscard]] Result<Value> castJson(const std::string& json, double x, double y, double z, double dx, double dy,
433 double dz, std::int64_t targetId, std::int64_t targetGeneration) {
434 if (evaluating_) return mutationConflict();
435 auto parsed = Value::fromJson(json);
436 if (!parsed.ok()) return Result<Value>::failure(parsed.status());
437 return castValue(parsed.value(), x, y, z, dx, dy, dz, targetId, targetGeneration);
438 }
439
440 [[nodiscard]] static Result<void> validateHandleParts(std::int64_t id, std::int64_t generation,
441 std::string_view path) {
442 if (id < 0 || generation < 0 || static_cast<std::uint64_t>(id) > std::numeric_limits<std::uint32_t>::max() ||
443 static_cast<std::uint64_t>(generation) > std::numeric_limits<std::uint32_t>::max()) {
445 "handle id/generation must fit in uint32", std::string(path),
446 {}, "weapon.carrier.squirrel"));
447 }
448 return Result<void>::success();
449 }
450
451 [[nodiscard]] static Result<void> validatePoint(double x, double y, double z, std::string_view path) {
452 if (!std::isfinite(x) || !std::isfinite(y) || !std::isfinite(z)) {
454 "coordinates must be finite", std::string(path), {},
455 "weapon.carrier.squirrel"));
456 }
457 return Result<void>::success();
458 }
459
460 [[nodiscard]] Result<Value> spawn(const std::string& recipeId, double x, double y, double z, double dx, double dy,
461 double dz, std::int64_t targetId, std::int64_t targetGeneration) {
462 if (evaluating_) return mutationConflict();
463 auto id = LogicalId::parse(recipeId);
464 if (!id.has_value())
466 "recipe id must be namespace:name", "recipeId", {},
467 "weapon.carrier.squirrel"));
468 if (auto point = validatePoint(x, y, z, "position"); !point) return Result<Value>::failure(point.status());
469 if (auto point = validatePoint(dx, dy, dz, "direction"); !point) return Result<Value>::failure(point.status());
470 CarrierSpawnRequest request;
471 request.position = {x, y, z};
472 request.direction = {dx, dy, dz};
473 if (targetId > 0) {
474 auto handle = validateHandleParts(targetId, targetGeneration, "target");
475 if (!handle) return Result<Value>::failure(handle.status());
476 ecs::EntityHandle target;
477 target.id = static_cast<std::uint32_t>(targetId);
478 target.generation = static_cast<std::uint32_t>(targetGeneration);
479 request.target = target;
480 }
481 auto spawned = runtime_.spawn(*id, request);
482 if (!spawned.ok()) return Result<Value>::failure(spawned.status());
484 object.emplace("handle", encodeHandle(spawned.value()));
485 object.emplace("activeCount", Value(static_cast<std::int64_t>(runtime_.activeCount())));
486 return Result<Value>::success(Value(std::move(object)));
487 }
488
489 [[nodiscard]] Result<Value> spawnVolley(const std::string& recipeId, double x, double y, double z, double dx,
490 double dy, double dz, std::int64_t count, const std::string& pattern,
491 double spread, std::int64_t targetId, std::int64_t targetGeneration) {
492 if (evaluating_) return mutationConflict();
493 auto id = LogicalId::parse(recipeId);
494 if (!id.has_value())
496 "recipe id must be namespace:name", "recipeId", {},
497 "weapon.carrier.squirrel"));
498 if (auto point = validatePoint(x, y, z, "position"); !point) return Result<Value>::failure(point.status());
499 if (auto point = validatePoint(dx, dy, dz, "direction"); !point) return Result<Value>::failure(point.status());
500 CarrierVolleySpec volley;
501 volley.count = static_cast<int>(count);
502 volley.spreadDegrees = spread;
503 volley.pattern = (pattern == "ring" || pattern == "Ring") ? CarrierVolleyPattern::Ring
505 CarrierSpawnRequest request;
506 request.position = {x, y, z};
507 request.direction = {dx, dy, dz};
508 if (targetId > 0) {
509 auto handle = validateHandleParts(targetId, targetGeneration, "target");
510 if (!handle) return Result<Value>::failure(handle.status());
511 ecs::EntityHandle target;
512 target.id = static_cast<std::uint32_t>(targetId);
513 target.generation = static_cast<std::uint32_t>(targetGeneration);
514 request.target = target;
515 }
516 auto spawned = runtime_.spawnVolley(*id, request, volley);
517 if (!spawned.ok()) return Result<Value>::failure(spawned.status());
518 Value::Array handles;
519 for (const auto& handle : spawned.value()) handles.push_back(encodeHandle(handle));
521 object.emplace("handles", Value(std::move(handles)));
522 object.emplace("count", Value(static_cast<std::int64_t>(spawned.value().size())));
523 object.emplace("activeCount", Value(static_cast<std::int64_t>(runtime_.activeCount())));
524 return Result<Value>::success(Value(std::move(object)));
525 }
526
527 [[nodiscard]] Result<Value> states() const {
529 for (const auto& state : runtime_.states()) {
530 Value::Object entry;
531 entry.emplace("handle", encodeHandle(state.handle));
532 entry.emplace("recipeId", Value(state.recipeId.format()));
533 entry.emplace("x", Value(state.motion.position.x));
534 entry.emplace("y", Value(state.motion.position.y));
535 entry.emplace("z", Value(state.motion.position.z));
536 entry.emplace("vx", Value(state.motion.velocity.x));
537 entry.emplace("vy", Value(state.motion.velocity.y));
538 entry.emplace("vz", Value(state.motion.velocity.z));
539 entry.emplace("age", Value(state.age.seconds()));
540 entry.emplace("distanceTravelled", Value(state.distanceTravelled));
541 values.emplace_back(std::move(entry));
542 }
543 return Result<Value>::success(Value(std::move(values)));
544 }
545
546 [[nodiscard]] Result<Value> bindWorld3D(const std::string& token, float radius, std::int64_t category,
547 std::int64_t mask, std::int64_t ignoredBody) {
548 if (evaluating_) return mutationConflict();
549 if (runtime_.activeCount() != 0)
551 Diagnostic::error(DiagnosticCode::Conflict, "Rebind only with an empty projectile pool", "worldSweep"));
552 if (category < -1 || category > UINT32_MAX || mask < -1 || mask > UINT32_MAX || ignoredBody < -1 ||
553 ignoredBody > INT32_MAX)
555 "Invalid category, mask or ignored body", "worldSweep"));
556 auto* factory = cap::query<IWorldSphereSweepFactory>();
557 if (!factory)
559 DiagnosticCode::Unsupported, "Physics world sweep provider is unavailable", "worldSweep"));
560 auto bound = factory->bind(token, {radius, static_cast<std::uint32_t>(category),
561 static_cast<std::uint32_t>(mask), static_cast<int>(ignoredBody)});
562 if (!bound) return Result<Value>::failure(bound.status());
563 worldHits_ = std::make_unique<WorldHitProbe>(std::move(bound).takeValue());
564 return Result<Value>::success(Value{});
565 }
566 [[nodiscard]] Result<Value> clearWorld3D() {
567 if (evaluating_) return mutationConflict();
568 if (runtime_.activeCount() != 0)
570 Diagnostic::error(DiagnosticCode::Conflict, "Unbind only with an empty projectile pool", "worldSweep"));
571 worldHits_.reset();
572 return Result<Value>::success(Value{});
573 }
574
575 [[nodiscard]] Result<Value> update(double seconds) {
576 if (evaluating_) return mutationConflict();
577 auto delta = Duration::fromSeconds(seconds);
578 if (!delta) return Result<Value>::failure(delta.status());
579 return finishFrame(runtime_.update(delta.value(), &targets_, &hits_, nullptr, worldHits_.get()));
580 }
581
582 [[nodiscard]] Result<Value> updateWithMotion(double seconds, ssq::Object callback) {
583 if (evaluating_) return mutationConflict();
584 if (callback.getType() != ssq::Type::CLOSURE && callback.getType() != ssq::Type::NATIVECLOSURE)
586 "Motion function must be callable", "motionFunction"));
587 auto delta = Duration::fromSeconds(seconds);
588 if (!delta) return Result<Value>::failure(delta.status());
589 struct Guard {
590 bool& flag;
591 ~Guard() { flag = false; }
592 } guard{evaluating_};
593 evaluating_ = true;
594 ScriptMotionFunction function(callback.toFunction());
595 return finishFrame(
596 runtime_.updateWithMotion(delta.value(), function, &targets_, &hits_, nullptr, worldHits_.get()));
597 }
598
599 [[nodiscard]] Result<Value> addHitTarget(std::int64_t id, std::int64_t generation, double x, double y, double z,
600 double radius) {
601 if (evaluating_) return mutationConflict();
602 auto handle = validateHandleParts(id, generation, "target");
603 if (!handle) return Result<Value>::failure(handle.status());
604 auto point = validatePoint(x, y, z, "target");
605 if (!point) return Result<Value>::failure(point.status());
606 if (!(radius > 0.0) || !std::isfinite(radius))
608 "hit target requires positive finite radius", "radius", {},
609 "weapon.carrier.squirrel"));
610 ScriptCircleHitProbe::Target target;
611 target.id.id = static_cast<std::uint32_t>(id);
612 target.id.generation = static_cast<std::uint32_t>(generation);
613 target.center = {x, y, z};
614 target.radius = radius;
615 hits_.add(target);
617 object.emplace("count", Value(static_cast<std::int64_t>(1)));
618 return Result<Value>::success(Value(std::move(object)));
619 }
620
621 [[nodiscard]] Result<Value> clearHitTargets() {
622 if (evaluating_) return mutationConflict();
623 hits_.clear();
625 }
626
627 [[nodiscard]] Result<Value> setTargetPosition(std::int64_t id, std::int64_t generation, double x, double y,
628 double z) {
629 if (evaluating_) return mutationConflict();
630 auto handle = validateHandleParts(id, generation, "target");
631 if (!handle) return Result<Value>::failure(handle.status());
632 auto point = validatePoint(x, y, z, "target");
633 if (!point) return Result<Value>::failure(point.status());
634 ecs::EntityHandle target;
635 target.id = static_cast<std::uint32_t>(id);
636 target.generation = static_cast<std::uint32_t>(generation);
637 targets_.set(target, {x, y, z});
639 }
640
641 [[nodiscard]] Result<Value> clearTargets() {
642 if (evaluating_) return mutationConflict();
643 targets_.clear();
645 }
646
647 [[nodiscard]] std::int64_t activeCount() const noexcept {
648 return static_cast<std::int64_t>(runtime_.activeCount());
649 }
650
651 [[nodiscard]] std::int64_t capacity() const noexcept { return static_cast<std::int64_t>(runtime_.capacity()); }
652
653private:
654 bool evaluating_ = false;
655 [[nodiscard]] static Result<Value> mutationConflict() {
657 Diagnostic::error(DiagnosticCode::Conflict, "Reentrant carrier mutation is forbidden", "runtime"));
658 }
659 [[nodiscard]] Result<Value> finishFrame(Result<CarrierFrame> frame) {
660 if (!frame) return Result<Value>::failure(frame.status());
661 lastFrame_ = frame.value();
662 Value encoded = encodeFrame(lastFrame_);
663 if (auto* object = encoded.getIf<Value::Object>())
664 object->emplace("activeCount", Value(static_cast<std::int64_t>(runtime_.activeCount())));
665 return Result<Value>::success(std::move(encoded));
666 }
667
668 [[nodiscard]] Result<LogicalId> uniquifyRecipeId(const LogicalId& base) {
669 ++castSeq_;
670 const std::string uniqueName = std::string(base.name()) + "-c" + std::to_string(castSeq_);
671 auto parsed = LogicalId::fromParts(base.namespaceName(), uniqueName);
672 if (!parsed.has_value())
674 "unable to allocate unique cast recipe id", "recipeId",
675 {}, "weapon.carrier.squirrel"));
676 return Result<LogicalId>::success(std::move(*parsed));
677 }
678
679 [[nodiscard]] Result<Value> registerPlan(SpellCastPlan plan) {
680 for (const auto& op : plan.recipe.motionOps) {
684 "SteerAvoidBody recipes are not supported by the script carrier runtime",
685 "motion", {}, "weapon.carrier.squirrel"));
686 }
687 }
688 for (const auto& dependent : plan.dependentRecipes) {
689 auto registered = runtime_.registerRecipe(dependent);
690 if (!registered) return Result<Value>::failure(registered.status());
691 }
692 auto registered = runtime_.registerRecipe(plan.recipe);
693 if (!registered) return Result<Value>::failure(registered.status());
694 return Result<Value>::success(encodePlan(plan));
695 }
696
697 [[nodiscard]] Result<Value> spawnPlan(const SpellCastPlan& plan, double x, double y, double z, double dx, double dy,
698 double dz, std::int64_t targetId, std::int64_t targetGeneration) {
699 auto spawned = plan.volley.has_value()
700 ? spawnVolley(plan.recipe.id.format(), x, y, z, dx, dy, dz, plan.volley->count,
701 plan.volley->pattern == CarrierVolleyPattern::Ring ? "ring" : "fan",
702 plan.volley->spreadDegrees, targetId, targetGeneration)
703 : spawn(plan.recipe.id.format(), x, y, z, dx, dy, dz, targetId, targetGeneration);
704 if (!spawned.ok()) return spawned;
705 Value owned = std::move(spawned).takeValue();
706 if (auto* object = owned.getIf<Value::Object>()) {
707 object->emplace("recipeId", Value(plan.recipe.id.format()));
708 }
709 return Result<Value>::success(std::move(owned));
710 }
711
712 CombatCarrierRuntime runtime_;
713 ScriptTargetProvider targets_;
714 ScriptCircleHitProbe hits_;
715 std::unique_ptr<WorldHitProbe> worldHits_;
716 CarrierFrame lastFrame_{};
717 std::uint64_t castSeq_ = 0;
718};
719
720ssq::Table project(HSQUIRRELVM vm, Result<Value>&& result) {
721 return script::projectResult(vm, std::move(result), [](Value value) { return value; });
722}
723
724ssq::Table newCarrierRuntime(HSQUIRRELVM vm, std::int64_t capacity) {
725 if (capacity < 1) capacity = 256;
726 auto runtime = std::make_unique<ScriptCombatCarrierRuntime>();
727 auto configured = runtime->configurePool(capacity);
728 if (!configured.ok()) return script::projectStatusResult(vm, configured.status());
729 auto object = script::makeOwnedSquirrelInstance<ScriptCombatCarrierRuntime>(vm, std::move(runtime));
730 if (!object) return script::projectStatusResult(vm, object.status());
732 result.set("value", std::move(object).takeValue());
733 result.set("ownership", std::string("owned"));
734 return result;
735}
736
737Result<Value> valueFromObject(const ssq::Object& object) {
738 return script::valueFromSquirrel(object);
739}
740
741} // namespace
742
743void exposeCombatCarrierBindings(ssq::Table& table) {
744 const HSQUIRRELVM vm = table.getHandle();
745
746 auto runtime = table.addClass<ScriptCombatCarrierRuntime>(
747 "CombatCarrierRuntime", std::function<ScriptCombatCarrierRuntime*()>([] { return nullptr; }), true);
748 runtime.addFunc("ownership", [](ScriptCombatCarrierRuntime*) { return std::string("owned"); });
749 runtime.addFunc("activeCount", [](ScriptCombatCarrierRuntime* self) {
750 return self ? self->activeCount() : static_cast<std::int64_t>(0);
751 });
752 runtime.addFunc("capacity", [](ScriptCombatCarrierRuntime* self) {
753 return self ? self->capacity() : static_cast<std::int64_t>(0);
754 });
755 runtime.addFunc("configurePool", [vm](ScriptCombatCarrierRuntime* self, std::int64_t capacity) {
756 return project(vm, self ? self->configurePool(capacity) : nullRuntime());
757 });
758 runtime.addFunc(
759 "configureSimulation", [vm](ScriptCombatCarrierRuntime* self, float maxStepSeconds, std::int64_t maxIterations,
760 std::int64_t maxCollisions, std::int64_t maxTriggerFirings) {
761 return project(
762 vm, self ? self->configureSimulation(maxStepSeconds, maxIterations, maxCollisions, maxTriggerFirings)
763 : nullRuntime());
764 });
765 runtime.addFunc("registerRecipe", [vm](ScriptCombatCarrierRuntime* self, ssq::Object recipe) {
766 if (!self) return project(vm, nullRuntime());
767 auto value = valueFromObject(recipe);
768 if (!value.ok()) return project(vm, Result<Value>::failure(value.status()));
769 return project(vm, self->registerRecipeValue(value.value()));
770 });
771 runtime.addFunc("registerRecipeJson", [vm](ScriptCombatCarrierRuntime* self, const std::string& json) {
772 return project(vm, self ? self->registerRecipeJson(json) : nullRuntime());
773 });
774 runtime.addFunc("compileFragments", [vm](ScriptCombatCarrierRuntime* self, ssq::Object fragments) {
775 if (!self) return project(vm, nullRuntime());
776 auto value = valueFromObject(fragments);
777 if (!value.ok()) return project(vm, Result<Value>::failure(value.status()));
778 return project(vm, self->compileFragmentsValue(value.value()));
779 });
780 runtime.addFunc("compileFragmentsJson", [vm](ScriptCombatCarrierRuntime* self, const std::string& json) {
781 return project(vm, self ? self->compileFragmentsJson(json) : nullRuntime());
782 });
783 runtime.addFunc("cast", [vm](ScriptCombatCarrierRuntime* self, ssq::Object fragments, float x, float y, float z,
784 float dx, float dy, float dz) {
785 if (!self) return project(vm, nullRuntime());
786 auto value = valueFromObject(fragments);
787 if (!value.ok()) return project(vm, Result<Value>::failure(value.status()));
788 return project(vm, self->castValue(value.value(), x, y, z, dx, dy, dz, 0, 0));
789 });
790 runtime.addFunc("castAtTarget", [vm](ScriptCombatCarrierRuntime* self, ssq::Object fragments, float x, float y,
791 float z, float dx, float dy, float dz, std::int64_t targetId,
792 std::int64_t targetGeneration) {
793 if (!self) return project(vm, nullRuntime());
794 auto value = valueFromObject(fragments);
795 if (!value.ok()) return project(vm, Result<Value>::failure(value.status()));
796 return project(vm, self->castValue(value.value(), x, y, z, dx, dy, dz, targetId, targetGeneration));
797 });
798 runtime.addFunc("castJson", [vm](ScriptCombatCarrierRuntime* self, const std::string& json, float x, float y,
799 float z, float dx, float dy, float dz) {
800 return project(vm, self ? self->castJson(json, x, y, z, dx, dy, dz, 0, 0) : nullRuntime());
801 });
802 runtime.addFunc("spawn", [vm](ScriptCombatCarrierRuntime* self, const std::string& recipeId, float x, float y,
803 float z, float dx, float dy, float dz) {
804 return project(vm, self ? self->spawn(recipeId, x, y, z, dx, dy, dz, 0, 0) : nullRuntime());
805 });
806 runtime.addFunc("spawnAtTarget", [vm](ScriptCombatCarrierRuntime* self, const std::string& recipeId, float x,
807 float y, float z, float dx, float dy, float dz, std::int64_t targetId,
808 std::int64_t targetGeneration) {
809 return project(vm, self ? self->spawn(recipeId, x, y, z, dx, dy, dz, targetId, targetGeneration)
810 : nullRuntime());
811 });
812 runtime.addFunc("spawnVolley", [vm](ScriptCombatCarrierRuntime* self, const std::string& recipeId, float x, float y,
813 float z, float dx, float dy, float dz, std::int64_t count,
814 const std::string& pattern, float spread) {
815 return project(vm, self ? self->spawnVolley(recipeId, x, y, z, dx, dy, dz, count, pattern, spread, 0, 0)
816 : nullRuntime());
817 });
818 runtime.addFunc("bindWorld3D", [vm](ScriptCombatCarrierRuntime* self, const std::string& token, float radius,
819 std::int64_t category, std::int64_t mask, std::int64_t ignoredBody) {
820 return project(vm, self ? self->bindWorld3D(token, radius, category, mask, ignoredBody) : nullRuntime());
821 });
822 runtime.addFunc("clearWorld3D", [vm](ScriptCombatCarrierRuntime* self) {
823 return project(vm, self ? self->clearWorld3D() : nullRuntime());
824 });
825 runtime.addFunc("states", [vm](ScriptCombatCarrierRuntime* self) {
826 return project(vm, self ? self->states() : nullRuntime());
827 });
828 runtime.addFunc("update", [vm](ScriptCombatCarrierRuntime* self, float seconds) {
829 return project(vm, self ? self->update(seconds) : nullRuntime());
830 });
831 runtime.addFunc("updateWithMotion", [vm](ScriptCombatCarrierRuntime* self, float seconds, ssq::Object function) {
832 return project(vm, self ? self->updateWithMotion(seconds, std::move(function)) : nullRuntime());
833 });
834 runtime.addFunc("addHitTarget", [vm](ScriptCombatCarrierRuntime* self, std::int64_t id, std::int64_t generation,
835 float x, float y, float z, float radius) {
836 return project(vm, self ? self->addHitTarget(id, generation, x, y, z, radius) : nullRuntime());
837 });
838 runtime.addFunc("clearHitTargets", [vm](ScriptCombatCarrierRuntime* self) {
839 return project(vm, self ? self->clearHitTargets() : nullRuntime());
840 });
841 runtime.addFunc("setTargetPosition", [vm](ScriptCombatCarrierRuntime* self, std::int64_t id,
842 std::int64_t generation, float x, float y, float z) {
843 return project(vm, self ? self->setTargetPosition(id, generation, x, y, z) : nullRuntime());
844 });
845 runtime.addFunc("clearTargets", [vm](ScriptCombatCarrierRuntime* self) {
846 return project(vm, self ? self->clearTargets() : nullRuntime());
847 });
848
849 // Module methods are registered from Weapon::expose(Class); helpers also on table for discoverability.
850 (void)vm;
851}
852
854 const HSQUIRRELVM vm = cls.getHandle();
855 cls.addFunc("newCarrierRuntime", [vm](Weapon*, std::int64_t capacity) { return newCarrierRuntime(vm, capacity); });
856 cls.addFunc("newCarrierRuntimeDefault", [vm](Weapon*) { return newCarrierRuntime(vm, 256); });
857}
858
859} // namespace eve::weapon
double z
double y
double x
LogicalId target
float duration
std::string output
ActiveSource owned
int mask
float cx
Definition CardTypes.cpp:36
float cy
Definition CardTypes.cpp:37
Decode/encode CombatCarrier recipes from canonical eve::Value trees.
Composable combat-carrier runtime: motion ops, triggers, and impacts.
struct SQVM * HSQUIRRELVM
Stable, structured diagnostics shared by engine modules.
HSQUIRRELVM vm
Definition ECS.cpp:38
HSQOBJECT cls
Definition ECS.cpp:39
SQObjectPtr key
Definition ECS.cpp:155
Generation generation
Definition ECS.cpp:40
std::string name
Definition ECS.cpp:154
std::string pattern
const GltfImportRequest & request
std::uint32_t spawned
std::uint32_t capacity
wgpu::PopErrorScopeStatus status
std::vector< float > positions
std::array< float, 3 > position
std::string id
Poco::JSON::Object::Ptr result
double radius
Definition MeleeHit.cpp:42
OceanWakeSettings settings
OceanGpuFrameToken token
ssq::Object frame
glm::dvec2 center
glm::dvec3 dx
glm::dvec3 dz
double dt
std::shared_ptr< const OceanSprayFrame > previous
std::vector< particles::ParticleRecordEvent > events
BakeRecipe recipe
std::string path
Definition PlayHost.cpp:111
std::uint32_t targetId
bool hit
PrimitiveHandle handle
std::set< std::string > values
Object::Ptr value
float t
double number
MigrationFunction function
std::string kind
double current
float dy
Definition Shadow.cpp:151
std::optional< CarrierVolleySpec > volley
Compile Noita-style spell/modifier fragment sequences into carrier recipes.
int count
The single Squirrel projection for common Result, Status and Value.
Explicit Value/Owned/Borrowed semantics at the Squirrel boundary.
Json object
Common time values and an injectable deterministic simulation clock.
float step
Definition TreeMesh.cpp:451
const char * category
Owning, renderer-independent dynamic values.
Contact contact
ViewPreparation callback
glm::vec3 point
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
static Result< Duration > fromSeconds(double seconds)
Convert finite seconds to the nearest nanosecond.
Definition Time.cpp:17
static std::optional< LogicalId > fromParts(std::string_view namespaceName, std::string_view name)
Builds a logical ID from separate namespace and name components.
Definition Identity.cpp:49
static std::optional< LogicalId > parse(std::string_view text)
Parses a scoped logical name.
Definition Identity.cpp:37
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Definition Status.cpp:19
static Result< Value > fromJson(std::string_view json)
Parse one strict JSON value into an owning Value.
Definition Value.cpp:177
std::map< std::string, Value > Object
Definition Value.h:34
std::vector< Value > Array
Definition Value.h:33
static Value object(Object value)
Compatibility factory for an object value.
Definition Value.cpp:129
武器模块(eve.Weapon)。
Definition Weapon.h:24
SQInteger top
Definition Snapshot.cpp:115
const Value * field(const Value &value, const char *key)
Borrow an optional object field.
I * query()
Queries .
Definition Capability.h:88
std::variant< std::monostate, std::int64_t, double, std::string, bool > Value
Definition Database.h:27
Snapshot project(Files files, Object::Ptr stats, std::string defaultProjectId, std::string projectDir)
Build a candidate evidence graph without touching the published snapshot.
ForceVector add(ForceVector a, ForceVector b)
Definition ForceMath.h:13
std::unordered_map< std::string, SkillDefinition > & table()
Definition Skill.cpp:73
SQRESULT callFunctionResult(HSQUIRRELVM vm, const HSQOBJECT &fn, const Receiver &receiver, Args &&... args)
callFunction() that keeps the return value on top for the caller to read.
ssq::Table projectStatusResult(HSQUIRRELVM vm, const Status &status)
Project a checked native status that carries no payload.
constexpr RootTable rootTable
ssq::Table projectResult(HSQUIRRELVM vm, Result< void > &&result)
Consume and project a void native Result using the common schema.
Result< Value > valueFromSquirrel(HSQUIRRELVM vm, SQInteger index, const SquirrelValueOptions &options)
Convert one Squirrel value into the canonical owning Value tree.
std::vector< OnnxNamedTensor > evaluate(const ModelData &, std::span< const OnnxNamedTensor >, const std::vector< std::string > &, OnnxCompute *, OnnxRunOptions options)
Evaluate.
载具模块入口(eve.Vehicle):定义注册 / 实体工厂 / RTS 命令 / 帧调度。 设计文档:docs/dev/通用载具系统设计.md
CarrierImpactKind
What happens when a matching trigger fires.
void exposeCombatCarrierModuleMethods(ssq::Class &cls)
Register Weapon module methods that create owned carrier runtimes.
Result< CarrierRecipe > decodeCarrierRecipe(const Value &value)
Decode one CarrierRecipe from an owning Value object.
CarrierTriggerKind
When an impact may fire.
void exposeCombatCarrierBindings(ssq::Table &table)
Expose CombatCarrierRuntime class bindings under the shared eve table.
Result< SpellCastPlan > compileSpellFragmentsJson(const std::string &json)
Compile a JSON array string into one cast plan.
Result< SpellCastPlan > compileSpellFragments(const Value &fragments)
Compile a fragment array Value into one cast plan.
CarrierVolleyPattern
Multi-projectile aim pattern for one salvo.