载入中...
搜索中...
未找到
WeaponDefinitionRuntime.cpp
浏览该文件的文档.
2#include "common/ValueRead.h"
3
4#include "common/Value.h"
5#include "weapon/Weapon.h"
6
7#include <algorithm>
8#include <cmath>
9#include <cstdint>
10#include <limits>
11#include <memory>
12#include <set>
13#include <stdexcept>
14#include <utility>
15
16namespace eve::weapon {
17namespace {
18
19const eve::Value* field(const eve::Value::Object& object, std::string_view name) {
20 const auto it = object.find(std::string(name));
21 return it == object.end() ? nullptr : &it->second;
22}
23
24bool readText(const eve::Value::Object& object, std::string_view name, std::string& output) {
25 if (!field(object, name)) return true;
26 auto parsed = eve::readStringMember(object, name);
27 if (!parsed) return false;
28 output = std::move(parsed.value());
29 return true;
30}
31
32bool readNumber(const eve::Value::Object& object, std::string_view name, float& output) {
33 const auto* value = field(object, name);
34 if (value == nullptr) return true;
35 if (const auto* number = value->getIf<double>()) {
36 if (!std::isfinite(*number)) return false;
37 output = static_cast<float>(*number);
38 return std::isfinite(output);
39 }
40 if (const auto* integer = value->getIf<std::int64_t>()) {
41 output = static_cast<float>(*integer);
42 return std::isfinite(output);
43 }
44 return false;
45}
46
47bool readInteger(const eve::Value::Object& object, std::string_view name, int& output) {
48 const auto* value = field(object, name);
49 if (!value) return true;
50 auto parsed = eve::readIntValue(*value);
51 if (!parsed) return false;
52 output = parsed.value();
53 return true;
54}
55
56bool readBoolean(const eve::Value::Object& object, std::string_view name, bool& output) {
57 const auto* value = field(object, name);
58 if (!value) return true;
59 auto parsed = eve::readBoolValue(*value);
60 if (!parsed) return false;
61 output = parsed.value();
62 return true;
63}
64
65bool readStringArray(const eve::Value::Object& object, std::string_view name,
66 std::vector<std::string>& output) {
67 const auto* value = field(object, name);
68 if (value == nullptr) return true;
69 const auto* array = value->getIf<eve::Value::Array>();
70 if (array == nullptr) return false;
71 std::vector<std::string> candidate;
72 candidate.reserve(array->size());
73 for (const auto& entry : *array) {
74 const auto* text = entry.getIf<std::string>();
75 if (text == nullptr || text->empty()) return false;
76 candidate.push_back(*text);
77 }
78 std::sort(candidate.begin(), candidate.end());
79 if (std::adjacent_find(candidate.begin(), candidate.end()) != candidate.end()) return false;
80 output = std::move(candidate);
81 return true;
82}
83
84const char* resourceKindName(ResourceKind kind) noexcept {
85 switch (kind) {
86 case ResourceKind::None: return "none";
87 case ResourceKind::Ammo: return "ammo";
88 case ResourceKind::Mana: return "mana";
89 case ResourceKind::Charges: return "charges";
90 case ResourceKind::Stamina: return "stamina";
91 }
92 return "none";
93}
94
95ResourceKind resourceKindFromName(std::string_view name) noexcept {
96 if (name == "ammo") return ResourceKind::Ammo;
97 if (name == "mana") return ResourceKind::Mana;
98 if (name == "charges") return ResourceKind::Charges;
99 if (name == "stamina") return ResourceKind::Stamina;
100 return ResourceKind::None;
101}
102
103AttackStage attackStageFromName(std::string_view name) noexcept {
104 if (name == "windup") return AttackStage::Windup;
105 if (name == "active") return AttackStage::Active;
106 if (name == "recover") return AttackStage::Recover;
107 return AttackStage::Idle;
108}
109
112 auto parsed = eve::Value::fromJson(source.json);
113 if (!parsed) return eve::Result<WeaponDefinition>::failure(parsed.status());
114 auto value = std::move(parsed).takeValue();
115 const auto* object = value.getIf<eve::Value::Object>();
116 if (object == nullptr)
118 "weapon definition must be an object",
119 "json", {}, "weapon.definition_runtime"));
120
121 WeaponDefinition result;
122 result.id = std::string(reference.id().name());
123 std::string id = result.id;
124 if (!readText(*object, "id", id) || id != result.id)
126 eve::DiagnosticCode::InvalidArgument, "weapon definition id does not match its logical reference", "id", {},
127 "weapon.definition_runtime"));
128 std::string kind = weaponKindName(result.kind);
129 std::string logic = result.logic;
130 if (!readText(*object, "kind", kind) || !readText(*object, "logic", logic))
132 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "weapon kind and logic must be strings",
133 "definition", {}, "weapon.definition_runtime"));
135 result.logic = std::move(logic);
136
137 if (!readNumber(*object, "damage", result.damage) || !readNumber(*object, "penetration", result.penetration) ||
138 !readNumber(*object, "range", result.range) || !readNumber(*object, "spread", result.spread) ||
139 !readNumber(*object, "falloffStart", result.falloffStart) ||
140 !readNumber(*object, "minimumDamageFactor", result.minimumDamageFactor) ||
141 !readNumber(*object, "splashMinimumDamageFactor", result.splashMinimumDamageFactor) ||
142 !readNumber(*object, "preferredTargetBonus", result.preferredTargetBonus) ||
143 !readNumber(*object, "accuracy", result.accuracy) ||
144 !readNumber(*object, "scatterRadius", result.scatterRadius) ||
145 !readNumber(*object, "spreadMin", result.spreadMin) || !readNumber(*object, "spreadMax", result.spreadMax) ||
146 !readNumber(*object, "spreadPerShot", result.spreadPerShot) ||
147 !readNumber(*object, "spreadRecover", result.spreadRecover) ||
148 !readNumber(*object, "recoilPitch", result.recoilPitch) ||
149 !readNumber(*object, "recoilYaw", result.recoilYaw) ||
150 !readNumber(*object, "recoilRecover", result.recoilRecover) ||
151 !readNumber(*object, "zoomFov", result.zoomFov) || !readNumber(*object, "cooldown", result.cooldown) ||
152 !readNumber(*object, "arc", result.arc))
154 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "weapon numeric fields must be finite numbers",
155 "definition", {}, "weapon.definition_runtime"));
156 if (result.falloffStart < 0.0f || result.falloffStart > result.range ||
157 result.minimumDamageFactor < 0.0f || result.minimumDamageFactor > 1.0f ||
158 result.splashMinimumDamageFactor < 0.0f || result.splashMinimumDamageFactor > 1.0f ||
159 result.accuracy < 0.0f || result.accuracy > 1.0f || result.scatterRadius < 0.0f ||
160 result.preferredTargetBonus < 1.0f)
162 eve::DiagnosticCode::InvalidArgument, "weapon damage falloff fields are outside valid ranges", "definition",
163 {}, "weapon.definition_runtime"));
164
165 if (!readText(*object, "damageType", result.damageType) || !readText(*object, "element", result.element) ||
166 !readBoolean(*object, "targetsGround", result.targetsGround) ||
167 !readBoolean(*object, "targetsAir", result.targetsAir) ||
168 !readBoolean(*object, "friendlyFire", result.friendlyFire) ||
169 !readBoolean(*object, "blockedByObstacles", result.blockedByObstacles) ||
170 !readStringArray(*object, "requiredTargetTags", result.requiredTargetTags) ||
171 !readStringArray(*object, "excludedTargetTags", result.excludedTargetTags) ||
172 !readStringArray(*object, "preferredTargetTags", result.preferredTargetTags))
174 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "weapon target policy fields are invalid",
175 "definition", {}, "weapon.definition_runtime"));
176 if (!result.targetsGround && !result.targetsAir)
178 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "weapon must target ground, air, or both",
179 "definition", {}, "weapon.definition_runtime"));
180
181 if (const auto* modes = field(*object, "fireModes")) {
182 const auto* array = modes->getIf<eve::Value::Array>();
183 if (array == nullptr)
185 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "fireModes must be an array", "fireModes",
186 {}, "weapon.definition_runtime"));
187 for (const auto& entry : *array) {
188 const auto* text = entry.getIf<std::string>();
189 if (text == nullptr)
192 "fireModes", {}, "weapon.definition_runtime"));
193 result.selectableModes.push_back(fireModeFromName(*text));
194 }
195 }
196 std::string fireMode = fireModeName(result.fireMode);
197 if (!readText(*object, "fireMode", fireMode))
199 "fireMode must be a string", "fireMode",
200 {}, "weapon.definition_runtime"));
201 result.fireMode = fireModeFromName(fireMode);
202
203 if (const auto* resource = field(*object, "resource")) {
204 const auto* nested = resource->getIf<eve::Value::Object>();
205 if (nested == nullptr)
207 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "resource must be an object", "resource",
208 {}, "weapon.definition_runtime"));
209 std::string resourceName = resourceKindName(result.resource.kind);
210 if (!readText(*nested, "kind", resourceName) || !readNumber(*nested, "max", result.resource.max) ||
211 !readNumber(*nested, "regen", result.resource.regen) ||
212 !readNumber(*nested, "cost", result.resource.cost) ||
213 !readBoolean(*nested, "infinite", result.resource.infinite))
215 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "weapon resource fields are invalid",
216 "resource", {}, "weapon.definition_runtime"));
217 result.resource.kind = resourceKindFromName(resourceName);
218 }
219 if (const auto* stages = field(*object, "stages")) {
220 const auto* nested = stages->getIf<eve::Value::Object>();
221 if (nested == nullptr || !readNumber(*nested, "windup", result.stages.windupTime) ||
222 !readNumber(*nested, "active", result.stages.activeTime) ||
223 !readNumber(*nested, "recover", result.stages.recoverTime))
225 "stages fields are invalid", "stages",
226 {}, "weapon.definition_runtime"));
227 }
228 if (const auto* burst = field(*object, "burst")) {
229 const auto* nested = burst->getIf<eve::Value::Object>();
230 if (nested == nullptr || !readInteger(*nested, "size", result.burstSize) ||
231 !readNumber(*nested, "interval", result.burstInterval))
233 "burst fields are invalid", "burst",
234 {}, "weapon.definition_runtime"));
235 }
236 if (const auto* ammo = field(*object, "ammo")) {
237 const auto* nested = ammo->getIf<eve::Value::Object>();
238 if (nested == nullptr || !readInteger(*nested, "mag", result.magSize) ||
239 !readInteger(*nested, "reserve", result.reserveSize) || !readNumber(*nested, "reload", result.reloadTime))
241 "ammo fields are invalid", "ammo", {},
242 "weapon.definition_runtime"));
243 }
244 if (const auto* projectile = field(*object, "projectile")) {
245 const auto* nested = projectile->getIf<eve::Value::Object>();
246 if (nested == nullptr || !readText(*nested, "type", result.projectile.type) ||
247 !readNumber(*nested, "speed", result.projectile.speed) ||
248 !readNumber(*nested, "gravity", result.projectile.gravity) ||
249 !readNumber(*nested, "aoe", result.projectile.aoe) ||
250 !readInteger(*nested, "pelletCount", result.projectile.pelletCount) ||
251 !readNumber(*nested, "pelletSpread", result.projectile.pelletSpread))
253 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "projectile fields are invalid",
254 "projectile", {}, "weapon.definition_runtime"));
255 }
256 if (const auto* effects = field(*object, "effects")) {
257 const auto* nested = effects->getIf<eve::Value::Object>();
258 if (nested == nullptr || !readText(*nested, "muzzle", result.effectMuzzle) ||
259 !readText(*nested, "sound", result.effectSound))
261 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "effects fields are invalid", "effects",
262 {}, "weapon.definition_runtime"));
263 }
264 if (result.resource.kind == ResourceKind::None) result.resource.infinite = true;
266}
267
270 const auto& logical = reference.id();
271 return registry.handle(std::string(logical.namespaceName()), std::string(logical.name()));
272}
273
277 auto resolved = registry.resolveHandle(handle);
279 return parseDefinition(resolved.value().get(), reference);
280}
281
282eve::LogicalId runtimeSchema() {
283 static const eve::LogicalId value = [] {
284 auto parsed = eve::LogicalId::parse("weapon:runtime");
285 if (!parsed) throw std::logic_error("invalid built-in weapon snapshot schema");
286 return *parsed;
287 }();
288 return value;
289}
290
291WeaponRuntimeState initialState(const WeaponDefinition& definition) {
292 WeaponRuntimeState result;
293 result.selector = definition.fireMode;
294 result.currentSpread = definition.spreadMin;
295 result.resource.kind = definition.resource.kind;
296 result.resource.max = definition.resource.max;
297 result.resource.regen = definition.resource.regen;
298 result.resource.cost = definition.resource.cost;
299 result.resource.infinite = definition.resource.infinite;
300 if (definition.kind == WeaponKind::Ranged) {
301 result.resource.kind = ResourceKind::Ammo;
302 result.resource.max = static_cast<float>(definition.magSize);
303 result.resource.value = static_cast<float>(definition.magSize);
304 result.resource.cost = 1.f;
305 result.resource.reserve = definition.reserveSize < 0 ? 0 : definition.reserveSize;
306 result.resource.infinite = definition.reserveSize < 0;
307 } else {
308 result.resource.value = result.resource.infinite ? 0.f : result.resource.max;
309 }
310 return result;
311}
312
313eve::Value encodeState(const WeaponRuntimeState& state) {
314 const Resource& resource = state.resource;
315 eve::Value::Object resourceObject{
316 {"cost", eve::Value(resource.cost)},
317 {"infinite", eve::Value(resource.infinite)},
318 {"kind", eve::Value(resourceKindName(resource.kind))},
319 {"max", eve::Value(resource.max)},
320 {"regen", eve::Value(resource.regen)},
321 {"reloadProgress", eve::Value(resource.reloadProgress)},
322 {"reloading", eve::Value(resource.reloading)},
323 {"reserve", eve::Value(resource.reserve)},
324 {"value", eve::Value(resource.value)},
325 };
327 {"aiming", eve::Value(state.aiming)},
328 {"burstRemaining", eve::Value(state.burstRemaining)},
329 {"burstTimer", eve::Value(state.burstTimer)},
330 {"cooldown", eve::Value(state.cooldown)},
331 {"currentSpread", eve::Value(state.currentSpread)},
332 {"jammed", eve::Value(state.jammed)},
333 {"recoilPitch", eve::Value(state.recoilPitch)},
334 {"recoilYaw", eve::Value(state.recoilYaw)},
335 {"resource", eve::Value(std::move(resourceObject))},
336 {"selector", eve::Value(fireModeName(state.selector))},
337 {"stage", eve::Value(attackStageName(state.stage))},
338 {"stageTimer", eve::Value(state.stageTimer)},
339 });
340}
341
342bool readStateNumber(const eve::Value::Object& object, const char* name, float& output) {
343 return readNumber(object, name, output);
344}
345
347 const auto* object = value.getIf<eve::Value::Object>();
348 if (object == nullptr)
350 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "weapon runtime state must be an object",
351 "state", {}, "weapon.definition_runtime"));
352 static const std::set<std::string> fields = {"aiming", "burstRemaining", "burstTimer", "cooldown",
353 "currentSpread", "jammed", "recoilPitch", "recoilYaw",
354 "resource", "selector", "stage", "stageTimer"};
355 for (const auto& [name, unused] : *object) {
356 (void)unused;
357 if (!fields.contains(name))
359 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "unknown weapon runtime state field",
360 "state." + name, {}, "weapon.definition_runtime"));
361 }
362 for (const auto& name : fields)
363 if (!object->contains(name))
364 return eve::Result<WeaponRuntimeState>::failure(
365 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "weapon runtime state is missing a field",
366 "state." + name, {}, "weapon.definition_runtime"));
367
368 WeaponRuntimeState result;
369 std::string selector;
370 std::string stage;
371 if (!readBoolean(*object, "aiming", result.aiming) ||
372 !readInteger(*object, "burstRemaining", result.burstRemaining) ||
373 !readStateNumber(*object, "burstTimer", result.burstTimer) ||
374 !readStateNumber(*object, "cooldown", result.cooldown) ||
375 !readStateNumber(*object, "currentSpread", result.currentSpread) ||
376 !readBoolean(*object, "jammed", result.jammed) ||
377 !readStateNumber(*object, "recoilPitch", result.recoilPitch) ||
378 !readStateNumber(*object, "recoilYaw", result.recoilYaw) || !readText(*object, "selector", selector) ||
379 !readText(*object, "stage", stage) || !readStateNumber(*object, "stageTimer", result.stageTimer))
381 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "weapon runtime scalar field is invalid",
382 "state", {}, "weapon.definition_runtime"));
383 result.selector = fireModeFromName(selector);
384 result.stage = attackStageFromName(stage);
385 const auto* resourceValue = object->at("resource").getIf<eve::Value::Object>();
386 if (resourceValue == nullptr)
388 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "weapon runtime resource is invalid",
389 "state.resource", {}, "weapon.definition_runtime"));
390 std::string kind;
391 if (!readText(*resourceValue, "kind", kind) || !readStateNumber(*resourceValue, "value", result.resource.value) ||
392 !readStateNumber(*resourceValue, "max", result.resource.max) ||
393 !readStateNumber(*resourceValue, "regen", result.resource.regen) ||
394 !readStateNumber(*resourceValue, "cost", result.resource.cost) ||
395 !readBoolean(*resourceValue, "infinite", result.resource.infinite) ||
396 !readInteger(*resourceValue, "reserve", result.resource.reserve) ||
397 !readBoolean(*resourceValue, "reloading", result.resource.reloading) ||
398 !readStateNumber(*resourceValue, "reloadProgress", result.resource.reloadProgress))
400 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "weapon runtime resource fields are invalid",
401 "state.resource", {}, "weapon.definition_runtime"));
402 result.resource.kind = resourceKindFromName(kind);
404}
405
406} // namespace
407
409 auto logical = eve::LogicalId::fromParts("weapon", source.id);
410 if (!logical)
412 "weapon definition id is invalid", "id",
413 {}, "weapon.definition_runtime"));
414 auto reference = eve::DefinitionRef::fromId(*logical);
416 if (source.type != "weapon")
418 "definition type must be weapon", "type",
419 {}, "weapon.definition_runtime"));
420 return parseDefinition(source, reference.value());
421}
422
424 eve::DefinitionRef definition,
427 if (!definition.id().isValid() || definition.id().namespaceName() != "weapon")
429 eve::DiagnosticCode::InvalidArgument, "weapon definition reference must use weapon namespace", "definition",
430 {}, "weapon.definition_runtime"));
431 auto handle = currentHandle(registry, definition);
433 auto typed = definitionFor(registry, handle.value(), definition);
434 if (!typed) return eve::Result<WeaponDefinitionRuntime>::failure(typed.status());
436 instanceId, std::move(definition), handle.value().generation, initialState(typed.value()));
437 if (!runtime) return eve::Result<WeaponDefinitionRuntime>::failure(runtime.status());
439 WeaponDefinitionRuntime(registry, std::move(runtime).takeValue(), policy));
440}
441
443 std::string_view definitionId,
446 auto logical = eve::LogicalId::fromParts("weapon", definitionId);
447 if (!logical)
449 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "weapon id is not a valid logical name",
450 "definitionId", {}, "weapon.definition_runtime"));
451 auto reference = eve::DefinitionRef::fromId(*logical);
453 return create(registry, std::move(reference).takeValue(), instanceId, policy);
454}
455
459 return create(module.definitionRegistry(), definitionId, instanceId, policy);
460}
461
463 return runtime_.identity();
464}
465
466const WeaponRuntimeState& WeaponDefinitionRuntime::state() const noexcept { return runtime_.state(); }
467
468WeaponRuntimeState& WeaponDefinitionRuntime::state() noexcept { return runtime_.state(); }
469
471 return runtime_.identity().definitionHandle();
472}
473
475 if (registry_ == nullptr)
477 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "weapon definition registry is not bound",
478 "registry", {}, "weapon.definition_runtime"));
479 return definitionFor(*registry_, definitionHandle(), identity().definition);
480}
481
482void WeaponDefinitionRuntime::setActive(bool active) noexcept { runtime_.setActive(active); }
483
484bool WeaponDefinitionRuntime::isActive() const noexcept { return runtime_.isActive(); }
485
487 if (entity == nullptr)
489 "weapon runtime cannot project to a null WeaponEntity",
490 "entity", {}, "weapon.definition_runtime"));
491 auto typed = definition();
492 if (!typed) return eve::Result<void>::failure(typed.status());
493 try {
494 auto definitionOwner = std::make_shared<const WeaponDefinition>(typed.value());
495 auto definitionComponent = *entity->definition();
496 auto binding = *entity->definitionBinding();
497 auto targetState = *entity->state();
498 definitionComponent.owned = std::move(definitionOwner);
499 definitionComponent.def = definitionComponent.owned.get();
500 binding.identity = identity();
501 binding.reloadPolicy = policy_;
502 binding.active = isActive();
503 const auto& source = state();
504 targetState.resource = source.resource;
505 targetState.cooldown = source.cooldown;
506 targetState.burstRemaining = source.burstRemaining;
507 targetState.burstTimer = source.burstTimer;
508 targetState.jammed = source.jammed;
509 targetState.stage = source.stage;
510 targetState.stageTimer = source.stageTimer;
511 targetState.stages = &definitionComponent.def->stages;
512 targetState.currentSpread = source.currentSpread;
513 targetState.recoilPitch = source.recoilPitch;
514 targetState.recoilYaw = source.recoilYaw;
515 targetState.selector = source.selector;
516 targetState.aiming = source.aiming;
517 using std::swap;
518 swap(*entity->definition(), definitionComponent);
519 swap(*entity->definitionBinding(), binding);
520 swap(*entity->state(), targetState);
522 } catch (const std::exception&) {
524 "weapon runtime projection allocation failed",
525 "entity", {}, "weapon.definition_runtime"));
526 }
527}
528
530 if (registry_ == nullptr)
532 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "weapon definition registry is not bound",
533 "registry", {}, "weapon.definition_runtime"));
534 auto next = currentHandle(*registry_, identity().definition);
535 if (!next) return eve::Result<eve::definition::ReloadOutcome>::failure(next.status());
536 auto typed = definitionFor(*registry_, next.value(), identity().definition);
537 if (!typed) return eve::Result<eve::definition::ReloadOutcome>::failure(typed.status());
538 const WeaponRuntimeState defaults = initialState(typed.value());
539 const float maxSpread = std::max(defaults.currentSpread, typed.value().spreadMax);
540 auto rebuild = [defaults, maxSpread](const WeaponRuntimeState& oldState, const eve::definition::InstanceIdentity&,
542 WeaponRuntimeState rebuilt = oldState;
543 if (oldState.resource.kind != defaults.resource.kind) {
544 rebuilt.resource = defaults.resource;
545 } else {
546 rebuilt.resource.kind = defaults.resource.kind;
547 rebuilt.resource.max = defaults.resource.max;
548 rebuilt.resource.regen = defaults.resource.regen;
549 rebuilt.resource.cost = defaults.resource.cost;
550 rebuilt.resource.infinite = defaults.resource.infinite;
551 if (rebuilt.resource.infinite) {
552 rebuilt.resource.value = 0.f;
553 } else {
554 rebuilt.resource.value = std::clamp(rebuilt.resource.value, 0.f, rebuilt.resource.max);
555 }
556 rebuilt.resource.reserve = defaults.resource.reserve < 0 ? 0 : rebuilt.resource.reserve;
557 }
558 rebuilt.selector = defaults.selector;
559 rebuilt.currentSpread = std::clamp(oldState.currentSpread, 0.f, maxSpread);
560 return eve::Result<WeaponRuntimeState>::success(std::move(rebuilt));
561 };
562 auto result = runtime_.reload(next.value(), policy, defaults, std::move(rebuild));
563 if (result.ok()) policy_ = policy;
564 return result;
565}
566
575
583
585 const eve::SnapshotHashProvider& hashProvider) {
586 if (registry_ == nullptr)
588 "weapon definition registry is not bound", "registry",
589 {}, "weapon.definition_runtime"));
590 auto current = currentHandle(*registry_, identity().definition);
591 if (!current) return eve::Result<void>::failure(current.status());
592 if (current.value() != definitionHandle())
594 eve::DiagnosticCode::StaleHandle, "weapon snapshot cannot restore against a replaced definition",
595 "definitionGeneration", {}, "weapon.definition_runtime"));
597 return eve::definition::restoreRuntimeInstance(runtime_, snapshotValue, "weapon.runtime", runtimeSchema(),
598 eve::SchemaVersion(1), hashProvider, decoder);
599}
600
601} // namespace eve::weapon
bool & active
std::string output
std::uint64_t revision
AuthorityStoreHandleRef reference
Definition Authority.cpp:24
std::vector< Value > defaults
Definition ECS.cpp:49
std::string name
Definition ECS.cpp:154
std::vector< std::string > fields
Definition ECS.cpp:42
int instanceId
Poco::JSON::Object::Ptr result
std::string error
Definition Package.cpp:174
eve::action::ActionVfxBinding binding
PrimitiveHandle handle
const eve::script::BindingContractRegistry & registry
Object::Ptr value
const EntityFact * entity
RoadNetwork resolved
double number
std::string text
std::string_view source
std::string kind
double current
std::string resource
SimulationTick tick
Json object
Owning, renderer-independent dynamic values.
Strongly typed Weapon definition/runtime adapter.
Stable definition reference backed by LogicalId.
Definition ResourceRef.h:85
static Result< DefinitionRef > fromId(LogicalId id)
Build a definition reference from a valid LogicalId.
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Human-readable, scoped identifier in the form namespace:name.
Definition Identity.h:414
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
The canonical owning dynamic value used by data-facing protocols.
Definition Value.h:31
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 eve::Result< RuntimeInstance > create(eve::PersistentId instanceId, eve::DefinitionRef definition, eve::Generation definitionGeneration, State state, bool active=true)
Construct a runtime instance after validating its identity.
Deterministic registry of topic-neutral, versioned JSON definitions.
Definition Definitions.h:58
Id128 public API.
Definition Identity.h:111
Binds a typed WeaponDefinition to one mutable runtime instance.
eve::Result< void > applyTo(WeaponEntity *entity) const
Atomically project this runtime into a borrowed WeaponEntity.
const WeaponRuntimeState & state() const noexcept
Borrow mutable typed firing/resource state.
eve::Result< eve::definition::ReloadOutcome > reload(eve::definition::ReloadPolicy policy)
Reload the registry's current generation using a typed policy.
eve::Result< eve::SnapshotEnvelope > snapshot(eve::Revision revision, eve::SimulationTick tick, const eve::SnapshotHashProvider &hashProvider) const
Capture stable typed runtime state in the common SnapshotEnvelope.
eve::Result< std::string > snapshotJson(eve::Revision revision, eve::SimulationTick tick, const eve::SnapshotHashProvider &hashProvider) const
Serialize snapshot() as canonical deterministic JSON.
eve::Result< void > restore(const eve::SnapshotEnvelope &snapshot, const eve::SnapshotHashProvider &hashProvider)
Verify and restore a same-generation snapshot transactionally.
eve::Result< WeaponDefinition > definition() const
Resolve the current strongly typed WeaponDefinition projection.
void setActive(bool active) noexcept
Set the active guard used by RejectWhileActive.
static eve::Result< WeaponDefinitionRuntime > create(eve::definitions::DefinitionRegistry &registry, eve::DefinitionRef definition, eve::PersistentId instanceId, eve::definition::ReloadPolicy policy=eve::definition::ReloadPolicy::RebuildInstance)
Create from a common weapon:<name> definition reference.
eve::definition::DefinitionHandle definitionHandle() const noexcept
Return the exact generation-qualified definition handle.
bool isActive() const noexcept
Return whether the instance is active.
const eve::definition::InstanceIdentity & identity() const noexcept
Borrow the common instance identity and exact definition generation.
武器实体:数据全部在组件里,行为在 WeaponSystem。
武器模块(eve.Weapon)。
Definition Weapon.h:24
eve::definitions::DefinitionRegistry & definitionRegistry() noexcept
Return the common registry backing legacy weapon definitions.
Definition Weapon.h:54
const Value * field(const Value &value, const char *key)
Borrow an optional object field.
ReloadPolicy
Policy used when a live definition is replaced.
eve::Result< eve::SnapshotEnvelope > snapshotRuntimeInstance(const RuntimeInstance< State > &runtime, std::string type, eve::LogicalId schema, eve::SchemaVersion schemaVersion, eve::Revision revision, eve::SimulationTick tick, const eve::SnapshotHashProvider &hashProvider, const RuntimeStateEncoder< State > &encode)
Capture a typed runtime instance in the common snapshot envelope.
eve::Result< void > restoreRuntimeInstance(RuntimeInstance< State > &runtime, const eve::SnapshotEnvelope &snapshot, std::string_view expectedType, const eve::LogicalId &expectedSchema, eve::SchemaVersion expectedVersion, const eve::SnapshotHashProvider &hashProvider, const RuntimeStateDecoder< State > &decode)
Verify and atomically restore a typed runtime instance.
std::function< eve::Result< State >(const eve::Value &)> RuntimeStateDecoder
Decodes one domain-owned runtime state from an owning Value.
std::function< eve::Result< eve::Value >(const State &)> RuntimeStateEncoder
Converts one domain-owned runtime state into an owning Value.
eve::Diagnostic Diagnostic
eve::Result< T > Result
eve::Result< double > readNumber(const eve::Value::Object &object, std::string_view name)
Reads a required finite number.
载具模块入口(eve.Vehicle):定义注册 / 实体工厂 / RTS 命令 / 帧调度。 设计文档:docs/dev/通用载具系统设计.md
const char * weaponKindName(WeaponKind kind)
武器形态的字符串名("melee" | "ranged" | "magic" | "missile" | "custom")。
Definition Weapon.cpp:86
eve::Result< WeaponDefinition > parseWeaponDefinition(const eve::definitions::Definition &source)
Parse one canonical registry definition into an owning typed snapshot.
WeaponKind weaponKindFromName(const std::string &name)
从字符串解析武器形态;未知名字回退 Ranged。
Definition Weapon.cpp:97
FireMode fireModeFromName(const std::string &name)
从字符串解析开火模式;未知名字回退 Single。
Definition Weapon.cpp:80
AttackStage
攻击阶段。
Definition WeaponTypes.h:62
const char * fireModeName(FireMode mode)
开火模式的字符串名("single" | "burst" | "auto")。
Definition Weapon.cpp:71
const char * attackStageName(AttackStage stage)
攻击阶段的字符串名("idle" | "windup" | "active" | "recover")。
Definition Weapon.cpp:105
ResourceKind
触发资源的类型。
Definition WeaponTypes.h:50
Build metadata (engine git commit, build time, third-party version).
Definition Build.cpp:16
DiagnosticCode
Stable machine-readable diagnostic codes.
Definition Diagnostic.h:47
Result< std::string > serializeSnapshotEnvelope(const SnapshotEnvelope &snapshot)
Serialize an envelope as deterministic compact JSON.
Definition Snapshot.cpp:184
Result< bool > readBoolValue(const Value &value)
Read a Bool without coercing integers, strings or other kinds.
Definition Value.cpp:50
Result< int > readIntValue(const Value &value)
Read an Int64 value as a range-checked native int without numeric coercion.
Definition Value.cpp:41
Result< std::string > readStringMember(const Value::Object &object, std::string_view name)
Read a required string field, including an empty string, as an owning value.
Definition Value.cpp:25
std::function< Result< ContentId >(std::string_view canonicalInput)> SnapshotHashProvider
Injected content-digest implementation used by snapshots.
Definition Snapshot.h:36
Stable outer format shared by persistence and cross-process snapshots.
Definition Snapshot.h:46
A generation-qualified reference to one definition incarnation.
Canonical identity carried by every typed runtime instance.
One immutable view of a registered versioned JSON definition.
Definition Definitions.h:31
int reserve
备用弹药(热武器;<0 = 无限)。
Mutable state owned by one typed weapon runtime instance.