载入中...
搜索中...
未找到
CombatCarrier.cpp
浏览该文件的文档.
1// eve-hot-path
3
4#include "common/Diagnostic.h"
5
6#include <algorithm>
7#include <cmath>
8#include <exception>
9#include <functional>
10#include <limits>
11#include <utility>
12
13namespace eve::weapon {
14namespace {
15
16constexpr std::uint32_t kDefaultCapacity = 128;
17constexpr std::uint32_t kMaximumCapacity = 1024 * 1024;
18constexpr double kPi = 3.14159265358979323846;
19
20bool sameTarget(ecs::EntityHandle a, ecs::EntityHandle b) {
21 return a.table == b.table && a.type == b.type && a.id == b.id && a.generation == b.generation;
22}
23
24bool finite(const ProjectilePoint& value) {
25 return std::isfinite(value.x) && std::isfinite(value.y) && std::isfinite(value.z);
26}
27
28bool finite(const ProjectileVector& value) {
29 return std::isfinite(value.x) && std::isfinite(value.y) && std::isfinite(value.z);
30}
31
32double length(const ProjectileVector& value) { return std::hypot(value.x, value.y, value.z); }
33
34ProjectileVector normalized(const ProjectileVector& value) {
35 const double magnitude = length(value);
36 return {value.x / magnitude, value.y / magnitude, value.z / magnitude};
37}
38
39ProjectileVector directionTo(const ProjectilePoint& from, const ProjectilePoint& to) {
40 return {to.x - from.x, to.y - from.y, to.z - from.z};
41}
42
43ProjectileVector steer(ProjectileVector velocity, ProjectileVector desired, double maxRadians) {
44 const double speed = length(velocity);
45 if (speed <= 0.0) return velocity;
46 ProjectileVector current = normalized(velocity);
47 desired = normalized(desired);
48 const double dot = std::clamp(current.x * desired.x + current.y * desired.y + current.z * desired.z, -1.0, 1.0);
49 const double angle = std::acos(dot);
50 if (angle <= maxRadians || angle <= 1e-12) return {desired.x * speed, desired.y * speed, desired.z * speed};
51 // Rotate through the exact angular budget, including antiparallel directions.
52 ProjectileVector tangent{desired.x - dot * current.x, desired.y - dot * current.y, desired.z - dot * current.z};
53 if (length(tangent) <= 1e-12) {
54 const ProjectileVector basis =
55 std::fabs(current.y) < 0.9 ? ProjectileVector{0.0, 1.0, 0.0} : ProjectileVector{1.0, 0.0, 0.0};
56 const double projection = basis.x * current.x + basis.y * current.y + basis.z * current.z;
57 tangent = {basis.x - projection * current.x, basis.y - projection * current.y,
58 basis.z - projection * current.z};
59 }
60 tangent = normalized(tangent);
61 return {(current.x * std::cos(maxRadians) + tangent.x * std::sin(maxRadians)) * speed,
62 (current.y * std::cos(maxRadians) + tangent.y * std::sin(maxRadians)) * speed,
63 (current.z * std::cos(maxRadians) + tangent.z * std::sin(maxRadians)) * speed};
64}
65
66ProjectileVector reflect(ProjectileVector velocity, ProjectileVector normal) {
67 const double nLen = length(normal);
68 if (nLen <= 1e-12) return velocity;
69 normal = {normal.x / nLen, normal.y / nLen, normal.z / nLen};
70 const double into = velocity.x * normal.x + velocity.y * normal.y + velocity.z * normal.z;
71 return {velocity.x - 2.0 * into * normal.x, velocity.y - 2.0 * into * normal.y,
72 velocity.z - 2.0 * into * normal.z};
73}
74
75ProjectileVector cross(const ProjectileVector& a, const ProjectileVector& b) {
76 return {a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x};
77}
78
79ProjectileVector rotateAroundAxis(ProjectileVector vector, ProjectileVector axis, double radians) {
80 axis = normalized(axis);
81 const double cosA = std::cos(radians);
82 const double sinA = std::sin(radians);
83 const auto axisCrossV = cross(axis, vector);
84 const double axisDotV = axis.x * vector.x + axis.y * vector.y + axis.z * vector.z;
85 return {vector.x * cosA + axisCrossV.x * sinA + axis.x * axisDotV * (1.0 - cosA),
86 vector.y * cosA + axisCrossV.y * sinA + axis.y * axisDotV * (1.0 - cosA),
87 vector.z * cosA + axisCrossV.z * sinA + axis.z * axisDotV * (1.0 - cosA)};
88}
89
90ProjectileVector lateralBasis(const ProjectileVector& forward) {
91 ProjectileVector up{0.0, 1.0, 0.0};
92 auto side = cross(forward, up);
93 if (length(side) <= 1e-12) {
94 up = {1.0, 0.0, 0.0};
95 side = cross(forward, up);
96 }
97 return normalized(side);
98}
99
100double randomSample(std::uint32_t seed, CarrierHandle handle, std::uint32_t tick, std::uint32_t channel) {
101 std::uint32_t value = seed ^ (handle.slot * 0x9e3779b9U) ^ handle.generation ^ (tick * 0x85ebca6bU) ^ channel;
102 value ^= value >> 16;
103 value *= 0x7feb352dU;
104 value ^= value >> 15;
105 value *= 0x846ca68bU;
106 value ^= value >> 16;
107 return static_cast<double>(value) / 4294967295.0;
108}
109
110bool crossed(Duration previousAge, Duration nextAge, Duration mark) {
111 return previousAge < mark && nextAge >= mark;
112}
113
114std::int64_t intervalIndex(Duration age, Duration interval) {
115 if (interval <= Duration::zero()) return 0;
116 return age.nanoseconds() / interval.nanoseconds();
117}
118
119Result<void> validateVolley(const CarrierVolleySpec& volley) {
120 if (volley.count <= 0)
121 return Result<void>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument, "Volley count must be positive", "count"));
122 if (volley.count > 256)
123 return Result<void>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument, "Volley count must be <= 256", "count"));
124 if (volley.pattern == CarrierVolleyPattern::Fan) {
125 if (!std::isfinite(volley.spreadDegrees) || volley.spreadDegrees < 0.0)
126 return Result<void>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument, "Fan volley spreadDegrees must be finite and non-negative", "spreadDegrees"));
127 }
128 return Result<void>::success();
129}
130
131Result<std::vector<ProjectileVector>> volleyDirections(const ProjectileVector& base,
132 const CarrierVolleySpec& volley) {
133 auto valid = validateVolley(volley);
134 if (!valid) return Result<std::vector<ProjectileVector>>::failure(valid.status());
135 if (length(base) <= 1e-12)
136 return Result<std::vector<ProjectileVector>>::failure(
137 Diagnostic::error(DiagnosticCode::InvalidArgument, "Volley base direction must be non-zero", "direction"));
138
139 const auto forward = normalized(base);
140 ProjectileVector yawAxis{0.0, 1.0, 0.0};
141 if (std::fabs(forward.x * yawAxis.x + forward.y * yawAxis.y + forward.z * yawAxis.z) > 0.999)
142 yawAxis = lateralBasis(forward);
143
144 std::vector<ProjectileVector> directions;
145 directions.reserve(static_cast<std::size_t>(volley.count));
146 if (volley.count == 1) {
147 directions.push_back(forward);
148 return Result<std::vector<ProjectileVector>>::success(std::move(directions));
149 }
150 if (volley.pattern == CarrierVolleyPattern::Ring) {
151 for (int i = 0; i < volley.count; ++i) {
152 const double radians = (2.0 * kPi * static_cast<double>(i)) / static_cast<double>(volley.count);
153 directions.push_back(normalized(rotateAroundAxis(forward, yawAxis, radians)));
154 }
155 return Result<std::vector<ProjectileVector>>::success(std::move(directions));
156 }
157 const double total = volley.spreadDegrees * kPi / 180.0;
158 for (int i = 0; i < volley.count; ++i) {
159 const double t = static_cast<double>(i) / static_cast<double>(volley.count - 1);
160 const double radians = -0.5 * total + t * total;
161 directions.push_back(normalized(rotateAroundAxis(forward, yawAxis, radians)));
162 }
163 return Result<std::vector<ProjectileVector>>::success(std::move(directions));
164}
165
166} // namespace
167
169 if (!id.isValid()) return Result<void>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument, "Carrier recipe id must not be empty", "id"));
170 if (lifetime <= Duration::zero())
171 return Result<void>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument, "Carrier lifetime must be positive", "lifetime"));
172 if (!std::isfinite(speed) || speed <= 0.0)
173 return Result<void>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument, "Carrier speed must be finite and positive", "speed"));
174 if (motionOps.empty())
175 return Result<void>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument, "Carrier recipe requires at least one motion op", "motionOps"));
176
177 if (motionOps.size() > 64 || triggers.size() > 64 || impacts.size() > 256)
180 "Carrier recipe exceeds operator/trigger/impact budgets (64/64/256)", "recipe"));
181 bool hasIntegrate = false;
182 bool curveTail = false;
183 for (std::size_t i = 0; i < motionOps.size(); ++i) {
184 const auto& op = motionOps[i];
185 const auto path = "motionOps[" + std::to_string(i) + "]";
186 const bool curve = op.kind == CarrierMotionOpKind::CurveSway || op.kind == CarrierMotionOpKind::CurveHelix;
187 if (curveTail && !curve && op.kind != CarrierMotionOpKind::IntegrateLinear)
190 "Curve modifiers must be the final operators before integration", path));
191 curveTail = curveTail || curve;
192 switch (op.kind) {
194 if (!std::isfinite(op.predictionSeconds) || op.predictionSeconds <= 0.0)
196 DiagnosticCode::InvalidArgument, "Prediction horizon must be finite and positive", path));
197 [[fallthrough]];
199 if (!std::isfinite(op.maxTurnRateDegrees) || op.maxTurnRateDegrees <= 0.0)
200 return Result<void>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument, "Homing turn rate must be finite and positive", path + ".maxTurnRateDegrees"));
201 break;
203 if (!std::isfinite(op.avoidLookAhead) || op.avoidLookAhead <= 0.0)
204 return Result<void>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument, "Body-avoid look-ahead must be finite and positive", path + ".avoidLookAhead"));
205 if (!std::isfinite(op.avoidStrength) || op.avoidStrength < 0.0)
206 return Result<void>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument, "Body-avoid strength must be finite and non-negative", path + ".avoidStrength"));
207 if (!std::isfinite(op.avoidRadiusPadding) || op.avoidRadiusPadding < 0.0)
208 return Result<void>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument, "Body-avoid radius padding must be finite and non-negative", path + ".avoidRadiusPadding"));
209 if (!std::isfinite(op.maxTurnRateDegrees) || op.maxTurnRateDegrees <= 0.0)
210 return Result<void>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument, "Body-avoid turn rate must be finite and positive", path + ".maxTurnRateDegrees"));
211 break;
213 if (!std::isfinite(op.gravity) || op.gravity < 0.0)
214 return Result<void>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument, "Gravity must be finite and non-negative", path + ".gravity"));
215 break;
217 if (!std::isfinite(op.acceleration))
219 DiagnosticCode::InvalidArgument, "Acceleration must be finite", path + ".acceleration"));
220 break;
223 if (!finite(op.axis) || length(op.axis) <= 1e-12 || !std::isfinite(length(op.axis)) ||
224 !std::isfinite(op.angularRateDegrees) ||
226 (!std::isfinite(op.orbitRadius) || op.orbitRadius <= 0.0 ||
227 !std::isfinite(op.maxTurnRateDegrees) || op.maxTurnRateDegrees <= 0.0)))
230 "Invalid rotation axis, angular rate, orbit radius or turn rate", path));
231 break;
233 if (!std::isfinite(op.drag) || op.drag < 0.0)
235 "Drag must be finite and non-negative", path));
236 break;
238 if (op.randomSeed < 0 || !std::isfinite(op.maxTurnRateDegrees) || op.maxTurnRateDegrees <= 0.0)
241 "Wander requires nonnegative seed and positive turn rate", path));
242 [[fallthrough]];
246 if (!std::isfinite(op.curveAmplitude) || op.curveAmplitude < 0.0)
247 return Result<void>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument, "Curve amplitude must be finite and non-negative", path + ".curveAmplitude"));
248 if (!std::isfinite(op.curveFrequencyHz) || op.curveFrequencyHz <= 0.0)
249 return Result<void>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument, "Curve frequency must be finite and positive", path + ".curveFrequencyHz"));
250 break;
252 if (hasIntegrate || i + 1 != motionOps.size())
255 "Exactly one integrator must be last in the motion stack", path));
256 hasIntegrate = true;
257 break;
258 default:
260 Diagnostic::error(DiagnosticCode::InvalidArgument, "Unknown carrier motion operator", path));
261 }
262 }
263 if (!hasIntegrate)
264 return Result<void>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument, "Carrier recipe must include IntegrateLinear so position advances", "motionOps"));
265
266 if (triggers.empty())
267 return Result<void>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument, "Carrier recipe requires at least one trigger", "triggers"));
268
269 for (std::size_t i = 0; i < triggers.size(); ++i) {
270 const auto& trigger = triggers[i];
271 const auto path = "triggers[" + std::to_string(i) + "]";
272 for (std::size_t previous = 0; previous < i; ++previous) {
273 if (triggers[previous].kind == trigger.kind)
276 "Trigger kinds must be unique because impacts bind by kind", path));
277 }
278 switch (trigger.kind) {
280 if (trigger.fuse <= Duration::zero())
281 return Result<void>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument, "Fuse trigger requires positive fuse", path + ".fuse"));
282 break;
284 if (trigger.interval <= Duration::zero())
285 return Result<void>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument, "Interval trigger requires positive interval", path + ".interval"));
286 break;
288 if (!std::isfinite(trigger.proximityRadius) || trigger.proximityRadius <= 0.0)
289 return Result<void>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument, "Proximity trigger requires positive radius", path + ".proximityRadius"));
290 break;
293 if (!std::isfinite(trigger.threshold) || trigger.threshold <= 0.0)
295 DiagnosticCode::InvalidArgument, "Trigger threshold must be finite and positive", path));
296 break;
300 break;
301 default:
303 Diagnostic::error(DiagnosticCode::InvalidArgument, "Unknown carrier trigger", path));
304 }
305 }
306
307 for (std::size_t i = 0; i < impacts.size(); ++i) {
308 const auto& impact = impacts[i];
309 const auto path = "impacts[" + std::to_string(i) + "]";
310 if (impact.kind > CarrierImpactKind::EmitTrigger ||
311 std::none_of(triggers.begin(), triggers.end(),
312 [&](const CarrierTrigger& trigger) { return trigger.kind == impact.on; }))
314 "Impact kind is unknown or has no matching trigger", path));
315 if (!std::isfinite(impact.damage) || impact.damage < 0.0)
316 return Result<void>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument, "Impact damage must be finite and non-negative", path + ".damage"));
317 if (!std::isfinite(impact.splashRadius) || impact.splashRadius < 0.0)
318 return Result<void>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument, "Splash radius must be finite and non-negative", path + ".splashRadius"));
319 if (!std::isfinite(impact.restitution) || impact.restitution < 0.0)
320 return Result<void>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument, "Bounce restitution must be finite and non-negative", path + ".restitution"));
321 if (!std::isfinite(impact.bounceFriction) || impact.bounceFriction < 0.0 || impact.bounceFriction > 1.0 ||
322 !std::isfinite(impact.bounceSpreadDegrees) || impact.bounceSpreadDegrees < 0.0 ||
323 impact.bounceSpreadDegrees > 90.0 || impact.randomSeed < 0)
326 "Bounce friction/spread/seed must be in [0,1]/[0,90]/nonnegative", path));
327 if (impact.pierceCount < 0 || impact.bounceCount < 0)
328 return Result<void>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument, "Pierce/bounce budgets must be non-negative", path));
329 if (impact.kind == CarrierImpactKind::SpawnChild && !impact.childRecipeId.isValid())
330 return Result<void>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument, "SpawnChild requires childRecipeId", path + ".childRecipeId"));
331 if (impact.kind == CarrierImpactKind::Splash && impact.splashRadius <= 0.0)
332 return Result<void>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument, "Splash impact requires positive splashRadius", path + ".splashRadius"));
333 }
334 return Result<void>::success();
335}
336
338 auto valid = definition.validate();
339 if (!valid) return Result<CarrierRecipe>::failure(valid.status());
340 if (!std::isfinite(damage) || damage < 0.0)
342 DiagnosticCode::InvalidArgument, "Bridge damage must be finite and non-negative", "damage"));
343
345 recipe.id = definition.id;
346 recipe.lifetime = definition.lifetime;
347 recipe.speed = definition.speed;
348
349 switch (definition.mode) {
351 recipe.motionOps.push_back({CarrierMotionOpKind::IntegrateLinear});
352 break;
354 recipe.motionOps.push_back({CarrierMotionOpKind::ApplyGravity, definition.gravity});
355 recipe.motionOps.push_back({CarrierMotionOpKind::IntegrateLinear});
356 break;
358 recipe.motionOps.push_back(
359 {CarrierMotionOpKind::SteerHoming, 0.0, definition.maxTurnRateDegrees});
360 recipe.motionOps.push_back({CarrierMotionOpKind::IntegrateLinear});
361 break;
362 }
363
364 recipe.triggers.push_back({CarrierTriggerKind::OnExpire});
365 recipe.triggers.push_back({CarrierTriggerKind::OnHit});
366 recipe.impacts.push_back({CarrierImpactKind::EmitHit, CarrierTriggerKind::OnHit, damage});
369
370 auto recipeValid = recipe.validate();
371 if (!recipeValid) return Result<CarrierRecipe>::failure(recipeValid.status());
372 return Result<CarrierRecipe>::success(std::move(recipe));
373}
374
375CombatCarrierRuntime::CombatCarrierRuntime() : slots_(kDefaultCapacity) {}
376
378 if (maxStep < Duration::zero() || maxIterations == 0 || maxIterations > 65536 || maxCollisions == 0 ||
379 maxCollisions > 65536 || maxTriggerFirings == 0 || maxTriggerFirings > 65536)
382 "Simulation requires nonnegative maxStep and budgets in 1..65536", "simulation"));
383 return Result<void>::success();
384}
385
387 if (updating_ || activeCount_ != 0)
389 DiagnosticCode::Conflict, "Configure simulation only while empty and outside callbacks", "simulation"));
390 auto valid = settings.validate();
391 if (!valid) return valid;
392 simulation_ = settings;
393 return Result<void>::success();
394}
395
397 if (updating_)
399 Diagnostic::error(DiagnosticCode::Conflict, "Reentrant carrier mutation is forbidden", "runtime"));
400 if (activeCount_ != 0)
401 return Result<void>::failure(Diagnostic::error(DiagnosticCode::Conflict, "Carrier pool cannot be resized while active", {}));
402 if (capacity == 0 || capacity > kMaximumCapacity)
403 return Result<void>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument, "Carrier pool capacity must be in 1..1048576", "capacity"));
404 slots_.assign(capacity, Slot{});
405 return Result<void>::success();
406}
407
408Result<CombatCarrierRuntime::LiveRecipe> CombatCarrierRuntime::prepareRecipe(const CarrierRecipe& recipe) {
409 auto valid = recipe.validate();
410 if (!valid) return Result<LiveRecipe>::failure(valid.status());
411
412 LiveRecipe live;
413 live.recipe = recipe;
414 for (const auto& op : recipe.motionOps) {
417 live.needsHoming = true;
418 if (op.kind == CarrierMotionOpKind::SteerAvoidBody) live.needsBodyAvoid = true;
419 }
420 for (const auto& trigger : recipe.triggers) {
421 if (trigger.kind == CarrierTriggerKind::OnHit) live.needsHit = recipe.collisionEnabled;
422 if (trigger.kind == CarrierTriggerKind::OnProximity) live.needsProximity = true;
423 }
424 for (const auto& impact : recipe.impacts) {
425 if (impact.kind == CarrierImpactKind::Pierce)
426 live.initialPierce = std::max(live.initialPierce, impact.pierceCount);
427 if (impact.kind == CarrierImpactKind::Bounce)
428 live.initialBounce = std::max(live.initialBounce, impact.bounceCount);
429 }
430 return Result<LiveRecipe>::success(std::move(live));
431}
432
434 if (updating_)
436 Diagnostic::error(DiagnosticCode::Conflict, "Reentrant carrier mutation is forbidden", "runtime"));
437 auto prepared = prepareRecipe(recipe);
438 if (!prepared) return Result<void>::failure(prepared.status());
439 LiveRecipe live = std::move(prepared).takeValue();
440 for (auto& existing : recipes_) {
441 if (existing.recipe.id == recipe.id) {
442 if (existing.recipe == recipe) return Result<void>::success(Status::success(StatusCode::NoOp));
443 if (std::any_of(slots_.begin(), slots_.end(),
444 [&](const Slot& slot) { return slot.state && slot.state->recipeId == recipe.id; }))
446 DiagnosticCode::Conflict, "Release live carriers before replacing their recipe", "recipeId"));
447 existing = std::move(live);
448 return Result<void>::success();
449 }
450 }
451 recipes_.push_back(std::move(live));
452 return Result<void>::success();
453}
454
455std::optional<CarrierRecipe> CombatCarrierRuntime::findRecipe(const LogicalId& id) const {
456 for (const auto& live : recipes_) {
457 if (live.recipe.id == id) return live.recipe;
458 }
459 return std::nullopt;
460}
461
462Result<void> CombatCarrierRuntime::validateSpawn(const CarrierRecipe& recipe,
464 auto valid = recipe.validate();
465 if (!valid) return valid;
466 if (!finite(request.position) || !finite(request.direction) || !std::isfinite(length(request.direction)))
467 return Result<void>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument, "Carrier transform must contain finite values", "request"));
468 if (length(request.direction) <= 0.0)
469 return Result<void>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument, "Carrier direction must be non-zero", "direction"));
470
471 bool needsTarget = false;
472 for (const auto& op : recipe.motionOps) {
475 needsTarget = true;
476 }
477 for (const auto& trigger : recipe.triggers) {
478 if (trigger.kind == CarrierTriggerKind::OnProximity) needsTarget = true;
479 }
480 if (needsTarget && !request.target.has_value())
481 return Result<void>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument, "Homing/proximity carrier requires a target handle", "target"));
482 return Result<void>::success();
483}
484
485Result<CarrierHandle> CombatCarrierRuntime::spawnPrepared(const LiveRecipe& live,
486 const CarrierSpawnRequest& request) {
487 auto valid = validateSpawn(live.recipe, request);
488 if (!valid) return Result<CarrierHandle>::failure(valid.status());
489
490 for (std::uint32_t slot = 0; slot < slots_.size(); ++slot) {
491 if (slots_[slot].state.has_value()) continue;
492 Slot& cell = slots_[slot];
493 ++cell.generation;
494 if (cell.generation == 0) ++cell.generation;
495
496 CarrierState state;
497 state.handle = {slot, cell.generation};
498 state.recipeId = live.recipe.id;
499 state.lifetime = live.recipe.lifetime;
500 state.age = Duration::zero();
501 state.pierceRemaining = live.initialPierce;
502 state.bounceRemaining = live.initialBounce;
503 state.target = request.target;
504 state.source = request.source;
505 const auto dir = normalized(request.direction);
506 state.heading = dir;
507 state.motion.position = request.position;
508 state.motion.velocity = {dir.x * live.recipe.speed, dir.y * live.recipe.speed, dir.z * live.recipe.speed};
509 cell.state = std::move(state);
510 ++activeCount_;
511 return Result<CarrierHandle>::success(cell.state->handle);
512 }
514 Diagnostic::error(DiagnosticCode::Conflict, "Carrier pool is full", "capacity"));
515}
516
518 if (updating_)
520 Diagnostic::error(DiagnosticCode::Conflict, "Reentrant carrier mutation is forbidden", "runtime"));
521 for (const auto& live : recipes_) {
522 if (live.recipe.id == recipeId) return spawnPrepared(live, request);
523 }
525 Diagnostic::error(DiagnosticCode::NotFound, "Carrier recipe is not registered", "recipeId"));
526}
527
529 if (updating_)
531 Diagnostic::error(DiagnosticCode::Conflict, "Reentrant carrier mutation is forbidden", "runtime"));
532 auto valid = validateSpawn(recipe, request);
533 if (!valid) return Result<CarrierHandle>::failure(valid.status());
534 if (activeCount_ >= slots_.size())
536 Diagnostic::error(DiagnosticCode::Conflict, "Carrier pool is full", "capacity"));
537 auto registered = registerRecipe(recipe);
538 if (!registered) return Result<CarrierHandle>::failure(registered.status());
539 return spawn(recipe.id, request);
540}
541
544 const CarrierVolleySpec& volley) {
545 if (updating_)
546 return Result<std::vector<CarrierHandle>>::failure(
547 Diagnostic::error(DiagnosticCode::Conflict, "Reentrant carrier mutation is forbidden", "runtime"));
548 auto dirs = volleyDirections(request.direction, volley);
549 if (!dirs) return Result<std::vector<CarrierHandle>>::failure(dirs.status());
550 if (activeCount_ + dirs.value().size() > slots_.size())
551 return Result<std::vector<CarrierHandle>>::failure(
552 Diagnostic::error(DiagnosticCode::Conflict, "Carrier pool cannot fit the full volley", "capacity"));
553
554 std::vector<CarrierHandle> handles;
555 handles.reserve(dirs.value().size());
556 const std::size_t activeBefore = activeCount_;
557 const auto slotsBefore = slots_;
558 for (const auto& direction : dirs.value()) {
560 one.direction = direction;
561 auto spawned = spawn(recipeId, one);
562 if (!spawned) {
563 slots_ = slotsBefore;
564 activeCount_ = activeBefore;
565 return Result<std::vector<CarrierHandle>>::failure(spawned.status());
566 }
567 handles.push_back(spawned.value());
568 }
569 return Result<std::vector<CarrierHandle>>::success(std::move(handles));
570}
571
574 const CarrierVolleySpec& volley) {
575 if (updating_)
576 return Result<std::vector<CarrierHandle>>::failure(
577 Diagnostic::error(DiagnosticCode::Conflict, "Reentrant carrier mutation is forbidden", "runtime"));
578 auto valid = validateSpawn(recipe, request);
579 if (!valid) return Result<std::vector<CarrierHandle>>::failure(valid.status());
580 auto directions = volleyDirections(request.direction, volley);
581 if (!directions) return Result<std::vector<CarrierHandle>>::failure(directions.status());
582 if (activeCount_ + directions.value().size() > slots_.size())
583 return Result<std::vector<CarrierHandle>>::failure(
584 Diagnostic::error(DiagnosticCode::Conflict, "Carrier pool cannot fit the full volley", "capacity"));
585 auto registered = registerRecipe(recipe);
586 if (!registered) return Result<std::vector<CarrierHandle>>::failure(registered.status());
587 return spawnVolley(recipe.id, request, volley);
588}
589
591 const ICarrierHitProbe* hits,
592 const ICarrierBodyDefenseProvider* bodies,
593 const ICarrierHitProbe* worldSweep) {
594 return updateImpl(delta, targets, hits, bodies, nullptr, worldSweep);
595}
596
599 const ICarrierHitProbe* hits,
600 const ICarrierBodyDefenseProvider* bodies,
601 const ICarrierHitProbe* worldSweep) {
602 return updateImpl(delta, targets, hits, bodies, &motion, worldSweep);
603}
604
605Result<CarrierFrame> CombatCarrierRuntime::updateImpl(Duration delta, const IProjectileTargetProvider* targets,
606 const ICarrierHitProbe* hits,
607 const ICarrierBodyDefenseProvider* bodies,
608 const ICarrierMotionFunction* customMotion,
609 const ICarrierHitProbe* worldSweep) {
610 if (updating_)
612 Diagnostic::error(DiagnosticCode::Conflict, "Reentrant carrier mutation is forbidden", "runtime"));
613 struct UpdateGuard {
614 bool& active;
615 explicit UpdateGuard(bool& flag) : active(flag) { active = true; }
616 ~UpdateGuard() { active = false; }
617 } guard(updating_);
618
619 if (delta < Duration::zero())
621 Diagnostic::error(DiagnosticCode::InvalidArgument, "Carrier update delta must be >= 0", "delta"));
623
624 struct Candidate {
625 CarrierState state;
626 bool release = false;
627 };
628 struct TriggerFire {
629 CarrierTriggerKind kind = CarrierTriggerKind::OnExpire;
630 std::optional<ICarrierHitProbe::Contact> contact;
631 Duration at;
632 };
633
634 std::vector<Candidate> candidates;
635 std::vector<CarrierEvent> events;
636 std::vector<CarrierChildSpawn> childSpawns;
637 candidates.reserve(activeCount_);
638
639 auto lookupLive = [&](const LogicalId& id) -> const LiveRecipe* {
640 for (const auto& live : recipes_) {
641 if (live.recipe.id == id) return &live;
642 }
643 return nullptr;
644 };
645
646 for (const auto& slot : slots_) {
647 if (!slot.state.has_value()) continue;
648 const LiveRecipe* live = lookupLive(slot.state->recipeId);
649 if (live == nullptr)
651 DiagnosticCode::NotFound, "Live carrier references an unregistered recipe", "recipeId"));
652 if ((live->needsHoming || live->needsProximity) && targets == nullptr)
654 DiagnosticCode::Unsupported, "Homing/proximity carrier update requires a target provider", "targets"));
655 if (live->needsHit && (live->recipe.physicsWorldSweep ? worldSweep : hits) == nullptr)
656 return Result<CarrierFrame>::failure(
657 Diagnostic::error(DiagnosticCode::Unsupported, "Enabled OnHit collision requires its selected probe",
658 live->recipe.physicsWorldSweep ? "worldSweep" : "hits"));
659 if (live->needsBodyAvoid && bodies == nullptr)
662 "SteerAvoidBody carrier update requires a body-defense provider", "bodies"));
663 candidates.push_back({*slot.state, false});
664 }
665
666 for (auto& candidate : candidates) {
667 const LiveRecipe* live = lookupLive(candidate.state.recipeId);
668 if (live == nullptr)
670 DiagnosticCode::NotFound, "Live carrier references an unregistered recipe", "recipeId"));
671
672 std::optional<ProjectilePoint> targetPos;
673 if (live->needsHoming || live->needsProximity) {
674 if (!candidate.state.target.has_value())
676 DiagnosticCode::InvalidArgument, "Homing/proximity carrier lost its target handle", "target"));
677 auto resolved = targets->position(*candidate.state.target);
678 if (!resolved) return Result<CarrierFrame>::failure(resolved.status());
679 targetPos = resolved.value();
680 if (!finite(*targetPos))
682 Diagnostic::error(DiagnosticCode::InvalidArgument, "Target position must be finite", "targets"));
683 }
684
685 const Duration sampleAge = candidate.state.age;
686 ProjectileVector targetVelocity{};
687 if (targetPos && candidate.state.previousTargetPosition &&
688 sampleAge > candidate.state.previousTargetSampleAge) {
689 const double sampleDt =
690 static_cast<double>(sampleAge.nanoseconds() - candidate.state.previousTargetSampleAge.nanoseconds()) *
691 1e-9;
692 const auto displacement = directionTo(*candidate.state.previousTargetPosition, *targetPos);
693 targetVelocity = {displacement.x / sampleDt, displacement.y / sampleDt, displacement.z / sampleDt};
694 }
695 std::int64_t remaining =
696 std::min(delta.nanoseconds(), candidate.state.lifetime.nanoseconds() - candidate.state.age.nanoseconds());
697 std::uint32_t iterations = 0, collisions = 0, triggerFirings = 0;
698 while (remaining > 0 && !candidate.release) {
699 if (++iterations > simulation_.maxIterations)
702 "Carrier simulation iteration budget exhausted; retry with smaller dt or a larger budget",
703 "simulation"));
704 const CarrierState segmentStart = candidate.state;
705 const Duration previousAge = segmentStart.age;
706 const double previousDistance = segmentStart.distanceTravelled;
707 CarrierMotion previous = segmentStart.motion;
708 CarrierMotion motion = previous;
709 const auto oldCurve = segmentStart.curveVelocity;
710 motion.velocity = {motion.velocity.x - oldCurve.x, motion.velocity.y - oldCurve.y,
711 motion.velocity.z - oldCurve.z};
712 ProjectileVector curveVelocity{};
713 const Duration step = Duration::fromNanoseconds(
714 simulation_.maxStep.isZero() ? remaining : std::min(remaining, simulation_.maxStep.nanoseconds()));
715 const double dtSeconds = step.seconds();
716 const double ageSeconds = candidate.state.age.seconds();
717 for (const auto& op : live->recipe.motionOps) {
718 switch (op.kind) {
720 auto predicted = *targetPos;
721 if (candidate.state.previousTargetPosition) {
722 const double speed = length(motion.velocity);
723 const double horizon =
724 speed > 1e-12 ? std::min(op.predictionSeconds,
725 length(directionTo(motion.position, *targetPos)) / speed)
726 : 0.0;
727 predicted.x += targetVelocity.x * horizon;
728 predicted.y += targetVelocity.y * horizon;
729 predicted.z += targetVelocity.z * horizon;
730 }
731 const auto desired = directionTo(motion.position, predicted);
732 if (length(desired) > 1e-12)
733 motion.velocity =
734 steer(motion.velocity, desired, op.maxTurnRateDegrees * kPi / 180.0 * dtSeconds);
735 break;
736 }
738 const auto desired = directionTo(motion.position, *targetPos);
739 if (length(desired) <= 1e-12) break;
740 const double maxRadians = op.maxTurnRateDegrees * kPi / 180.0 * dtSeconds;
741 motion.velocity = steer(motion.velocity, desired, maxRadians);
742 break;
743 }
745 ecs::EntityHandle targetHandle{};
746 if (candidate.state.target.has_value()) targetHandle = *candidate.state.target;
747 auto samples = bodies->sample(candidate.state.handle, targetHandle, motion);
748 if (!samples) return Result<CarrierFrame>::failure(samples.status());
749 ProjectileVector avoid{0.0, 0.0, 0.0};
750 bool any = false;
751 const auto fwd = length(motion.velocity) > 1e-12 ? normalized(motion.velocity)
752 : ProjectileVector{1.0, 0.0, 0.0};
753 for (const auto& body : samples.value()) {
754 if (!std::isfinite(body.radius) || body.radius < 0.0) {
757 "Body defense radius must be finite and non-negative", "bodies"));
758 }
759 const auto toCenter = directionTo(motion.position, body.center);
760 const double dist = length(toCenter);
761 const double blockAt = body.radius + op.avoidRadiusPadding + op.avoidLookAhead;
762 if (dist <= 1e-12 || dist > blockAt) continue;
763 if (length(body.facing) > 1e-12 && body.frontConeDegrees < 180.0) {
764 const auto approach =
765 normalized(ProjectileVector{-toCenter.x, -toCenter.y, -toCenter.z});
766 const auto face = normalized(body.facing);
767 const double dot = std::clamp(
768 approach.x * face.x + approach.y * face.y + approach.z * face.z, -1.0, 1.0);
769 const double angleDeg = std::acos(dot) * 180.0 / kPi;
770 if (angleDeg > body.frontConeDegrees) continue;
771 }
772 auto lateral = cross(fwd, toCenter);
773 if (length(lateral) <= 1e-12) lateral = lateralBasis(fwd);
774 lateral = normalized(lateral);
775 if (targetPos.has_value()) {
776 const auto around = directionTo(body.center, *targetPos);
777 const auto left = lateral;
778 const auto right = ProjectileVector{-lateral.x, -lateral.y, -lateral.z};
779 const double leftScore = left.x * around.x + left.y * around.y + left.z * around.z;
780 const double rightScore = right.x * around.x + right.y * around.y + right.z * around.z;
781 if (rightScore > leftScore) lateral = right;
782 }
783 const double weight = op.avoidStrength * (1.0 - dist / blockAt);
784 avoid.x += lateral.x * weight;
785 avoid.y += lateral.y * weight;
786 avoid.z += lateral.z * weight;
787 any = true;
788 }
789 if (any && length(avoid) > 1e-12) {
790 const auto desired = ProjectileVector{fwd.x + avoid.x, fwd.y + avoid.y, fwd.z + avoid.z};
791 const double maxRadians = op.maxTurnRateDegrees * kPi / 180.0 * dtSeconds;
792 motion.velocity = steer(motion.velocity, desired, maxRadians);
793 }
794 break;
795 }
797 motion.velocity =
798 rotateAroundAxis(motion.velocity, op.axis, op.angularRateDegrees * kPi / 180.0 * dtSeconds);
799 break;
801 const auto axis = normalized(op.axis);
802 auto radial = directionTo(*targetPos, motion.position);
803 const double height = radial.x * axis.x + radial.y * axis.y + radial.z * axis.z;
804 radial = {radial.x - height * axis.x, radial.y - height * axis.y, radial.z - height * axis.z};
805 const double radius = length(radial);
806 radial = radius > 1e-12 ? normalized(radial) : lateralBasis(axis);
807 const auto tangent = cross(axis, radial);
808 const double angular = op.angularRateDegrees * kPi / 180.0;
809 const double correction = (op.orbitRadius - radius) / op.orbitRadius;
810 const auto desired = ProjectileVector{tangent.x * angular + radial.x * correction,
811 tangent.y * angular + radial.y * correction,
812 tangent.z * angular + radial.z * correction};
813 if (length(desired) > 1e-12)
814 motion.velocity =
815 steer(motion.velocity, desired, op.maxTurnRateDegrees * kPi / 180.0 * dtSeconds);
816 break;
817 }
819 const double factor = std::exp(-op.drag * dtSeconds);
820 motion.velocity = {motion.velocity.x * factor, motion.velocity.y * factor,
821 motion.velocity.z * factor};
822 break;
823 }
825 const double speed = length(motion.velocity);
826 const auto dir = speed > 1e-12 ? normalized(motion.velocity) : candidate.state.heading;
827 const double next = std::max(
828 0.0, live->recipe.speed + op.curveAmplitude * std::sin(2.0 * kPi * op.curveFrequencyHz *
829 (ageSeconds + dtSeconds)));
830 motion.velocity = {dir.x * next, dir.y * next, dir.z * next};
831 break;
832 }
834 // Absolute-age hashed samples: replay needs no global random state.
835 const double phase = ageSeconds * op.curveFrequencyHz;
836 if (!std::isfinite(phase) || phase > 4294967294.0)
839 "Wander sample index exceeds supported range", "motion"));
840 const auto index = static_cast<std::uint32_t>(phase);
841 const double blend = (phase - index) * (phase - index) * (3.0 - 2.0 * (phase - index));
842 auto sample = [&](std::uint32_t tick, std::uint32_t channel) {
843 return randomSample(static_cast<std::uint32_t>(op.randomSeed), candidate.state.handle, tick,
844 channel) *
845 2.0 -
846 1.0;
847 };
848 auto smooth = [&](std::uint32_t channel) {
849 const double first = sample(index, channel);
850 return first + (sample(index + 1, channel) - first) * blend;
851 };
852 const double speed = length(motion.velocity);
853 if (speed <= 1e-12) break;
854 const auto fwd = normalized(motion.velocity);
855 const auto side = lateralBasis(fwd);
856 const auto up = cross(side, fwd);
857 const double lateral = smooth(0x12345678U) * op.curveAmplitude;
858 const double vertical = smooth(0xabcdef01U) * op.curveAmplitude;
859 const ProjectileVector desired{fwd.x + side.x * lateral + up.x * vertical,
860 fwd.y + side.y * lateral + up.y * vertical,
861 fwd.z + side.z * lateral + up.z * vertical};
862 motion.velocity =
863 steer(motion.velocity, desired, op.maxTurnRateDegrees * kPi / 180.0 * dtSeconds);
864 break;
865 }
866 case CarrierMotionOpKind::ApplyGravity: motion.velocity.y -= op.gravity * dtSeconds; break;
868 const double speed = length(motion.velocity);
869 const auto dir = speed > 1e-12 ? normalized(motion.velocity) : candidate.state.heading;
870 const double next = std::max(0.0, speed + op.acceleration * dtSeconds);
871 motion.velocity = {dir.x * next, dir.y * next, dir.z * next};
872 break;
873 }
876 const ProjectileVector base{motion.velocity.x - curveVelocity.x,
877 motion.velocity.y - curveVelocity.y,
878 motion.velocity.z - curveVelocity.z};
879 if (length(base) <= 1e-12) break;
880 const auto fwd = normalized(base);
881 const auto side = lateralBasis(fwd);
882 const auto up = normalized(cross(side, fwd));
883 const double omega = 2.0 * kPi * op.curveFrequencyHz;
884 const double before = omega * ageSeconds;
885 const double after = omega * (ageSeconds + dtSeconds);
886 const double lateral = op.curveAmplitude * (std::sin(after) - std::sin(before)) / dtSeconds;
887 const double vertical =
889 ? op.curveAmplitude * (std::cos(before) - std::cos(after)) / dtSeconds
890 : 0.0;
891 const ProjectileVector modifier{side.x * lateral + up.x * vertical,
892 side.y * lateral + up.y * vertical,
893 side.z * lateral + up.z * vertical};
894 motion.velocity = {motion.velocity.x + modifier.x, motion.velocity.y + modifier.y,
895 motion.velocity.z + modifier.z};
896 curveVelocity = {curveVelocity.x + modifier.x, curveVelocity.y + modifier.y,
897 curveVelocity.z + modifier.z};
898 break;
899 }
901 candidate.state.distanceTravelled += length(motion.velocity) * dtSeconds;
902 motion.position.x += motion.velocity.x * dtSeconds;
903 motion.position.y += motion.velocity.y * dtSeconds;
904 motion.position.z += motion.velocity.z * dtSeconds;
905 break;
906 }
907 }
908
909 if (customMotion != nullptr) {
910 const auto& before = segmentStart;
911 auto custom = [&]() -> Result<CarrierMotion> {
912 try {
913 return customMotion->evaluate(before, motion, step);
914 } catch (const std::exception& error) {
916 Diagnostic::error(DiagnosticCode::Failed, error.what(), "motionFunction"));
917 } catch (...) {
919 DiagnosticCode::Failed, "Custom motion function threw", "motionFunction"));
920 }
921 }();
922 if (!custom) return Result<CarrierFrame>::failure(custom.status());
923 const auto& output = custom.value();
924 const bool changed = output.position.x != motion.position.x || output.position.y != motion.position.y ||
925 output.position.z != motion.position.z || output.velocity.x != motion.velocity.x ||
926 output.velocity.y != motion.velocity.y || output.velocity.z != motion.velocity.z;
927 if (changed) {
928 candidate.state.distanceTravelled =
929 before.distanceTravelled + length(directionTo(previous.position, output.position));
930 curveVelocity = {};
931 motion = output;
932 }
933 }
934
935 if (!finite(motion.position) || !finite(motion.velocity) || !std::isfinite(length(motion.velocity)) ||
936 !std::isfinite(candidate.state.distanceTravelled))
938 Diagnostic::error(DiagnosticCode::Failed, "Carrier motion produced non-finite values", "motion"));
939
940 auto nextAge = previousAge.tryAdd(step);
941 if (!nextAge) return Result<CarrierFrame>::failure(nextAge.status());
942
943 candidate.state.curveVelocity = curveVelocity;
944 const ProjectileVector baseVelocity{motion.velocity.x - curveVelocity.x,
945 motion.velocity.y - curveVelocity.y,
946 motion.velocity.z - curveVelocity.z};
947 if (length(baseVelocity) > 1e-12) candidate.state.heading = normalized(baseVelocity);
948 candidate.state.motion = motion;
949 candidate.state.age = std::move(nextAge).takeValue();
950
951 std::vector<TriggerFire> fires;
952 for (const auto& trigger : live->recipe.triggers) {
953 switch (trigger.kind) {
955 if (crossed(previousAge, candidate.state.age, candidate.state.lifetime) ||
956 candidate.state.age >= candidate.state.lifetime)
957 fires.push_back({CarrierTriggerKind::OnExpire, std::nullopt, candidate.state.lifetime});
958 break;
960 if (crossed(previousAge, candidate.state.age, trigger.fuse))
961 fires.push_back({CarrierTriggerKind::OnFuse, std::nullopt, trigger.fuse});
962 break;
964 const auto before = intervalIndex(previousAge, trigger.interval);
965 const auto after = intervalIndex(candidate.state.age, trigger.interval);
966 if (after - before > simulation_.maxTriggerFirings)
969 "Interval trigger exceeds the configured firing budget; use smaller steps",
970 "interval"));
971 for (auto i = before; i < after; ++i)
972 fires.push_back({CarrierTriggerKind::OnInterval, std::nullopt,
973 Duration::fromNanoseconds((i + 1) * trigger.interval.nanoseconds())});
974 break;
975 }
977 if (!live->recipe.collisionEnabled) break;
978 const auto* probe = live->recipe.physicsWorldSweep ? worldSweep : hits;
979 auto contacts = probe->query(candidate.state.handle, previous, motion);
980 if (!contacts) return Result<CarrierFrame>::failure(contacts.status());
981 auto& ordered = contacts.value();
982 const auto displacement = directionTo(previous.position, motion.position);
983 const double segmentLength = length(displacement);
984 for (auto& contact : ordered) {
985 if (contact.worldContact &&
986 ((contact.worldContact->identity.world >> 32) == 0 ||
987 (contact.worldContact->identity.body >> 32) == 0 ||
988 (contact.worldContact->identity.world & 0xffffffffu) == 0xffffffffu ||
989 (contact.worldContact->identity.body & 0xffffffffu) == 0xffffffffu))
992 "Invalid physics contact identity", "hits.worldContact"));
993 if (!finite(contact.point) || !finite(contact.normal) ||
994 !std::isfinite(length(contact.normal)) || length(contact.normal) <= 1e-12)
997 "Contact requires finite point and nonzero normal", "hits"));
998 if (!contact.fraction) {
999 const auto direction =
1000 segmentLength > 1e-12 ? normalized(displacement) : ProjectileVector{};
1001 const auto offset = directionTo(previous.position, contact.point);
1002 contact.fraction = segmentLength > 1e-12
1003 ? std::clamp((offset.x * direction.x + offset.y * direction.y +
1004 offset.z * direction.z) /
1005 segmentLength,
1006 0.0, 1.0)
1007 : 0.0;
1008 }
1009 if (!std::isfinite(*contact.fraction) || *contact.fraction < 0.0 || *contact.fraction > 1.0)
1012 "Contact fraction must be finite and in [0,1]", "hits.fraction"));
1013 }
1014 std::stable_sort(ordered.begin(), ordered.end(),
1015 [](const auto& a, const auto& b) { return *a.fraction < *b.fraction; });
1016 for (auto& contact : ordered) {
1017 if (contact.worldContact &&
1018 std::find(candidate.state.piercedWorldBodies.begin(),
1019 candidate.state.piercedWorldBodies.end(),
1020 contact.worldContact->identity) != candidate.state.piercedWorldBodies.end())
1021 continue;
1022 if (contact.target.id != 0 &&
1023 std::find_if(candidate.state.piercedTargets.begin(),
1024 candidate.state.piercedTargets.end(), [&](const auto& target) {
1025 return sameTarget(target, contact.target);
1026 }) != candidate.state.piercedTargets.end())
1027 continue;
1028 const double fraction = *contact.fraction;
1029 // A contact at the start while moving away must not consume another bounce.
1030 if (fraction <= 1e-12 && displacement.x * contact.normal.x +
1031 displacement.y * contact.normal.y +
1032 displacement.z * contact.normal.z >=
1033 0.0)
1034 continue;
1035 auto offset = step.scaled(fraction);
1036 if (!offset) return Result<CarrierFrame>::failure(offset.status());
1037 auto at = previousAge.tryAdd(offset.value());
1038 if (!at) return Result<CarrierFrame>::failure(at.status());
1039 fires.push_back({CarrierTriggerKind::OnHit, std::move(contact), at.value()});
1040 }
1041 break;
1042 }
1044 const double before = previousDistance;
1045 if (before < trigger.threshold && candidate.state.distanceTravelled >= trigger.threshold) {
1046 const double fraction =
1047 (trigger.threshold - before) / (candidate.state.distanceTravelled - before);
1048 auto offset = step.scaled(std::clamp(fraction, 0.0, 1.0));
1049 if (!offset) return Result<CarrierFrame>::failure(offset.status());
1050 auto at = previousAge.tryAdd(offset.value());
1051 if (!at) return Result<CarrierFrame>::failure(at.status());
1052 fires.push_back({trigger.kind, std::nullopt, at.value()});
1053 }
1054 break;
1055 }
1058 const double before = trigger.kind == CarrierTriggerKind::OnApex ? previous.velocity.y
1059 : length(previous.velocity);
1060 const double after =
1061 trigger.kind == CarrierTriggerKind::OnApex ? motion.velocity.y : length(motion.velocity);
1062 const double threshold = trigger.kind == CarrierTriggerKind::OnApex ? 0.0 : trigger.threshold;
1063 if (before > threshold && after <= threshold) {
1064 auto offset = step.scaled(std::clamp((before - threshold) / (before - after), 0.0, 1.0));
1065 if (!offset) return Result<CarrierFrame>::failure(offset.status());
1066 auto at = previousAge.tryAdd(offset.value());
1067 if (!at) return Result<CarrierFrame>::failure(at.status());
1068 fires.push_back({trigger.kind, std::nullopt, at.value()});
1069 }
1070 break;
1071 }
1073 const auto deltaPos = directionTo(motion.position, *targetPos);
1074 const double dist = length(deltaPos);
1075 if (dist <= trigger.proximityRadius)
1076 fires.push_back({CarrierTriggerKind::OnProximity, std::nullopt, candidate.state.age});
1077 break;
1078 }
1079 }
1080 }
1081
1082 std::stable_sort(fires.begin(), fires.end(), [](const TriggerFire& a, const TriggerFire& b) {
1083 if (a.at != b.at) return a.at < b.at;
1084 return a.kind != CarrierTriggerKind::OnExpire && b.kind == CarrierTriggerKind::OnExpire;
1085 });
1086 std::optional<Duration> bouncedAt;
1087 for (std::size_t fireIndex = 0; fireIndex < fires.size(); ++fireIndex) {
1088 const auto fire = fires[fireIndex];
1089 if (bouncedAt && fire.at > *bouncedAt) break;
1090 if (fire.contact && fire.contact->worldContact &&
1091 std::find(candidate.state.piercedWorldBodies.begin(), candidate.state.piercedWorldBodies.end(),
1092 fire.contact->worldContact->identity) != candidate.state.piercedWorldBodies.end())
1093 continue;
1094 if (fire.contact && fire.contact->target.id != 0 &&
1095 std::find_if(candidate.state.piercedTargets.begin(), candidate.state.piercedTargets.end(),
1096 [&](const auto& target) { return sameTarget(target, fire.contact->target); }) !=
1097 candidate.state.piercedTargets.end())
1098 continue;
1099 if (bouncedAt && fire.contact &&
1100 candidate.state.motion.velocity.x * fire.contact->normal.x +
1101 candidate.state.motion.velocity.y * fire.contact->normal.y +
1102 candidate.state.motion.velocity.z * fire.contact->normal.z >=
1103 0.0)
1104 continue;
1105 if (++triggerFirings > simulation_.maxTriggerFirings)
1107 Diagnostic::error(DiagnosticCode::Conflict, "Carrier trigger budget exhausted", "simulation"));
1108 if (fire.kind == CarrierTriggerKind::OnHit && ++collisions > simulation_.maxCollisions)
1110 DiagnosticCode::Conflict, "Carrier collision budget exhausted", "simulation"));
1111 bool suppressRelease = false;
1112 bool requestRelease = false;
1113 const double fraction =
1114 std::clamp(static_cast<double>(fire.at.nanoseconds() - previousAge.nanoseconds()) /
1115 static_cast<double>(step.nanoseconds()),
1116 0.0, 1.0);
1117 const ProjectilePoint eventPosition =
1118 fire.contact
1119 ? fire.contact->point
1120 : ProjectilePoint{previous.position.x + (motion.position.x - previous.position.x) * fraction,
1121 previous.position.y + (motion.position.y - previous.position.y) * fraction,
1122 previous.position.z + (motion.position.z - previous.position.z) * fraction};
1123
1124 for (const auto& impact : live->recipe.impacts) {
1125 if (impact.on != fire.kind) continue;
1126
1127 CarrierEvent event;
1128 event.age = fire.at;
1129 event.carrier = candidate.state.handle;
1130 event.recipeId = candidate.state.recipeId;
1131 event.trigger = fire.kind;
1132 event.impact = impact.kind;
1133 event.position = eventPosition;
1134 event.source = candidate.state.source;
1135 if (fire.contact.has_value()) {
1136 event.worldContact = fire.contact->worldContact;
1137 event.target = fire.contact->target;
1138 event.normal = fire.contact->normal;
1139 event.position = fire.contact->point;
1140 } else if (candidate.state.target.has_value()) {
1141 event.target = *candidate.state.target;
1142 }
1143
1144 switch (impact.kind) {
1145 case CarrierImpactKind::EmitTrigger: events.push_back(std::move(event)); break;
1147 event.damage = impact.damage;
1148 event.damageType = impact.damageType;
1149 event.element = impact.element;
1150 events.push_back(std::move(event));
1151 break;
1153 event.damage = impact.damage;
1154 event.splashRadius = impact.splashRadius;
1155 event.damageType = impact.damageType;
1156 event.element = impact.element;
1157 event.position = eventPosition;
1158 events.push_back(std::move(event));
1159 break;
1161 if (candidate.state.pierceRemaining > 0) {
1162 if (fire.contact && fire.contact->worldContact) {
1163 if (candidate.state.piercedWorldBodies.size() >= 65536)
1165 DiagnosticCode::Conflict, "Pierced world body budget exhausted", "hits"));
1166 candidate.state.piercedWorldBodies.push_back(fire.contact->worldContact->identity);
1167 }
1168 if (fire.contact && fire.contact->target.id != 0) {
1169 if (candidate.state.piercedTargets.size() >= 65536)
1172 "Carrier pierced-target budget exhausted", "hits"));
1173 candidate.state.piercedTargets.push_back(fire.contact->target);
1174 }
1175 --candidate.state.pierceRemaining;
1176 suppressRelease = true;
1177 }
1178 break;
1180 if (candidate.state.bounceRemaining > 0 && fire.contact.has_value()) {
1181 if (!finite(fire.contact->point) || !finite(fire.contact->normal) ||
1182 length(fire.contact->normal) <= 1e-12)
1185 "Bounce requires finite contact point and nonzero normal", "hits"));
1186 --candidate.state.bounceRemaining;
1187 candidate.state.motion.position = fire.contact->point;
1188 candidate.state.distanceTravelled =
1189 previousDistance + length(directionTo(previous.position, fire.contact->point));
1190 const auto impactVelocity =
1191 bouncedAt
1192 ? candidate.state.motion.velocity
1193 : ProjectileVector{previous.velocity.x +
1194 (motion.velocity.x - previous.velocity.x) * fraction,
1195 previous.velocity.y +
1196 (motion.velocity.y - previous.velocity.y) * fraction,
1197 previous.velocity.z +
1198 (motion.velocity.z - previous.velocity.z) * fraction};
1199 auto reflected = reflect(impactVelocity, fire.contact->normal);
1200 const auto normal = normalized(fire.contact->normal);
1201 const double normalSpeed =
1202 reflected.x * normal.x + reflected.y * normal.y + reflected.z * normal.z;
1203 const double retained = 1.0 - impact.bounceFriction;
1204 reflected = {
1205 (normal.x * normalSpeed + (reflected.x - normal.x * normalSpeed) * retained) *
1206 impact.restitution,
1207 (normal.y * normalSpeed + (reflected.y - normal.y * normalSpeed) * retained) *
1208 impact.restitution,
1209 (normal.z * normalSpeed + (reflected.z - normal.z * normalSpeed) * retained) *
1210 impact.restitution};
1211 const double speed = length(reflected);
1212 if (impact.bounceSpreadDegrees > 0.0 && speed > 1e-12 && std::isfinite(speed)) {
1213 const auto forward = normalized(reflected);
1214 const auto side = lateralBasis(forward);
1215 const auto up = cross(side, forward);
1216 const auto seed = static_cast<std::uint32_t>(impact.randomSeed);
1217 const auto tick = static_cast<std::uint32_t>(candidate.state.bounceRemaining);
1218 const double cosine =
1219 1.0 - randomSample(seed, candidate.state.handle, tick, 0xb01U) *
1220 (1.0 - std::cos(impact.bounceSpreadDegrees * kPi / 180.0));
1221 const double sine = std::sqrt(std::max(0.0, 1.0 - cosine * cosine));
1222 const double azimuth =
1223 2.0 * kPi * randomSample(seed, candidate.state.handle, tick, 0xb02U);
1224 const double a = sine * std::cos(azimuth), b = sine * std::sin(azimuth);
1225 reflected = {(forward.x * cosine + side.x * a + up.x * b) * speed,
1226 (forward.y * cosine + side.y * a + up.y * b) * speed,
1227 (forward.z * cosine + side.z * a + up.z * b) * speed};
1228 if (reflected.x * normal.x + reflected.y * normal.y + reflected.z * normal.z < 0.0)
1229 reflected = reflect(reflected, normal);
1230 }
1231 if (!finite(reflected) || !std::isfinite(length(reflected)))
1234 "Bounce restitution overflowed velocity", "restitution"));
1235 for (const auto& trigger : live->recipe.triggers) {
1236 const bool speedCrossed = trigger.kind == CarrierTriggerKind::OnSpeedBelow &&
1237 length(impactVelocity) > trigger.threshold &&
1238 speed <= trigger.threshold;
1239 const bool apexCrossed = trigger.kind == CarrierTriggerKind::OnApex &&
1240 impactVelocity.y > 0.0 && reflected.y <= 0.0;
1241 if (speedCrossed || apexCrossed)
1242 fires.insert(fires.begin() + static_cast<std::ptrdiff_t>(fireIndex + 1),
1243 {trigger.kind, std::nullopt, fire.at});
1244 }
1245 candidate.state.motion.velocity = reflected;
1246 if (length(reflected) > 1e-12) candidate.state.heading = normalized(reflected);
1247 candidate.state.curveVelocity = {};
1248 bouncedAt = fire.at;
1249 suppressRelease = true;
1250 }
1251 break;
1252 case CarrierImpactKind::Release: requestRelease = true; break;
1254 CarrierChildSpawn child;
1255 child.recipeId = impact.childRecipeId;
1256 child.parent = candidate.state.handle;
1257 child.request.position = eventPosition;
1258 child.request.direction =
1259 bouncedAt
1260 ? candidate.state.motion.velocity
1261 : ProjectileVector{
1262 previous.velocity.x + (motion.velocity.x - previous.velocity.x) * fraction,
1263 previous.velocity.y + (motion.velocity.y - previous.velocity.y) * fraction,
1264 previous.velocity.z + (motion.velocity.z - previous.velocity.z) * fraction};
1265 if (length(child.request.direction) <= 1e-12) child.request.direction = {1.0, 0.0, 0.0};
1266 child.request.target = candidate.state.target;
1267 child.request.source = candidate.state.source;
1268 childSpawns.push_back(std::move(child));
1269 break;
1270 }
1271 }
1272 }
1273
1274 if (requestRelease && !suppressRelease) {
1275 candidate.release = true;
1276 break;
1277 }
1278 }
1279
1280 if (bouncedAt) {
1281 const auto consumed = bouncedAt->nanoseconds() - previousAge.nanoseconds();
1282 candidate.state.age = *bouncedAt;
1283 remaining -= consumed;
1284 } else {
1285 remaining -= step.nanoseconds();
1286 }
1287 if (candidate.state.age >= candidate.state.lifetime) candidate.release = true;
1288 } // all segments for this carrier
1289 candidate.state.previousTargetPosition = targetPos;
1290 candidate.state.previousTargetSampleAge = sampleAge;
1291 }
1292
1293 std::vector<Slot> staged = slots_;
1294 std::size_t stagedActive = activeCount_;
1295 for (const auto& candidate : candidates) {
1296 auto& cell = staged[candidate.state.handle.slot];
1297 if (cell.generation != candidate.state.handle.generation || !cell.state.has_value())
1299 Diagnostic::error(DiagnosticCode::StaleHandle, "Carrier handle became stale", "handle"));
1300 if (candidate.release) {
1301 cell.state.reset();
1302 --stagedActive;
1303 } else {
1304 cell.state = candidate.state;
1305 }
1306 }
1307
1308 std::vector<CarrierHandle> spawnedChildren;
1309 spawnedChildren.reserve(childSpawns.size());
1310 for (const auto& child : childSpawns) {
1311 const LiveRecipe* childLive = lookupLive(child.recipeId);
1312 if (childLive == nullptr)
1314 DiagnosticCode::NotFound, "Child spawn references an unregistered recipe", "childRecipeId"));
1315 auto valid = validateSpawn(childLive->recipe, child.request);
1316 if (!valid) return Result<CarrierFrame>::failure(valid.status());
1317
1318 bool placed = false;
1319 for (std::uint32_t slot = 0; slot < staged.size(); ++slot) {
1320 if (staged[slot].state.has_value()) continue;
1321 Slot& cell = staged[slot];
1322 ++cell.generation;
1323 if (cell.generation == 0) ++cell.generation;
1324 CarrierState state;
1325 state.handle = {slot, cell.generation};
1326 state.recipeId = childLive->recipe.id;
1327 state.lifetime = childLive->recipe.lifetime;
1328 state.age = Duration::zero();
1329 state.pierceRemaining = childLive->initialPierce;
1330 state.bounceRemaining = childLive->initialBounce;
1331 state.target = child.request.target;
1332 state.source = child.request.source;
1333 const auto dir = normalized(child.request.direction);
1334 state.heading = dir;
1335 state.motion.position = child.request.position;
1336 state.motion.velocity = {dir.x * childLive->recipe.speed, dir.y * childLive->recipe.speed,
1337 dir.z * childLive->recipe.speed};
1338 cell.state = std::move(state);
1339 ++stagedActive;
1340 spawnedChildren.push_back(cell.state->handle);
1341 placed = true;
1342 break;
1343 }
1344 if (!placed)
1346 DiagnosticCode::Conflict, "Carrier pool cannot fit deferred child spawns", "capacity"));
1347 }
1348
1349 slots_ = std::move(staged);
1350 activeCount_ = stagedActive;
1351
1352 CarrierFrame frame;
1353 for (const auto& candidate : candidates) {
1354 frame.advanced.push_back(candidate.state.handle);
1355 if (candidate.release) frame.released.push_back(candidate.state.handle);
1356 }
1357 for (const auto& child : spawnedChildren) frame.advanced.push_back(child);
1358 frame.events = std::move(events);
1359 frame.childSpawns = std::move(childSpawns);
1360 return Result<CarrierFrame>::success(std::move(frame));
1361}
1362
1363Result<void> CombatCarrierRuntime::release(CarrierHandle handle) {
1364 if (updating_)
1365 return Result<void>::failure(
1366 Diagnostic::error(DiagnosticCode::Conflict, "Reentrant carrier mutation is forbidden", "runtime"));
1367 if (handle.slot >= slots_.size())
1368 return Result<void>::failure(Diagnostic::error(DiagnosticCode::StaleHandle, "Carrier handle slot is out of range", "handle"));
1369 Slot& cell = slots_[handle.slot];
1370 if (!cell.state.has_value() || cell.generation != handle.generation)
1371 return Result<void>::failure(Diagnostic::error(DiagnosticCode::StaleHandle, "Carrier handle is stale", "handle"));
1372 cell.state.reset();
1373 --activeCount_;
1374 return Result<void>::success();
1375}
1376
1377std::optional<CarrierState> CombatCarrierRuntime::find(CarrierHandle handle) const {
1378 if (handle.slot >= slots_.size()) return std::nullopt;
1379 const Slot& cell = slots_[handle.slot];
1380 if (!cell.state.has_value() || cell.generation != handle.generation) return std::nullopt;
1381 return cell.state;
1382}
1383
1384std::vector<CarrierState> CombatCarrierRuntime::states() const {
1385 std::vector<CarrierState> result;
1386 result.reserve(activeCount_);
1387 for (const auto& slot : slots_) {
1388 if (slot.state.has_value()) result.push_back(*slot.state);
1389 }
1390 return result;
1391}
1392
1393CarrierRuntimeSnapshot CombatCarrierRuntime::snapshot() const {
1395 snap.simulation = simulation_;
1396 for (const auto& live : recipes_) snap.recipes.push_back(live.recipe);
1397 snap.slots.reserve(slots_.size());
1398 for (const auto& slot : slots_) snap.slots.push_back({slot.generation, slot.state});
1399 return snap;
1400}
1401
1402Result<void> CombatCarrierRuntime::restore(const CarrierRuntimeSnapshot& snapshot) {
1403 if (updating_)
1404 return Result<void>::failure(
1405 Diagnostic::error(DiagnosticCode::Conflict, "Reentrant carrier mutation is forbidden", "runtime"));
1406 if (snapshot.schemaVersion != 4)
1408 DiagnosticCode::Unsupported, "Unsupported carrier snapshot schema; migrate to version 4 before restoring",
1409 "schemaVersion"));
1410 auto simulationValid = snapshot.simulation.validate();
1411 if (!simulationValid) return simulationValid;
1412 if (snapshot.slots.empty() || snapshot.slots.size() > kMaximumCapacity)
1413 return Result<void>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument, "Carrier snapshot capacity must be in 1..1048576", "slots"));
1414
1415 std::vector<Slot> staged;
1416 staged.reserve(snapshot.slots.size());
1417 std::size_t active = 0;
1418 for (const auto& slot : snapshot.slots) {
1419 if (slot.state.has_value()) {
1420 if (slot.state->handle.slot != staged.size() || slot.generation == 0 ||
1421 slot.state->handle.generation != slot.generation || !finite(slot.state->motion.position) ||
1422 !finite(slot.state->motion.velocity) || !std::isfinite(length(slot.state->motion.velocity)) ||
1423 !finite(slot.state->curveVelocity) || !finite(slot.state->heading) ||
1424 std::abs(length(slot.state->heading) - 1.0) > 1e-6 ||
1425 (slot.state->previousTargetPosition && !finite(*slot.state->previousTargetPosition)) ||
1426 slot.state->previousTargetSampleAge < Duration::zero() ||
1427 slot.state->previousTargetSampleAge > slot.state->age ||
1428 !std::isfinite(slot.state->distanceTravelled) || slot.state->distanceTravelled < 0.0 ||
1429 slot.state->age < Duration::zero() || slot.state->lifetime <= slot.state->age ||
1430 slot.state->pierceRemaining < 0 || slot.state->bounceRemaining < 0)
1431 return Result<void>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument, "Carrier snapshot state handle does not match slot metadata", "slots"));
1432 if (slot.state->piercedTargets.size() > 65536)
1434 DiagnosticCode::InvalidArgument, "Too many pierced targets in snapshot", "slots.piercedTargets"));
1435 auto worldBodies = slot.state->piercedWorldBodies;
1436 if (worldBodies.size() > 65536)
1438 DiagnosticCode::InvalidArgument, "Too many pierced physics bodies", "slots.piercedWorldBodies"));
1439 std::sort(worldBodies.begin(), worldBodies.end(), [](const auto& a, const auto& b) {
1440 return a.world < b.world || (a.world == b.world && a.body < b.body);
1441 });
1442 if (std::any_of(worldBodies.begin(), worldBodies.end(),
1443 [](const auto& id) {
1444 return (id.world >> 32) == 0 || (id.body >> 32) == 0 ||
1445 (id.world & 0xffffffffu) == 0xffffffffu ||
1446 (id.body & 0xffffffffu) == 0xffffffffu;
1447 }) ||
1448 std::adjacent_find(worldBodies.begin(), worldBodies.end()) != worldBodies.end())
1450 "Invalid or duplicate pierced physics identity",
1451 "slots.piercedWorldBodies"));
1452 auto pierced = slot.state->piercedTargets;
1453 std::sort(pierced.begin(), pierced.end(), [](const auto& a, const auto& b) {
1454 if (a.table != b.table) return std::less<ecs::Table*>{}(a.table, b.table);
1455 if (a.type != b.type) return a.type < b.type;
1456 return a.id < b.id || (a.id == b.id && a.generation < b.generation);
1457 });
1458 if (std::any_of(pierced.begin(), pierced.end(), [](const auto& target) { return target.id == 0; }) ||
1459 std::adjacent_find(pierced.begin(), pierced.end(), sameTarget) != pierced.end())
1461 "Invalid or duplicate pierced target in snapshot",
1462 "slots.piercedTargets"));
1463 const auto registered = findRecipe(slot.state->recipeId);
1464 if (!registered)
1466 DiagnosticCode::NotFound, "Carrier snapshot references an unregistered recipe", "recipeId"));
1467 const auto context =
1468 std::find_if(snapshot.recipes.begin(), snapshot.recipes.end(),
1469 [&](const CarrierRecipe& recipe) { return recipe.id == slot.state->recipeId; });
1470 if (context == snapshot.recipes.end() || *context != *registered)
1472 DiagnosticCode::Conflict, "Carrier snapshot recipe context differs from the runtime", "recipes"));
1473 CarrierSpawnRequest request{slot.state->motion.position, slot.state->heading, slot.state->target,
1474 slot.state->source};
1475 auto valid = validateSpawn(*registered, request);
1476 if (!valid) return valid;
1477 if (slot.state->lifetime != registered->lifetime)
1479 DiagnosticCode::InvalidArgument, "Carrier snapshot lifetime differs from its recipe", "lifetime"));
1480 ++active;
1481 }
1482 staged.push_back({slot.generation, slot.state});
1483 }
1484 simulation_ = snapshot.simulation;
1485 slots_ = std::move(staged);
1486 activeCount_ = active;
1487 return Result<void>::success();
1488}
1489
1490} // namespace eve::weapon
LogicalId target
bool & active
double lateral
std::string output
std::vector< std::unique_ptr< ScriptClimbingEventSink > > live
Composable combat-carrier runtime: motion ops, triggers, and impacts.
bool changed
b3Vec3 angular
Stable, structured diagnostics shared by engine modules.
std::vector< FieldTarget > targets
const GltfImportRequest & request
std::uint32_t spawned
std::uint32_t capacity
HexVec3 up
HexVec3 left
HexVec3 right
std::int32_t first
float blend
std::uint32_t height
float length
JointPoint2D axis
bool ordered
size_t offset
std::string to
std::string from
std::string id
Poco::JSON::Object::Ptr result
Snapshot snapshot
bool valid
MeleePoint3 b
Definition MeleeHit.cpp:41
double radius
Definition MeleeHit.cpp:42
MeleePoint3 a
Definition MeleeHit.cpp:40
Texture * normal
OceanWakeSettings settings
ssq::Object frame
glm::dvec3 displacement
glm::dvec3 velocity
std::shared_ptr< const OceanSprayFrame > previous
size_t directions
bool finite
std::string error
Definition Package.cpp:174
std::vector< particles::ParticleRecordEvent > events
BakeRecipe recipe
std::string path
Definition PlayHost.cpp:111
PrimitiveHandle handle
std::string body
Object::Ptr value
float t
std::string slot
RoadNetwork resolved
RoadLaneDirection direction
std::string kind
std::map< std::array< int, 4 >, std::vector< const Subject * > > candidates
Definition Sensing.cpp:32
double current
std::optional< CarrierVolleySpec > volley
float phase
Cell cell
bool placed
SimulationTick tick
Heightmap curve
int iterations
Definition TreeMesh.cpp:448
uint32_t seed
Definition TreeMesh.cpp:276
float step
Definition TreeMesh.cpp:451
V3 heading
Definition TreeMesh.cpp:429
V3 dir
Definition TreeMesh.cpp:151
std::size_t at
double weight
uint32_t index
const VegetationPresetContext & context
float fraction
Contact contact
V forward
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Signed, fixed-resolution simulation duration in nanoseconds.
Definition Time.h:43
constexpr std::int64_t nanoseconds() const noexcept
Return the exact signed nanosecond representation.
Definition Time.h:69
static constexpr Duration fromNanoseconds(std::int64_t nanoseconds) noexcept
Construct an exact duration from nanoseconds.
Definition Time.h:55
static constexpr Duration zero() noexcept
Return zero duration.
Definition Time.h:60
double seconds() const noexcept
Return this duration as seconds for legacy/presentation APIs.
Definition Time.cpp:29
constexpr bool isZero() const noexcept
Whether this duration is exactly zero.
Definition Time.h:75
Human-readable, scoped identifier in the form namespace:name.
Definition Identity.h:414
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
CombatCarrierRuntime()
Combat carrier runtime.
Result< void > configurePool(std::uint32_t capacity)
Resize the pool while empty; capacity must be in 1..1048576.
std::size_t capacity() const noexcept
Current fixed pool capacity.
Result< void > configureSimulation(const CarrierSimulationSettings &settings)
Copy validated solver settings while the pool is empty; conflicts fail atomically....
Result< CarrierFrame > update(Duration delta, const IProjectileTargetProvider *targets=nullptr, const ICarrierHitProbe *hits=nullptr, const ICarrierBodyDefenseProvider *bodies=nullptr, const ICarrierHitProbe *worldSweep=nullptr)
Atomically advance all live carriers by supplied deterministic time.
Result< std::vector< CarrierHandle > > spawnVolley(const LogicalId &recipeId, const CarrierSpawnRequest &request, const CarrierVolleySpec &volley)
Spawn multiple carriers in deterministic Fan/Ring directions.
std::optional< CarrierRecipe > findRecipe(const LogicalId &id) const
Look up a previously registered recipe by id.
Result< CarrierFrame > updateWithMotion(Duration delta, const ICarrierMotionFunction &motion, const IProjectileTargetProvider *targets=nullptr, const ICarrierHitProbe *hits=nullptr, const ICarrierBodyDefenseProvider *bodies=nullptr, const ICarrierHitProbe *worldSweep=nullptr)
Advance using a caller-owned custom motion function, before hits and triggers. @ownership All provide...
Result< CarrierHandle > spawn(const LogicalId &recipeId, const CarrierSpawnRequest &request)
Spawn one carrier from a registered recipe id.
Result< void > registerRecipe(const CarrierRecipe &recipe)
Register a recipe, or replace it only when no live carrier uses the id. Equal registration is a no-op...
Optional body/shield boundary for SteerAvoidBody.
virtual Result< std::vector< CarrierBodyDefenseSample > > sample(CarrierHandle handle, ecs::EntityHandle target, const CarrierMotion &motion) const =0
Sample body/shield volumes relevant to one carrier step.
Optional swept-hit boundary used only by OnHit triggers.
virtual Result< std::vector< Contact > > query(CarrierHandle handle, const CarrierMotion &previous, const CarrierMotion &current) const =0
Query contacts for one candidate step.
Synchronous custom motion strategy, invoked per proposed segment before collisions....
virtual Result< CarrierMotion > evaluate(const CarrierState &before, const CarrierMotion &proposed, Duration step) const =0
Return final position and velocity, or failure to abort the whole frame.
Optional target-position boundary used only by homing projectiles.
eve::Diagnostic Diagnostic
eve::Result< T > Result
constexpr HexDirection next(HexDirection d) noexcept
The next direction clockwise (NW wraps to NE).
Definition HexMetrics.h:76
Vector2 avoid(Vector2 position, Vector2 velocity, Vector2 obstacle, float obstacleRadius, float lookAhead, float maxAcceleration)
Computes avoidance acceleration away from a predicted obstacle overlap.
Definition Steering.cpp:185
double dot(ForceVector a, ForceVector b)
Definition ForceMath.h:14
ShapeState * child(const JPH::Body &body, const JPH::SubShapeID &id)
Resolves a native child record for a synchronous callback or query. @ownership Borrowed from the worl...
double sample(const Heightmap &map, double u, double v)
Sample.
V3 cross(V3 a, V3 b)
Module-private road bake implementation helper.
Definition RoadBake.cpp:29
载具模块入口(eve.Vehicle):定义注册 / 实体工厂 / RTS 命令 / 帧调度。 设计文档:docs/dev/通用载具系统设计.md
Result< CarrierRecipe > carrierRecipeFromProjectile(const ProjectileDefinition &definition, double damage)
Build a default recipe matching a classic ProjectileDefinition mode.
CarrierTriggerKind
When an impact may fire.
DiagnosticCode
Stable machine-readable diagnostic codes.
Definition Diagnostic.h:47
Generation-qualified reference to one pooled carrier slot.
Data-driven composition recipe for one carrier family.
std::vector< CarrierTrigger > triggers
Result< void > validate() const
Validate finite parameters and composition constraints.
std::vector< CarrierMotionOp > motionOps
std::vector< CarrierImpact > impacts
Complete deterministic carrier-pool state for rollback/save.
std::vector< CarrierSlotSnapshot > slots
CarrierSimulationSettings simulation
std::vector< CarrierRecipe > recipes
Owning recipe context; restore rejects missing or modified active recipes.
Bounded simulation work per carrier per outer update. Zero maxStep preserves caller-supplied fixed st...
EVENGINE_API_WORLD Result< void > validate() const
Validate finite work budgets and a nonnegative step duration.
One trigger specification.
Deterministic multi-direction spawn descriptor.
Data-driven trajectory and lifetime definition.
bool consumed
Definition Graphics.cpp:201