载入中...
搜索中...
未找到
WaveDirector.cpp
浏览该文件的文档.
2
3#include "common/Diagnostic.h"
4#include "common/Json.h"
6#include "common/Value.h"
7
8#include <simplesquirrel/simplesquirrel.hpp>
9
10#include <cmath>
11#include <utility>
12
14namespace {
15
16std::string phaseLabel(WavePhase phase) {
17 switch (phase) {
18 case WavePhase::Idle: return "idle";
19 case WavePhase::Preparing: return "preparing";
20 case WavePhase::Spawning: return "spawning";
21 case WavePhase::BetweenWaves: return "betweenWaves";
22 case WavePhase::Completed: return "completed";
23 case WavePhase::Failed: return "failed";
24 }
25 return "idle";
26}
27
28eve::Value spawnEventValue(const WaveSpawnEvent& event) {
30 {"sequence", eve::Value(static_cast<std::int64_t>(event.sequence))},
31 {"waveId", eve::Value(event.waveId)},
32 {"waveIndex", eve::Value(static_cast<std::int64_t>(event.waveIndex))},
33 {"archetypeId", eve::Value(event.archetypeId)},
34 {"entryIndex", eve::Value(static_cast<std::int64_t>(event.entryIndex))},
35 {"spawnIndex", eve::Value(static_cast<std::int64_t>(event.spawnIndex))},
36 });
37}
38
39eve::Value lifecycleEventValue(const WaveLifecycleEvent& event) {
41 {"sequence", eve::Value(static_cast<std::int64_t>(event.sequence))},
42 {"kind", eve::Value(event.kind)},
43 {"waveId", eve::Value(event.waveId)},
44 {"waveIndex", eve::Value(static_cast<std::int64_t>(event.waveIndex))},
45 {"rewardGold", eve::Value(static_cast<std::int64_t>(event.rewardGold))},
46 {"reason", eve::Value(event.reason)},
47 });
48}
49
50eve::Value advanceResultValue(const WaveAdvanceResult& result) {
51 eve::Value::Array spawns;
52 spawns.reserve(result.spawns.size());
53 for (const auto& spawn : result.spawns) spawns.push_back(spawnEventValue(spawn));
55 events.reserve(result.events.size());
56 for (const auto& event : result.events) events.push_back(lifecycleEventValue(event));
58 {"phase", eve::Value(phaseLabel(result.phase))},
59 {"spawnCount", eve::Value(static_cast<std::int64_t>(result.spawns.size()))},
60 {"eventCount", eve::Value(static_cast<std::int64_t>(result.events.size()))},
61 {"spawns", eve::Value(std::move(spawns))},
62 {"events", eve::Value(std::move(events))},
63 });
64}
65
66Result<WaveEntry> decodeEntry(const eve::json::Value& object) {
67 WaveEntry entry;
68 entry.archetypeId = object.getString("archetypeId");
69 entry.count = object.getInt("count", 1);
70 entry.intervalSeconds = object.getDouble("intervalSeconds", 0.5);
71 entry.delaySeconds = object.getDouble("delaySeconds", 0.0);
72 if (entry.archetypeId.empty())
74 "wave entry requires archetypeId", "entry.archetypeId", {},
75 "towerdefense"));
76 if (entry.count <= 0)
78 DiagnosticCode::InvalidArgument, "wave entry count must be positive", "entry.count", {}, "towerdefense"));
79 if (!std::isfinite(entry.intervalSeconds) || entry.intervalSeconds < 0.0)
81 "intervalSeconds must be finite and >= 0",
82 "entry.intervalSeconds", {}, "towerdefense"));
83 if (!std::isfinite(entry.delaySeconds) || entry.delaySeconds < 0.0)
85 "delaySeconds must be finite and >= 0",
86 "entry.delaySeconds", {}, "towerdefense"));
87 return Result<WaveEntry>::success(std::move(entry));
88}
89
90Result<WaveDefinition> decodeWave(const eve::json::Value& object) {
91 WaveDefinition wave;
92 wave.id = object.getString("id");
93 wave.prepSeconds = object.getDouble("prepSeconds", 3.0);
94 wave.rewardGold = object.getInt("rewardGold", 0);
95 if (wave.id.empty())
97 Diagnostic::error(DiagnosticCode::InvalidArgument, "wave requires id", "wave.id", {}, "towerdefense"));
98 if (!std::isfinite(wave.prepSeconds) || wave.prepSeconds < 0.0)
100 "prepSeconds must be finite and >= 0",
101 "wave.prepSeconds", {}, "towerdefense"));
102 if (wave.rewardGold < 0)
104 DiagnosticCode::InvalidArgument, "rewardGold must be >= 0", "wave.rewardGold", {}, "towerdefense"));
105 const eve::json::Value entries = object.get("entries");
106 if (!entries.isArray() || entries.size() == 0)
108 "wave requires a non-empty entries array",
109 "wave.entries", {}, "towerdefense"));
110 wave.entries.reserve(entries.size());
111 for (std::size_t i = 0; i < entries.size(); ++i) {
112 const eve::json::Value entry = entries.at(i);
113 if (!entry.isObject())
115 DiagnosticCode::InvalidArgument, "wave entry must be an object", "wave.entries", {}, "towerdefense"));
116 auto decoded = decodeEntry(entry);
117 if (!decoded) return Result<WaveDefinition>::failure(decoded.status());
118 wave.entries.push_back(std::move(decoded).takeValue());
119 }
120 return Result<WaveDefinition>::success(std::move(wave));
121}
122
123} // namespace
124
126 waves_.clear();
127 phase_ = WavePhase::Idle;
128 waveIndex_ = 0;
129 entryIndex_ = 0;
130 spawnedInEntry_ = 0;
131 remainingPrep_ = 0.0;
132 spawnCooldown_ = 0.0;
133 lastTick_ = 0;
134 hasTick_ = false;
135 eventSequence_ = 0;
136}
137
139 if (definition.id.empty())
141 Diagnostic::error(DiagnosticCode::InvalidArgument, "wave requires id", "wave.id", {}, "towerdefense"));
142 if (definition.entries.empty())
144 "wave requires a non-empty entries array", "wave.entries", {},
145 "towerdefense"));
146 if (!std::isfinite(definition.prepSeconds) || definition.prepSeconds < 0.0)
148 "prepSeconds must be finite and >= 0", "wave.prepSeconds", {},
149 "towerdefense"));
150 for (const auto& entry : definition.entries) {
151 if (entry.archetypeId.empty() || entry.count <= 0 || !std::isfinite(entry.intervalSeconds) ||
152 entry.intervalSeconds < 0.0 || !std::isfinite(entry.delaySeconds) || entry.delaySeconds < 0.0)
154 DiagnosticCode::InvalidArgument, "wave entry fields are invalid", "wave.entries", {}, "towerdefense"));
155 }
156 for (auto& existing : waves_) {
157 if (existing.id == definition.id) {
158 existing = std::move(definition);
160 }
161 }
162 waves_.push_back(std::move(definition));
164}
165
167 std::string error;
168 const eve::json::Document doc = eve::json::Document::parse(std::string(json), &error);
169 if (!doc.valid())
171 error.empty() ? "invalid wave schedule json" : error, "schedule",
172 {}, "towerdefense"));
173 const eve::json::Value root = doc.root();
174 if (!root.isArray())
176 DiagnosticCode::InvalidArgument, "wave schedule must be a JSON array", "schedule", {}, "towerdefense"));
177 clear();
178 int loaded = 0;
179 for (std::size_t i = 0; i < root.size(); ++i) {
180 const eve::json::Value entry = root.at(i);
181 if (!entry.isObject())
183 DiagnosticCode::InvalidArgument, "schedule entries must be objects", "schedule", {}, "towerdefense"));
184 auto decoded = decodeWave(entry);
185 if (!decoded) return Result<int>::failure(decoded.status());
186 auto registered = registerWave(std::move(decoded).takeValue());
187 if (!registered) return Result<int>::failure(registered.status());
188 ++loaded;
189 }
191}
192
193std::string WaveDirector::phaseName() const { return phaseLabel(phase_); }
194
196 if (waves_.empty())
198 "cannot start an empty wave schedule", "schedule", {},
199 "towerdefense"));
200 waveIndex_ = 0;
201 entryIndex_ = 0;
202 spawnedInEntry_ = 0;
203 spawnCooldown_ = 0.0;
204 hasTick_ = false;
205 lastTick_ = 0;
206 eventSequence_ = 0;
207 remainingPrep_ = waves_.front().prepSeconds;
208 phase_ = WavePhase::Preparing;
210}
211
213 phase_ = WavePhase::Idle;
214 waveIndex_ = 0;
215 entryIndex_ = 0;
216 spawnedInEntry_ = 0;
217 remainingPrep_ = 0.0;
218 spawnCooldown_ = 0.0;
219 hasTick_ = false;
220 lastTick_ = 0;
221 eventSequence_ = 0;
223}
224
225void WaveDirector::emitLifecycle(WaveAdvanceResult& out, std::string kind, std::string waveId, int waveIndex,
226 int rewardGold, std::string reason) {
227 WaveLifecycleEvent event;
228 event.sequence = ++eventSequence_;
229 event.kind = std::move(kind);
230 event.waveId = std::move(waveId);
231 event.waveIndex = waveIndex;
232 event.rewardGold = rewardGold;
233 event.reason = std::move(reason);
234 out.events.push_back(std::move(event));
235}
236
237Result<void> WaveDirector::beginWave(int index, WaveAdvanceResult& out) {
238 if (index < 0 || index >= static_cast<int>(waves_.size()))
240 "wave index is out of range", "waveIndex", {}, "towerdefense"));
241 waveIndex_ = index;
242 entryIndex_ = 0;
243 spawnedInEntry_ = 0;
244 const auto& wave = waves_[static_cast<std::size_t>(index)];
245 spawnCooldown_ = wave.entries.empty() ? 0.0 : wave.entries.front().delaySeconds;
246 phase_ = WavePhase::Spawning;
247 emitLifecycle(out, "waveStarted", wave.id, index, 0, {});
249}
250
253 out.phase = phase_;
254 if (!std::isfinite(dt) || dt < 0.0)
256 DiagnosticCode::InvalidArgument, "dt must be finite and >= 0", "advance.dt", {}, "towerdefense"));
257 if (hasTick_ && tick <= lastTick_)
259 DiagnosticCode::PreconditionViolation, "tick must strictly increase", "advance.tick", {}, "towerdefense"));
260 hasTick_ = true;
261 lastTick_ = tick;
262
263 if (phase_ == WavePhase::Idle || phase_ == WavePhase::Completed || phase_ == WavePhase::Failed) {
264 out.phase = phase_;
265 return Result<WaveAdvanceResult>::success(std::move(out));
266 }
267
268 double budget = dt;
269 int spawnsThisAdvance = 0;
270 constexpr int kMaxSpawnsPerAdvance = 256;
271 while (true) {
272 if (phase_ == WavePhase::Preparing || phase_ == WavePhase::BetweenWaves) {
273 if (remainingPrep_ > budget) {
274 remainingPrep_ -= budget;
275 break;
276 }
277 budget -= remainingPrep_;
278 remainingPrep_ = 0.0;
279 auto began = beginWave(waveIndex_, out);
280 if (!began) {
281 phase_ = WavePhase::Failed;
282 emitLifecycle(out, "failed", {}, waveIndex_, 0, began.status().describe());
283 out.phase = phase_;
284 return Result<WaveAdvanceResult>::success(std::move(out));
285 }
286 continue;
287 }
288
289 if (phase_ != WavePhase::Spawning) break;
290 if (waveIndex_ < 0 || waveIndex_ >= static_cast<int>(waves_.size())) {
291 phase_ = WavePhase::Failed;
292 emitLifecycle(out, "failed", {}, waveIndex_, 0, "active wave missing");
293 break;
294 }
295 auto& wave = waves_[static_cast<std::size_t>(waveIndex_)];
296 if (entryIndex_ >= static_cast<int>(wave.entries.size())) {
297 emitLifecycle(out, "waveCompleted", wave.id, waveIndex_, wave.rewardGold, {});
298 const int next = waveIndex_ + 1;
299 if (next >= static_cast<int>(waves_.size())) {
300 phase_ = WavePhase::Completed;
301 emitLifecycle(out, "scheduleCompleted", {}, next, 0, {});
302 break;
303 }
304 waveIndex_ = next;
305 remainingPrep_ = waves_[static_cast<std::size_t>(next)].prepSeconds;
307 continue;
308 }
309
310 auto& entry = wave.entries[static_cast<std::size_t>(entryIndex_)];
311 if (spawnCooldown_ > budget) {
312 spawnCooldown_ -= budget;
313 break;
314 }
315 budget -= spawnCooldown_;
316 spawnCooldown_ = 0.0;
317 if (spawnsThisAdvance >= kMaxSpawnsPerAdvance) break;
318
319 WaveSpawnEvent spawn;
320 spawn.sequence = ++eventSequence_;
321 spawn.waveId = wave.id;
322 spawn.waveIndex = waveIndex_;
323 spawn.archetypeId = entry.archetypeId;
324 spawn.entryIndex = entryIndex_;
325 spawn.spawnIndex = spawnedInEntry_;
326 out.spawns.push_back(std::move(spawn));
327 ++spawnsThisAdvance;
328 ++spawnedInEntry_;
329 if (spawnedInEntry_ >= entry.count) {
330 ++entryIndex_;
331 spawnedInEntry_ = 0;
332 if (entryIndex_ < static_cast<int>(wave.entries.size()))
333 spawnCooldown_ = wave.entries[static_cast<std::size_t>(entryIndex_)].delaySeconds;
334 } else {
335 spawnCooldown_ = entry.intervalSeconds;
336 }
337 // Zero-interval batches may consume no dt; stop once the time budget is exhausted.
338 if (budget <= 0.0 && spawnCooldown_ <= 0.0) break;
339 }
340
341 out.phase = phase_;
342 return Result<WaveAdvanceResult>::success(std::move(out));
343}
344
345DefenseBase::DefenseBase(int lives) : lives_(lives < 0 ? 0 : lives) {}
346
348 if (count <= 0)
349 return Result<int>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument, "leak count must be positive",
350 "leak.count", {}, "towerdefense"));
351 leaks_ += count;
352 if (lives_ > count)
353 lives_ -= count;
354 else
355 lives_ = 0;
356 return Result<int>::success(lives_);
357}
358
360 if (lives < 0)
362 Diagnostic::error(DiagnosticCode::InvalidArgument, "lives must be >= 0", "base.lives", {}, "towerdefense"));
363 lives_ = lives;
364 leaks_ = 0;
366}
367
369
370void TowerDefense::expose(ssq::Table& table) {
371 const HSQUIRRELVM vm = table.getHandle();
372
373 auto director = table.addClass<WaveDirector>(
374 "WaveDirector", std::function<WaveDirector*()>([]() -> WaveDirector* { return new WaveDirector(); }), true);
375 director.addFunc("clear", [](WaveDirector* value) {
376 if (value) value->clear();
377 });
378 director.addFunc("waveCount", [](WaveDirector* value) { return value ? value->waveCount() : 0; });
379 director.addFunc("phaseName", [](WaveDirector* value) { return value ? value->phaseName() : std::string{}; });
380 director.addFunc("waveIndex", [](WaveDirector* value) { return value ? value->waveIndex() : 0; });
381 director.addFunc("remainingPrepSeconds", [](WaveDirector* value) {
382 return value ? static_cast<float>(value->remainingPrepSeconds()) : 0.f;
383 });
384 director.addFunc("loadScheduleJson", [vm](WaveDirector* value, const std::string& json) {
385 if (!value)
387 vm,
389 DiagnosticCode::InvalidArgument, "wave director must not be null", "director", {}, "towerdefense")),
390 [](int count) { return eve::Value(static_cast<std::int64_t>(count)); });
391 return eve::script::projectResult(vm, value->loadScheduleJson(json),
392 [](int count) { return eve::Value(static_cast<std::int64_t>(count)); });
393 });
394 director.addFunc("start", [vm](WaveDirector* value) {
395 if (!value)
397 DiagnosticCode::InvalidArgument, "wave director must not be null",
398 "director", {}, "towerdefense")));
399 return eve::script::projectResult(vm, value->start());
400 });
401 director.addFunc("reset", [vm](WaveDirector* value) {
402 if (!value)
404 DiagnosticCode::InvalidArgument, "wave director must not be null",
405 "director", {}, "towerdefense")));
406 return eve::script::projectResult(vm, value->reset());
407 });
408 director.addFunc("advance", [vm](WaveDirector* value, std::int64_t tick, float dt) {
409 if (!value)
411 vm,
413 DiagnosticCode::InvalidArgument, "wave director must not be null", "director", {}, "towerdefense")),
414 [](const WaveAdvanceResult& result) { return advanceResultValue(result); });
415 return eve::script::projectResult(vm, value->advance(static_cast<std::uint64_t>(tick), static_cast<double>(dt)),
416 [](const WaveAdvanceResult& result) { return advanceResultValue(result); });
417 });
418
419 auto base = table.addClass<DefenseBase>(
420 "DefenseBase",
421 std::function<DefenseBase*(int)>([](int lives) -> DefenseBase* { return new DefenseBase(lives); }), true);
422 base.addFunc("lives", [](DefenseBase* value) { return value ? value->lives() : 0; });
423 base.addFunc("leaks", [](DefenseBase* value) { return value ? value->leaks() : 0; });
424 base.addFunc("isDefeated", [](DefenseBase* value) { return value && value->isDefeated(); });
425 base.addFunc("leak", [vm](DefenseBase* value, int count) {
426 if (!value)
428 vm,
430 "base", {}, "towerdefense")),
431 [](int lives) { return eve::Value(static_cast<std::int64_t>(lives)); });
433 [](int lives) { return eve::Value(static_cast<std::int64_t>(lives)); });
434 });
435 base.addFunc("reset", [vm](DefenseBase* value, int lives) {
436 if (!value)
439 DiagnosticCode::InvalidArgument, "defense base must not be null", "base", {}, "towerdefense")));
440 return eve::script::projectResult(vm, value->reset(lives));
441 });
442
443 auto cls = table.addClass(name, TowerDefense::create, false);
444 expose(cls);
445}
446
447void TowerDefense::expose(ssq::Class& cls) {
448 cls.addFunc("newDirector", [](TowerDefense*) -> WaveDirector* { return new WaveDirector(); });
449 cls.addFunc("newBase", [](TowerDefense*, int lives) -> DefenseBase* { return new DefenseBase(lives); });
450}
451
452} // namespace eve::towerdefense
int root
Definition AnimSmr.cpp:119
std::unordered_map< std::string, QuestRuntime > entries
struct SQVM * HSQUIRRELVM
Stable, structured diagnostics shared by engine modules.
HSQUIRRELVM vm
Definition ECS.cpp:38
HSQOBJECT cls
Definition ECS.cpp:39
std::string name
Definition ECS.cpp:154
Poco::JSON::Object::Ptr result
#define Module_IMPL(ModuleName, newExpr)
Definition Module.h:27
double dt
std::string error
Definition Package.cpp:174
std::vector< particles::ParticleRecordEvent > events
std::unordered_set< std::string > loaded
Definition Plugins.cpp:24
Object::Ptr value
ScriptStructure out
std::string kind
int count
The single Squirrel projection for common Result, Status and Value.
float phase
SimulationTick tick
uint32_t index
Owning, renderer-independent dynamic values.
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Move-only operation result carrying either a value or Status.
Definition Result.h:176
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
The canonical owning dynamic value used by data-facing protocols.
Definition Value.h:31
std::map< std::string, Value > Object
Definition Value.h:34
std::vector< Value > Array
Definition Value.h:33
EVENGINE_API_FOUNDATION public API.
Definition Json.h:137
bool valid() const
Valid.
Definition Json.h:158
static Document parse(const std::string &text, std::string *error=nullptr)
Parse.
Definition Json.cpp:623
Value root() const
Root.
Definition Json.h:160
EVENGINE_API_FOUNDATION public API.
Definition Json.h:39
bool isObject() const
True when object.
Definition Json.cpp:332
Value get(const char *key) const
Returns the value.
Definition Json.cpp:337
Value at(size_t index) const
At.
Definition Json.cpp:359
Result< void > reset(int lives)
Restores the life budget.
DefenseBase(int lives=20)
Constructs with a positive life budget.
Result< int > leak(int count=1)
Applies one or more leaks; lives clamp at zero.
int lives() const noexcept
Script module factory for tower-defense schedule helpers.
Deterministic wave / creep spawn schedule.
Result< WaveAdvanceResult > advance(std::uint64_t tick, double dt)
Advances the schedule by one injected simulation step.
Result< void > registerWave(WaveDefinition definition)
Registers or replaces one wave definition.
Result< int > loadScheduleJson(std::string_view json)
Loads an array of wave objects from JSON text.
int waveIndex() const noexcept
Index of the active/next wave, or waveCount when completed.
Result< void > reset()
Resets progress without clearing definitions.
std::string phaseName() const
Current phase name for scripts/HUD.
Result< void > start()
Starts the schedule from the first wave (Preparing).
void clear()
Clears definitions and resets schedule state.
std::unordered_map< std::string, SkillDefinition > & table()
Definition Skill.cpp:73
ssq::Table projectResult(HSQUIRRELVM vm, Result< void > &&result)
Consume and project a void native Result using the common schema.
WavePhase
Lifecycle phase of a WaveDirector.
Owning result of one advance step.
Data-driven wave definition.
std::vector< WaveEntry > entries
One spawn group inside a wave.
One phase/reward event emitted by advance().
One deterministic spawn request emitted by advance().