载入中...
搜索中...
未找到
Combat.cpp
浏览该文件的文档.
1#include "combat/Combat.h"
2
6#include "combat/Damage.h"
10
11#include <simplesquirrel/simplesquirrel.hpp>
12
13#include <algorithm>
14#include <cmath>
15#include <cstdint>
16#include <functional>
17#include <map>
18#include <memory>
19#include <string>
20#include <utility>
21
22namespace eve::combat {
23namespace {
24
25Result<SubjectRef> parseSubject(const std::string& text, std::string path) {
26 const auto parsed = PersistentId::parse(text);
27 if (!parsed)
29 DiagnosticCode::InvalidArgument, "combat subject must be a UUID", std::move(path), {}, "combat.squirrel"));
31}
32
33Value vectorValue(CombatVector2 value) {
35 result["x"] = value.x;
36 result["z"] = value.z;
37 return Value(std::move(result));
38}
39
40std::string reactionName(HitReaction reaction) {
41 switch (reaction) {
42 case HitReaction::None: return "none";
43 case HitReaction::Flinch: return "flinch";
44 case HitReaction::Stagger: return "stagger";
45 case HitReaction::Knockdown: return "knockdown";
46 case HitReaction::Death: return "death";
47 }
48 return "none";
49}
50
51class ScriptCombatRuntime {
52public:
53 ScriptCombatRuntime() : locomotion_(navigation_) {}
54
55 Result<void> initializeAbilities() {
57 if (!definitions) return Result<void>::failure(definitions.status());
58 for (auto& definition : definitions.value()) {
59 auto registered = actions_.registerAbilityDefinition(std::move(definition));
60 if (!registered) return registered;
61 }
63 }
64
65 Result<Value> registerFighter(const std::string& subjectText, const std::string& ownerId, double x, double z,
66 double health, double poise, double maximumSpeed, double acceleration) {
67 auto subject = parseSubject(subjectText, "subject");
68 if (!subject) return Result<Value>::failure(subject.status());
69 CombatState combatState{subject.value(), health, health, poise, poise};
70 auto valid = combatState.validate();
71 if (!valid) return Result<Value>::failure(valid.status());
72 if (states_.contains(subjectText))
74 DiagnosticCode::AlreadyExists, "combat fighter already exists", subjectText, {}, "combat.squirrel"));
75 auto registered = locomotion_.registerSubject({subject.value(), ownerId, {x, z}, maximumSpeed, acceleration});
76 if (!registered) return Result<Value>::failure(registered.status());
77 states_.emplace(subjectText, std::move(combatState));
78 return state(subjectText);
79 }
80
81 Result<Value> setMoveIntent(const std::string& subjectText, double x, double z, double speedFraction) {
82 auto subject = parseSubject(subjectText, "subject");
83 if (!subject) return Result<Value>::failure(subject.status());
84 auto changed = locomotion_.setMoveIntent(subject.value(), {x, z}, speedFraction);
85 if (!changed) return Result<Value>::failure(changed.status());
86 return state(subjectText);
87 }
88
89 Result<Value> navigateTo(const std::string& subjectText, double x, double z, double acceptanceRadius) {
90 auto subject = parseSubject(subjectText, "subject");
91 if (!subject) return Result<Value>::failure(subject.status());
92 auto changed = locomotion_.navigateTo(subject.value(), {{x, z}, acceptanceRadius});
93 if (!changed) return Result<Value>::failure(changed.status());
94 return state(subjectText);
95 }
96
97 Result<Value> stop(const std::string& subjectText) {
98 auto subject = parseSubject(subjectText, "subject");
99 if (!subject) return Result<Value>::failure(subject.status());
100 auto stopped = locomotion_.stop(subject.value());
101 if (!stopped) return Result<Value>::failure(stopped.status());
102 return state(subjectText);
103 }
104
105 Result<Value> advance(std::int64_t tick, double seconds) {
106 if (tick < 0)
108 DiagnosticCode::InvalidArgument, "combat tick must be non-negative", "tick", {}, "combat.squirrel"));
109 auto delta = Duration::fromSeconds(seconds);
110 if (!delta) return Result<Value>::failure(delta.status());
111 auto advanced =
112 locomotion_.advance({SimulationTick(static_cast<std::uint64_t>(tick)), std::move(delta).takeValue()});
113 if (!advanced) return Result<Value>::failure(advanced.status());
114 lastTick_ = SimulationTick(static_cast<std::uint64_t>(tick));
116 events.reserve(advanced.value().events.size());
117 for (const auto& event : advanced.value().events) {
119 value["subject"] = event.subject.format();
120 value["kind"] = event.kind == CombatLocomotionEventKind::Arrived ? "arrived" : "moved";
121 value["position"] = vectorValue(event.position);
122 events.emplace_back(std::move(value));
123 }
125 result["tick"] = tick;
126 result["events"] = std::move(events);
128 }
129
130 Result<Value> applyDamage(const std::string& sourceText, const std::string& targetText,
131 const std::string& damageType, double healthDamage, double poiseDamage, double knockbackX,
132 double knockbackY, double knockbackZ, bool critical, std::int64_t tick) {
133 if (tick < 0)
135 auto source = parseSubject(sourceText, "source");
136 if (!source) return Result<Value>::failure(source.status());
137 auto target = parseSubject(targetText, "target");
138 if (!target) return Result<Value>::failure(target.status());
139 const auto found = states_.find(targetText);
140 if (found == states_.end())
141 return Result<Value>::failure(Diagnostic::error(DiagnosticCode::NotFound, "combat target was not found",
142 targetText, {}, "combat.squirrel"));
143 DamageRequest request;
144 request.source = source.value();
145 request.target = target.value();
146 request.damageType = damageType;
147 request.healthDamage = healthDamage;
148 request.poiseDamage = poiseDamage;
149 request.knockback = {knockbackX, knockbackY, knockbackZ};
150 request.critical = critical;
151 request.tick = SimulationTick(static_cast<std::uint64_t>(tick));
152 auto outcome = damage_.apply(found->second, request);
153 if (!outcome) return Result<Value>::failure(outcome.status());
155 result["source"] = outcome.value().source.format();
156 result["target"] = outcome.value().target.format();
157 result["health"] = outcome.value().health;
158 result["poise"] = outcome.value().poise;
159 result["appliedHealthDamage"] = outcome.value().appliedHealthDamage;
160 result["appliedPoiseDamage"] = outcome.value().appliedPoiseDamage;
161 result["reaction"] = reactionName(outcome.value().reaction);
162 // Reuse the canonical event payload codec, including schema-owned stage explanations.
163 auto payload = Value::fromJson(outcome.value().settlementResult.event->payload);
164 if (!payload) return Result<Value>::failure(payload.status());
165 result["settlement"] = std::move(payload).takeValue();
167 }
168
169 Result<Value> applyTimelineDamage(const std::string& sourceText, const std::string& targetText,
170 const std::string& payloadJson) {
171 auto decoded = Value::fromJson(payloadJson);
172 if (!decoded) return Result<Value>::failure(decoded.status());
173 const auto* payload = decoded.value().getIf<Value::Object>();
174 if (!payload)
176 "combat timeline damage payload must be an object",
177 "payload", {}, "combat.squirrel"));
179 if (!binding) return Result<Value>::failure(binding.status());
180 return applyDamage(sourceText, targetText, binding.value().damageType, binding.value().amount,
181 binding.value().poiseAmount, binding.value().knockback.x, binding.value().knockback.y,
182 binding.value().knockback.z, false, static_cast<std::int64_t>(lastTick_.value()));
183 }
184
185 Result<Value> grantAbility(const std::string& ownerId, const std::string& definitionText) {
186 return actions_.grantAbility(ownerId, definitionText);
187 }
188
189 Result<Value> registerTimelineAbility(const std::string& definitionText, const std::string& timelineJson,
190 double cooldownSeconds, const std::string& instancingText,
191 const std::string& groupText, const std::string& triggerTag) {
192 return actions_.registerTimelineAbility(definitionText, timelineJson, static_cast<float>(cooldownSeconds),
193 instancingText, groupText, triggerTag);
194 }
195
196 Result<Value> replaceTimelineAbility(const std::string& definitionText, const std::string& timelineJson,
197 double cooldownSeconds, const std::string& instancingText,
198 const std::string& groupText, const std::string& triggerTag) {
199 return actions_.replaceTimelineAbility(definitionText, timelineJson, static_cast<float>(cooldownSeconds),
200 instancingText, groupText, triggerTag);
201 }
202
203 Result<Value> activateAbility(std::int64_t grantValue, std::int64_t tickValue) {
204 return actions_.activateAbility(grantValue, tickValue);
205 }
206
207 Result<Value> advanceAbilities(std::int64_t tickValue, double seconds) {
208 return actions_.advanceAbilities(tickValue, static_cast<float>(seconds));
209 }
210
211 Result<Value> cancelAbility(std::int64_t activationValue, std::int64_t tickValue) {
212 return actions_.cancelAbility(activationValue, tickValue);
213 }
214
215 Result<Value> abilityGrant(std::int64_t grantValue) const { return actions_.abilityGrant(grantValue); }
216
217 Result<Value> matchingAbilities(const std::string& ownerId, const std::string& eventTag) const {
218 return actions_.matchingAbilities(ownerId, eventTag);
219 }
220
221 Result<Value> state(const std::string& subjectText) const {
222 auto subject = parseSubject(subjectText, "subject");
223 if (!subject) return Result<Value>::failure(subject.status());
224 const auto found = states_.find(subjectText);
225 if (found == states_.end())
226 return Result<Value>::failure(Diagnostic::error(DiagnosticCode::NotFound, "combat fighter was not found",
227 subjectText, {}, "combat.squirrel"));
228 auto movement = locomotion_.state(subject.value());
229 if (!movement) return Result<Value>::failure(movement.status());
231 result["subject"] = subjectText;
232 result["ownerId"] = movement.value().ownerId;
233 result["position"] = vectorValue(movement.value().position);
234 result["velocity"] = vectorValue(movement.value().velocity);
235 result["facing"] = vectorValue(movement.value().facing);
236 result["health"] = found->second.health;
237 result["maxHealth"] = found->second.maxHealth;
238 result["poise"] = found->second.poise;
239 result["maxPoise"] = found->second.maxPoise;
240 result["navigating"] = movement.value().navigationGoal.has_value();
241 return Result<Value>::success(Value(std::move(result)));
242 }
243
244private:
245 DirectCombatNavigationProvider navigation_;
246 CombatLocomotionRuntime locomotion_;
247 DamageRuntime damage_;
249 std::map<std::string, CombatState, std::less<>> states_;
251 action::ScriptActionRuntime actions_;
252};
253
254ssq::Table project(HSQUIRRELVM vm, Result<Value>&& result) {
255 return script::projectResult(vm, std::move(result), [](Value value) { return value; });
256}
257
258ssq::Table newRuntime(HSQUIRRELVM vm) {
259 auto runtime = std::make_unique<ScriptCombatRuntime>();
260 auto initialized = runtime->initializeAbilities();
261 if (!initialized) return script::projectStatusResult(vm, initialized.status());
262 auto object = script::makeOwnedSquirrelInstance<ScriptCombatRuntime>(vm, std::move(runtime));
263 if (!object) return script::projectStatusResult(vm, object.status());
265 result.set("value", std::move(object).takeValue());
266 result.set("ownership", std::string("owned"));
267 return result;
268}
269
270} // namespace
271
273
274void Combat::expose(ssq::Table& table) {
275 const HSQUIRRELVM vm = table.getHandle();
276 auto runtime = table.addClass<ScriptCombatRuntime>(
277 "CombatRuntime", std::function<ScriptCombatRuntime*()>([] { return nullptr; }), true);
278 runtime.addFunc("ownership", [](ScriptCombatRuntime*) { return std::string("owned"); });
279 runtime.addFunc(
280 "registerFighter", [vm](ScriptCombatRuntime* self, const std::string& subject, const std::string& owner,
281 float x, float z, float health, float poise, float speed, float acceleration) {
282 return project(vm, self ? self->registerFighter(subject, owner, x, z, health, poise, speed, acceleration)
283 : Result<Value>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument,
284 "combat runtime must not be null",
285 "runtime", {}, "combat.squirrel")));
286 });
287 runtime.addFunc(
288 "setMoveIntent", [vm](ScriptCombatRuntime* self, const std::string& subject, float x, float z, float speed) {
289 return project(vm, self ? self->setMoveIntent(subject, x, z, speed)
291 "combat runtime must not be null",
292 "runtime", {}, "combat.squirrel")));
293 });
294 runtime.addFunc(
295 "navigateTo", [vm](ScriptCombatRuntime* self, const std::string& subject, float x, float z, float radius) {
296 return project(vm, self ? self->navigateTo(subject, x, z, radius)
298 "combat runtime must not be null",
299 "runtime", {}, "combat.squirrel")));
300 });
301 runtime.addFunc("stop", [vm](ScriptCombatRuntime* self, const std::string& subject) {
302 return project(vm, self ? self->stop(subject)
304 "combat runtime must not be null", "runtime",
305 {}, "combat.squirrel")));
306 });
307 runtime.addFunc("advance", [vm](ScriptCombatRuntime* self, std::int64_t tick, float seconds) {
308 return project(vm, self ? self->advance(tick, seconds)
310 "combat runtime must not be null", "runtime",
311 {}, "combat.squirrel")));
312 });
313 runtime.addFunc("applyDamage", [vm](ScriptCombatRuntime* self, const std::string& source, const std::string& target,
314 const std::string& type, float health, float poise, float x, float y, float z,
315 bool critical, std::int64_t tick) {
316 return project(vm, self ? self->applyDamage(source, target, type, health, poise, x, y, z, critical, tick)
318 "combat runtime must not be null", "runtime",
319 {}, "combat.squirrel")));
320 });
321 runtime.addFunc("applyTimelineDamage", [vm](ScriptCombatRuntime* self, const std::string& source,
322 const std::string& target, const std::string& payloadJson) {
323 return project(vm, self ? self->applyTimelineDamage(source, target, payloadJson)
325 "combat runtime must not be null", "runtime",
326 {}, "combat.squirrel")));
327 });
328 runtime.addFunc(
329 "grantAbility", [vm](ScriptCombatRuntime* self, const std::string& owner, const std::string& definitionId) {
330 return project(vm, self ? self->grantAbility(owner, definitionId)
332 "combat runtime must not be null",
333 "runtime", {}, "combat.squirrel")));
334 });
335 runtime.addFunc("registerTimelineAbility", [vm](ScriptCombatRuntime* self, const std::string& definitionId,
336 const std::string& timelineJson, float cooldownSeconds,
337 const std::string& instancing, const std::string& activationGroup,
338 const std::string& triggerTag) {
339 return project(vm, self ? self->registerTimelineAbility(definitionId, timelineJson, cooldownSeconds, instancing,
340 activationGroup, triggerTag)
342 "combat runtime must not be null", "runtime",
343 {}, "combat.squirrel")));
344 });
345 runtime.addFunc("replaceTimelineAbility", [vm](ScriptCombatRuntime* self, const std::string& definitionId,
346 const std::string& timelineJson, float cooldownSeconds,
347 const std::string& instancing, const std::string& activationGroup,
348 const std::string& triggerTag) {
349 return project(vm, self ? self->replaceTimelineAbility(definitionId, timelineJson, cooldownSeconds, instancing,
350 activationGroup, triggerTag)
352 "combat runtime must not be null", "runtime",
353 {}, "combat.squirrel")));
354 });
355 runtime.addFunc("activateAbility", [vm](ScriptCombatRuntime* self, std::int64_t grantId, std::int64_t tick) {
356 return project(vm, self ? self->activateAbility(grantId, tick)
358 "combat runtime must not be null", "runtime",
359 {}, "combat.squirrel")));
360 });
361 runtime.addFunc("advanceAbilities", [vm](ScriptCombatRuntime* self, std::int64_t tick, float seconds) {
362 return project(vm, self ? self->advanceAbilities(tick, seconds)
364 "combat runtime must not be null", "runtime",
365 {}, "combat.squirrel")));
366 });
367 runtime.addFunc("cancelAbility", [vm](ScriptCombatRuntime* self, std::int64_t activationId, std::int64_t tick) {
368 return project(vm, self ? self->cancelAbility(activationId, tick)
370 "combat runtime must not be null", "runtime",
371 {}, "combat.squirrel")));
372 });
373 runtime.addFunc("abilityGrant", [vm](ScriptCombatRuntime* self, std::int64_t grantId) {
374 return project(vm, self ? self->abilityGrant(grantId)
376 "combat runtime must not be null", "runtime",
377 {}, "combat.squirrel")));
378 });
379 runtime.addFunc(
380 "matchingAbilities", [vm](ScriptCombatRuntime* self, const std::string& owner, const std::string& eventTag) {
381 return project(vm, self ? self->matchingAbilities(owner, eventTag)
383 "combat runtime must not be null",
384 "runtime", {}, "combat.squirrel")));
385 });
386 runtime.addFunc("state", [vm](ScriptCombatRuntime* self, const std::string& subject) {
387 return project(vm, self ? self->state(subject)
389 "combat runtime must not be null", "runtime",
390 {}, "combat.squirrel")));
391 });
392
393 auto module = table.addClass(name, Combat::create, false);
394 module.addFunc("getName", &Combat::getName);
395 module.addFunc("newRuntime", [vm](Combat*) { return newRuntime(vm); });
396}
397
398void Combat::expose(ssq::Class& cls) {
399 cls.addFunc("getName", &Combat::getName);
400 cls.addFunc("newRuntime", [vm = cls.getHandle()](Combat*) { return newRuntime(vm); });
401}
402
403} // namespace eve::combat
Typed instantaneous combat-damage action contract.
double z
double y
double x
LogicalId target
Value::Object payload
int subject
Definition AnimSmr.cpp:163
Deterministic player/navigation locomotion adapter for combat subjects.
Script-facing combat composition module.
struct SQVM * HSQUIRRELVM
bool changed
Deterministic damage, poise, hit-reaction and knockback resolution.
HSQUIRRELVM vm
Definition ECS.cpp:38
HSQOBJECT cls
Definition ECS.cpp:39
ScriptForceVector acceleration
const GltfImportRequest & request
wgpu::PopErrorScopeStatus status
std::map< unsigned, Colour > definitions
Poco::JSON::Object::Ptr result
bool valid
double radius
Definition MeleeHit.cpp:42
#define Module_IMPL(ModuleName, newExpr)
Definition Module.h:27
std::shared_ptr< OceanGpuSpectrum > owner
std::string error
Definition Package.cpp:174
std::vector< particles::ParticleRecordEvent > events
eve::action::ActionVfxBinding binding
std::string path
Definition PlayHost.cpp:111
Object::Ptr value
bool found
Script-owned projection over ActionRuntime + AbilityRuntime.
std::string text
std::string_view source
std::string damageType
The single Squirrel projection for common Result, Status and Value.
Explicit Value/Owned/Borrowed semantics at the Squirrel boundary.
AbilityInstancingPolicy instancing
Registerable standard action-combat ability archetypes.
SimulationTick tick
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
static Result< Duration > fromSeconds(double seconds)
Convert finite seconds to the nearest nanosecond.
Definition Time.cpp:17
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Definition Status.cpp:19
static SubjectRef fromPersistentId(PersistentId id) noexcept
Wrap a persistent identity without changing its bytes.
Definition SubjectRef.h:32
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
Result< CombatLocomotionAdvance > advance(const SimulationStep &step)
Atomically advance every subject using only the supplied deterministic step.
Result< CombatLocomotionState > state(SubjectRef subject) const
Return an owning state snapshot, or NotFound for a stale subject.
Result< void > stop(SubjectRef subject)
Clear a navigation goal and desired movement for one subject.
Factory module for script-owned deterministic combat runtimes.
Definition Combat.h:18
Result< DamageOutcome > apply(CombatState &target, const DamageRequest &request) const
Resolve and atomically commit one damage request.
Definition Damage.cpp:208
static std::optional< Id128 > parse(std::string_view text) noexcept
Parses canonical UUID text.
Definition Identity.h:150
static constexpr StrongUint64 zero() noexcept
Returns the zero value for this strong type.
Result< std::vector< action::AbilityDefinition > > standardCombatAbilities()
Build twenty validated, registerable standard combat ability definitions.
HitReaction
Typed reaction selected after health and poise are resolved.
Definition Damage.h:27
std::variant< std::monostate, std::int64_t, double, std::string, bool > Value
Definition Database.h:27
Snapshot project(Files files, Object::Ptr stats, std::string defaultProjectId, std::string projectDir)
Build a candidate evidence graph without touching the published snapshot.
eve::Diagnostic Diagnostic
eve::Result< T > Result
ssq::Table projectStatusResult(HSQUIRRELVM vm, const Status &status)
Project a checked native status that carries no payload.
ssq::Table projectResult(HSQUIRRELVM vm, Result< void > &&result)
Consume and project a void native Result using the common schema.
DiagnosticCode
Stable machine-readable diagnostic codes.
Definition Diagnostic.h:47
detail::StrongUint64< detail::SimulationTickTag > SimulationTick
Deterministic simulation time step; it is not wall-clock time.
Definition Time.h:31
static Result< ActionDamageBinding > fromPayload(const Value::Object &payload)
Decode and validate a damage payload without mutating combat state.