载入中...
搜索中...
未找到
Dialogue.cpp
浏览该文件的文档.
1#include "dialogue/Dialogue.h"
5
7#include "common/Capability.h"
10#include "common/utf8.h"
11#include "filesystem/FileData.h"
13#include "i18n/I18n.h"
14#include "scene/Scene.h"
15#include "scene/SceneHost.h"
16
17#include <algorithm>
18#include <cmath>
19#include <cstdio>
20#include <iterator>
21#include <simplesquirrel/simplesquirrel.hpp>
22#include <squirrel.h>
23
24namespace eve::dialogue {
25
27
28namespace {
29
30std::string floatToString(double v) {
31 char buf[64];
32 std::snprintf(buf, sizeof(buf), "%g", v);
33 return buf;
34}
35
36bool squirrelToVarValueAt(HSQUIRRELVM vm, SQInteger index, Dialogue::VarValue &out) {
37 auto converted = eve::script::valueFromSquirrel(vm, index);
38 if (!converted.ok()) {
39 converted.ignore("Dialogue scalar compatibility adapter rejected the value");
40 return false;
41 }
42 Dialogue::VarValue value = std::move(converted).takeValue();
43 if (value.isNull() || value.isArray() || value.isObject()) return false;
44 out = std::move(value);
45 return true;
46}
47
49bool objectToDataValue(HSQUIRRELVM vm, const ssq::Object &object, DataValue &out) {
50 if (!vm || object.isEmpty()) return false;
51 auto converted = eve::script::valueFromSquirrel(object);
52 if (!converted.ok()) {
53 converted.ignore("Dialogue data compatibility adapter rejected the value");
54 return false;
55 }
56 out = std::move(converted).takeValue();
57 return true;
58}
59
60bool objectToVarParams(HSQUIRRELVM vm, const ssq::Object &object,
61 std::unordered_map<std::string, Dialogue::VarValue> &out) {
62 out.clear();
63 if (!vm || object.isEmpty() || object.getType() != ssq::Type::TABLE) return true;
64 auto converted = eve::script::valueFromSquirrel(object);
65 if (!converted.ok()) {
66 converted.ignore("Dialogue parameter compatibility adapter rejected the table");
67 return true;
68 }
69 Dialogue::VarValue value = std::move(converted).takeValue();
70 const auto *fields = value.getIf<eve::Value::Object>();
71 if (!fields) return true;
72 for (const auto &[key, field] : *fields) {
73 if (!field.isNull() && !field.isArray() && !field.isObject()) out[key] = field;
74 }
75 return true;
76}
77
78void pushVarValue(HSQUIRRELVM vm, const Dialogue::VarValue &value) {
79 auto pushed = eve::script::pushValue(vm, value);
80 if (!pushed.ok()) {
81 pushed.ignore("Dialogue scalar compatibility adapter could not push the value");
82 sq_pushnull(vm);
83 }
84}
85
86void pushVarTable(HSQUIRRELVM vm, const std::unordered_map<std::string, Dialogue::VarValue> &vars) {
88 for (const auto &[key, value] : vars) fields.emplace(key, value);
89 auto pushed = eve::script::pushValue(vm, eve::Value(std::move(fields)));
90 if (!pushed.ok()) {
91 pushed.ignore("Dialogue parameter compatibility adapter could not push the table");
92 sq_pushnull(vm);
93 }
94}
95
96std::vector<Dialogue*>& liveDialogues() {
97 static std::vector<Dialogue*> instances;
98 return instances;
99}
100
101StateValue varValueToState(const Dialogue::VarValue& v) {
102 switch (v.type()) {
107 default: break;
108 }
109 return StateValue::null();
110}
111
112bool stateToVarValue(const StateValue& v, Dialogue::VarValue& out) {
113 switch (v.kind()) {
114 case StateValue::Kind::Int: out = Dialogue::VarValue::integer(v.asInt()); return true;
115 case StateValue::Kind::Float: out = Dialogue::VarValue::number(v.asDouble()); return true;
116 case StateValue::Kind::Bool: out = Dialogue::VarValue::boolean(v.asBool()); return true;
117 case StateValue::Kind::String: out = Dialogue::VarValue::string(v.asString()); return true;
118 default: return false;
119 }
120}
121
123class DialogueStateProvider : public eve::caps::IStateProvider {
124public:
125 const char* stateKind() const override { return "dialogue"; }
126
127 Result<Value> capture() override {
128 StateValue arr = StateValue::array();
129 for (Dialogue* d : liveDialogues()) {
130 StateValue sv;
131 if (!d->captureState(sv))
132 return Result<Value>::failure(Diagnostic::error(DiagnosticCode::Failed, "dialogue capture failed"));
133 arr.pushBack(std::move(sv));
134 }
136 }
137
138 Result<void> restore(const Value &value) override {
139 const StateValue in = toLegacyStateValue(value);
140 if (!in.isArray()) {
142 Diagnostic::error(DiagnosticCode::InvalidArgument, "dialogue: expected array of instances"));
143 }
144 const size_t n = std::min(in.arraySize(), liveDialogues().size());
145 for (size_t i = 0; i < n; ++i) {
146 std::string error;
147 if (!liveDialogues()[i]->restoreState(in.at(i), &error))
149 }
150 return Result<void>::success();
151 }
152
153 Result<void> resetToDefaults() override {
154 for (Dialogue* d : liveDialogues()) d->reset();
155 return Result<void>::success();
156 }
157};
158
159struct Register {
160 Register() {
161 static DialogueStateProvider provider;
162 eve::cap::addListener<eve::caps::IStateProvider>(&provider);
163 }
164} g_register;
165
166} // namespace
167
169 liveDialogues().push_back(this);
172}
173
177 liveDialogues().erase(std::remove(liveDialogues().begin(), liveDialogues().end(), this), liveDialogues().end());
178 if (vm_) {
179 for (auto &kv : predicates_) sq_release(vm_, &kv.second);
180 predicates_.clear();
181 }
182}
183
184// ---------------------------------------------------------------------------
185// Variables (global / scene)
186// ---------------------------------------------------------------------------
187
188std::unordered_map<std::string, Dialogue::VarValue> *Dialogue::varsForScope(
189 const std::string &scope) {
190 if (scope == "global") return &globalVars_;
191 if (scope == "scene") return &sceneVars_;
192 return nullptr;
193}
194
195const std::unordered_map<std::string, Dialogue::VarValue> *Dialogue::varsForScope(
196 const std::string &scope) const {
197 if (scope == "global") return &globalVars_;
198 if (scope == "scene") return &sceneVars_;
199 return nullptr;
200}
201
202bool Dialogue::setVarValue(const std::string &name, const VarValue &value,
203 const std::string &scope) {
204 auto *m = varsForScope(scope);
205 if (!m || name.empty()) return false;
206 (*m)[name] = value;
207 return true;
208}
209
210bool Dialogue::setVar(const std::string &name, ssq::Object value, const std::string &scope) {
211 if (!vm_) return false;
212 const SQInteger top = sq_gettop(vm_);
213 sq_pushobject(vm_, value.getRaw());
214 VarValue v;
215 const bool ok = squirrelToVarValueAt(vm_, -1, v);
216 sq_settop(vm_, top);
217 if (!ok) return false;
218 return setVarValue(name, v, scope);
219}
220
221Dialogue::VarValue Dialogue::getVarValue(const std::string &name, const std::string &scope) const {
222 const auto *m = varsForScope(scope);
223 if (!m) return VarValue::string("");
224 const auto it = m->find(name);
225 return it == m->end() ? VarValue::string("") : it->second;
226}
227
228std::string Dialogue::getVarType(const std::string &name, const std::string &scope) const {
229 return hasVar(name, scope) ? getVarValue(name, scope).typeName() : "";
230}
231
232int Dialogue::getVarInt(const std::string &name, int defaultValue, const std::string &scope) const {
233 const VarValue v = getVarValue(name, scope);
234 if (v.type() == VarValue::Type::Int) return int(v.asInt());
235 if (v.type() == VarValue::Type::Float) return int(v.asDouble());
236 if (v.type() == VarValue::Type::Bool) return v.asBool() ? 1 : 0;
237 return defaultValue;
238}
239
240float Dialogue::getVarFloat(const std::string &name, float defaultValue,
241 const std::string &scope) const {
242 const VarValue v = getVarValue(name, scope);
243 if (v.type() == VarValue::Type::Int) return float(v.asInt());
244 if (v.type() == VarValue::Type::Float) return float(v.asDouble());
245 if (v.type() == VarValue::Type::Bool) return v.asBool() ? 1.f : 0.f;
246 return defaultValue;
247}
248
249bool Dialogue::getVarBool(const std::string &name, bool defaultValue,
250 const std::string &scope) const {
251 const VarValue v = getVarValue(name, scope);
252 if (v.type() == VarValue::Type::Int) return v.asInt() != 0;
253 if (v.type() == VarValue::Type::Float) return v.asDouble() != 0.0;
254 if (v.type() == VarValue::Type::Bool) return v.asBool();
255 return defaultValue;
256}
257
258std::string Dialogue::getVarString(const std::string &name, const std::string &defaultValue,
259 const std::string &scope) const {
260 const VarValue v = getVarValue(name, scope);
261 return v.type() == VarValue::Type::String ? v.asString() : defaultValue;
262}
263
264bool Dialogue::hasVar(const std::string &name, const std::string &scope) const {
265 const auto *m = varsForScope(scope);
266 return m && m->find(name) != m->end();
267}
268
269bool Dialogue::clearVar(const std::string &name, const std::string &scope) {
270 auto *m = varsForScope(scope);
271 return m && m->erase(name) > 0;
272}
273
274void Dialogue::clearVars(const std::string &scope) {
275 if (scope == "global") {
276 globalVars_.clear();
277 } else if (scope == "scene") {
278 sceneVars_.clear();
279 } else if (scope == "all") {
280 globalVars_.clear();
281 sceneVars_.clear();
282 }
283}
284
285// ---------------------------------------------------------------------------
286// Conditions (structured tables + script predicates)
287// ---------------------------------------------------------------------------
288
289bool Dialogue::registerCondition(const std::string &name, ssq::Object fn) {
290 if (!vm_ || name.empty()) return false;
291 HSQOBJECT raw = fn.getRaw();
292 if (raw._type == OT_NULL) return unregisterCondition(name);
293 if (raw._type != OT_CLOSURE && raw._type != OT_NATIVECLOSURE) return false;
294 const auto it = predicates_.find(name);
295 if (it != predicates_.end()) {
296 sq_release(vm_, &it->second);
297 predicates_.erase(it);
298 }
299 sq_addref(vm_, &raw);
300 predicates_[name] = raw;
301 return true;
302}
303
304bool Dialogue::unregisterCondition(const std::string &name) {
305 const auto it = predicates_.find(name);
306 if (it == predicates_.end()) return false;
307 if (vm_) sq_release(vm_, &it->second);
308 predicates_.erase(it);
309 return true;
310}
311
312bool Dialogue::evalCondition(ssq::Object table) {
313 DataValue v;
314 if (!objectToDataValue(vm_, table, v)) return false;
315 return evalConditionData(v);
316}
317
318bool Dialogue::parseCondition(const DataValue &v, Condition &out, std::string &error) {
319 if (v.kind() == DataValue::Kind::Array) {
320 out.kind = Condition::Kind::All;
321 for (size_t i = 0; i < v.arraySize(); ++i) {
322 const auto &item = v.at(i);
323 Condition child;
324 if (!parseCondition(item, child, error)) return false;
325 out.children.push_back(std::move(child));
326 }
327 return true;
328 }
329 if (v.kind() != DataValue::Kind::Object) {
330 error = "condition must be a table";
331 return false;
332 }
333 if (const DataValue *script = v.find("script")) {
334 if (script->kind() != DataValue::Kind::String) {
335 error = "script condition name must be a string";
336 return false;
337 }
338 out.kind = Condition::Kind::Script;
339 out.script = script->asString();
340 return true;
341 }
342 if (const DataValue *all = v.find("all")) {
343 if (all->kind() != DataValue::Kind::Array) {
344 error = "all must be an array";
345 return false;
346 }
347 out.kind = Condition::Kind::All;
348 for (size_t i = 0; i < all->arraySize(); ++i) {
349 const auto &item = all->at(i);
350 Condition child;
351 if (!parseCondition(item, child, error)) return false;
352 out.children.push_back(std::move(child));
353 }
354 return true;
355 }
356 if (const DataValue *any = v.find("any")) {
357 if (any->kind() != DataValue::Kind::Array) {
358 error = "any must be an array";
359 return false;
360 }
361 out.kind = Condition::Kind::Any;
362 for (size_t i = 0; i < any->arraySize(); ++i) {
363 const auto &item = any->at(i);
364 Condition child;
365 if (!parseCondition(item, child, error)) return false;
366 out.children.push_back(std::move(child));
367 }
368 return true;
369 }
370 if (const DataValue *notc = v.find("not")) {
371 out.kind = Condition::Kind::Not;
372 out.children.emplace_back();
373 return parseCondition(*notc, out.children.back(), error);
374 }
375 if (const DataValue *var = v.find("var")) {
376 const DataValue *op = v.find("op");
377 if (var->kind() != DataValue::Kind::String || !op || op->kind() != DataValue::Kind::String) {
378 error = "var/op condition requires string var and op";
379 return false;
380 }
381 static const char *kOps[] = {"eq", "ne", "gt", "ge", "lt", "le", "has", "missing"};
382 const std::string opStr = op->asString();
383 if (std::find(std::begin(kOps), std::end(kOps), opStr) == std::end(kOps)) {
384 error = "unknown condition op: " + opStr;
385 return false;
386 }
387 out.kind = Condition::Kind::Cmp;
388 out.var = var->asString();
389 out.op = opStr;
390 out.value = VarValue::string("");
391 if (const DataValue *val = v.find("value")) {
392 switch (val->kind()) {
393 case DataValue::Kind::Int: out.value = VarValue::integer(val->asInt()); break;
394 case DataValue::Kind::Float: out.value = VarValue::number(val->asDouble()); break;
395 case DataValue::Kind::Bool: out.value = VarValue::boolean(val->asBool()); break;
396 case DataValue::Kind::String: out.value = VarValue::string(val->asString()); break;
397 default:
398 break;
399 }
400 }
401 return true;
402 }
403 error = "unrecognized condition table";
404 return false;
405}
406
407bool Dialogue::compareEq(const VarValue &a, const VarValue &b) const {
408 if (a.isNumeric() && b.isNumeric()) {
409 const double x = a.type() == VarValue::Type::Int ? double(a.asInt()) : a.asDouble();
410 const double y = b.type() == VarValue::Type::Int ? double(b.asInt()) : b.asDouble();
411 return x == y;
412 }
413 if (a.type() == VarValue::Type::Bool && b.type() == VarValue::Type::Bool) return a.asBool() == b.asBool();
414 if (a.type() == VarValue::Type::String && b.type() == VarValue::Type::String) return a.asString() == b.asString();
415 return false;
416}
417
418bool Dialogue::compareOrder(const std::string &op, const VarValue &a, const VarValue &b) const {
419 if (!a.isNumeric() || !b.isNumeric()) return false;
420 const double x = a.type() == VarValue::Type::Int ? double(a.asInt()) : a.asDouble();
421 const double y = b.type() == VarValue::Type::Int ? double(b.asInt()) : b.asDouble();
422 if (op == "gt") return x > y;
423 if (op == "ge") return x >= y;
424 if (op == "lt") return x < y;
425 if (op == "le") return x <= y;
426 return false;
427}
428
429bool Dialogue::evalConditionInternal(const Condition &c,
430 const std::unordered_map<std::string, VarValue> &merged,
431 const std::unordered_map<std::string, VarValue> &params,
432 const std::string &lineId) const {
433 switch (c.kind) {
434 case Condition::Kind::Always:
435 return true;
436 case Condition::Kind::Cmp: {
437 const auto it = merged.find(c.var);
438 const bool present = it != merged.end();
439 if (c.op == "has") return present;
440 if (c.op == "missing") return !present;
441 if (!present) return false;
442 if (c.op == "eq") return compareEq(it->second, c.value);
443 if (c.op == "ne") return !compareEq(it->second, c.value);
444 return compareOrder(c.op, it->second, c.value);
445 }
446 case Condition::Kind::All:
447 for (const auto &child : c.children)
448 if (!evalConditionInternal(child, merged, params, lineId)) return false;
449 return true;
450 case Condition::Kind::Any:
451 for (const auto &child : c.children)
452 if (evalConditionInternal(child, merged, params, lineId)) return true;
453 return false;
454 case Condition::Kind::Not:
455 return c.children.empty() ||
456 !evalConditionInternal(c.children.front(), merged, params, lineId);
457 case Condition::Kind::Script:
458 return evalScriptPredicate(c.script, merged, params, lineId);
459 }
460 return false;
461}
462
464 Condition c;
465 std::string error;
466 if (!parseCondition(cond, c, error)) return false;
467 return evalConditionInternal(c, mergedVars({}), {}, "");
468}
469
470bool Dialogue::evalScriptPredicate(const std::string &name,
471 const std::unordered_map<std::string, VarValue> &merged,
472 const std::unordered_map<std::string, VarValue> &params,
473 const std::string &lineId) const {
474 if (!vm_) return false;
475 const auto it = predicates_.find(name);
476 if (it == predicates_.end()) return false;
477
478 const SQInteger top = sq_gettop(vm_);
479 // The closure is pushed as fn + this + ctx. `ctx` is built in place on the VM stack,
480 // so script::callFunction's value-argument form does not fit here; the count is
481 // derived from the stack instead of written by hand, which is the same rule. Writing
482 // 1 here previously bound ctx as `this`, leaving the callback zero arguments and
483 // failing the arity check, so every registered condition silently evaluated false.
484 sq_pushobject(vm_, it->second); // fn
485 sq_pushroottable(vm_); // this
486 sq_newtable(vm_); // ctx
487
488 sq_pushstring(vm_, "vars", -1);
489 pushVarTable(vm_, merged);
490 sq_newslot(vm_, -3, SQFalse); // ctx at -3, key at -2, var table at -1
491
492 sq_pushstring(vm_, "params", -1);
493 pushVarTable(vm_, params);
494 sq_newslot(vm_, -3, SQFalse);
495
496 sq_pushstring(vm_, "lineId", -1);
497 sq_pushstring(vm_, lineId.c_str(), lineId.size());
498 sq_newslot(vm_, -3, SQFalse);
499
500 const SQInteger paramCount = sq_gettop(vm_) - top - 1; // receiver + ctx, excluding fn
501 if (SQ_FAILED(sq_call(vm_, paramCount, SQTrue, SQTrue))) {
502 sq_settop(vm_, top);
503 return false;
504 }
505 SQBool result = SQFalse;
506 if (SQ_FAILED(sq_getbool(vm_, -1, &result))) {
507 sq_settop(vm_, top);
508 return false;
509 }
510 sq_settop(vm_, top);
511 return result != 0;
512}
513
514// ---------------------------------------------------------------------------
515// Content pools
516// ---------------------------------------------------------------------------
517
518int Dialogue::loadPoolsFromTable(ssq::Object table) {
520 if (!objectToDataValue(vm_, table, root)) {
521 lastPoolsError_ = "pools root must be a table";
522 return 0;
523 }
524 return loadPoolsFromData(root);
525}
526
527bool Dialogue::parseLineData(const std::string &poolId, const DataValue &v, int index, Line &line,
528 std::string &error) {
529 if (v.kind() != DataValue::Kind::Object) {
530 error = "line must be a table";
531 return false;
532 }
533 if (const DataValue *id = v.find("id"))
534 if (id->kind() == DataValue::Kind::String) line.id = id->asString();
535 if (line.id.empty()) line.id = poolId + "." + std::to_string(index);
536
537 if (const DataValue *sp = v.find("speaker"))
538 if (sp->kind() == DataValue::Kind::String) line.speaker = sp->asString();
539 if (const DataValue *tx = v.find("text"))
540 if (tx->kind() == DataValue::Kind::String) line.text = tx->asString();
541 if (const DataValue *ik = v.find("i18n"))
542 if (ik->kind() == DataValue::Kind::String) line.i18nKey = ik->asString();
543 if (line.text.empty() && line.i18nKey.empty()) {
544 error = "line '" + line.id + "': text or i18n required";
545 return false;
546 }
547
548 if (const DataValue *w = v.find("weight")) {
549 if (w->kind() == DataValue::Kind::Int)
550 line.weight = double(w->asInt());
551 else if (w->kind() == DataValue::Kind::Float)
552 line.weight = w->asDouble();
553 else {
554 error = "line '" + line.id + "': weight must be a number";
555 return false;
556 }
557 }
558
559 if (const DataValue *when = v.find("when")) {
560 if (!parseCondition(*when, line.when, error)) {
561 error = "line '" + line.id + "': " + error;
562 return false;
563 }
564 }
565
566 if (const DataValue *meta = v.find("meta")) {
567 if (meta->kind() != DataValue::Kind::Object) {
568 error = "line '" + line.id + "': meta must be a table";
569 return false;
570 }
571 const auto *fields = meta->getIf<DataValue::Object>();
572 for (const auto &mkv : *fields) {
573 std::string val;
574 switch (mkv.second.kind()) {
575 case DataValue::Kind::String: val = mkv.second.asString(); break;
576 case DataValue::Kind::Int: val = std::to_string(mkv.second.asInt()); break;
577 case DataValue::Kind::Float: val = floatToString(mkv.second.asDouble()); break;
578 case DataValue::Kind::Bool: val = mkv.second.asBool() ? "true" : "false"; break;
579 default:
580 break;
581 }
582 line.meta[mkv.first] = val;
583 }
584 }
585
586 if (const DataValue *tags = v.find("tags")) {
587 if (tags->kind() != DataValue::Kind::Array) {
588 error = "line '" + line.id + "': tags must be an array";
589 return false;
590 }
591 for (size_t i = 0; i < tags->arraySize(); ++i) {
592 const auto &t = tags->at(i);
593 if (t.kind() == DataValue::Kind::String) line.tags.push_back(t.asString());
594 }
595 }
596 return true;
597}
598
599int Dialogue::loadPoolsFromData(const DataValue &root) { return applyPoolsFromData(root, false); }
600
601int Dialogue::replacePoolsFromData(const DataValue& root) { return applyPoolsFromData(root, true); }
602
603int Dialogue::applyPoolsFromData(const DataValue &root, bool replace) {
604 lastPoolsError_.clear();
605 if (root.kind() != DataValue::Kind::Object) {
606 lastPoolsError_ = "pools root must be an object";
607 return 0;
608 }
609 const DataValue *pools = root.find("pools");
610 if (!pools || pools->kind() != DataValue::Kind::Object) {
611 lastPoolsError_ = "missing pools object";
612 return 0;
613 }
614
615 int registered = 0;
616 std::vector<Pool> candidate = replace ? std::vector<Pool>{} : pools_;
617 const auto *poolFields = pools->getIf<DataValue::Object>();
618 for (const auto &kv : *poolFields) {
619 Pool pool;
620 pool.id = kv.first;
621 if (kv.second.kind() != DataValue::Kind::Object) {
622 lastPoolsError_ = "pool '" + kv.first + "': expected object";
623 return 0;
624 }
625 if (const DataValue *nr = kv.second.find("noRepeat")) {
626 if (nr->kind() == DataValue::Kind::Int)
627 pool.noRepeat = int(nr->asInt());
628 else if (nr->kind() == DataValue::Kind::Float)
629 pool.noRepeat = int(nr->asDouble());
630 if (pool.noRepeat < 0) pool.noRepeat = 0;
631 }
632 const DataValue *lines = kv.second.find("lines");
633 if (!lines || lines->kind() != DataValue::Kind::Array) {
634 lastPoolsError_ = "pool '" + kv.first + "': missing lines array";
635 return 0;
636 }
637 int lineIndex = 1;
638 for (size_t i = 0; i < lines->arraySize(); ++i) {
639 const auto &lv = lines->at(i);
640 Line line;
641 std::string error;
642 if (!parseLineData(pool.id, lv, lineIndex, line, error)) {
643 lastPoolsError_ = error;
644 return 0;
645 }
646 pool.lines.push_back(std::move(line));
647 ++lineIndex;
648 }
649 auto existing = std::find_if(candidate.begin(), candidate.end(),
650 [&](const Pool& item) { return item.id == pool.id; });
651 if (existing != candidate.end()) *existing = std::move(pool);
652 else candidate.push_back(std::move(pool));
653 ++registered;
654 }
655 pools_ = std::move(candidate);
656 return registered;
657}
658
659void Dialogue::clearPools() { pools_.clear(); }
660
661int Dialogue::getPoolCount() const { return int(pools_.size()); }
662
663std::string Dialogue::getPoolId(int index) const {
664 if (index < 0 || size_t(index) >= pools_.size()) return {};
665 return pools_[size_t(index)].id;
666}
667
668bool Dialogue::hasPool(const std::string &id) const { return findPool(id) != nullptr; }
669
670Dialogue::Pool *Dialogue::findPool(const std::string &id) {
671 for (auto &p : pools_)
672 if (p.id == id) return &p;
673 return nullptr;
674}
675
676const Dialogue::Pool *Dialogue::findPool(const std::string &id) const {
677 for (const auto &p : pools_)
678 if (p.id == id) return &p;
679 return nullptr;
680}
681
682Dialogue::Line *Dialogue::findLine(const std::string &id) {
683 for (auto &p : pools_)
684 for (auto &l : p.lines)
685 if (l.id == id) return &l;
686 return nullptr;
687}
688
689const Dialogue::Line *Dialogue::findLine(const std::string &id) const {
690 for (const auto &p : pools_)
691 for (const auto &l : p.lines)
692 if (l.id == id) return &l;
693 return nullptr;
694}
695
696// ---------------------------------------------------------------------------
697// Merged variable context / interpolation
698// ---------------------------------------------------------------------------
699
700std::unordered_map<std::string, Dialogue::VarValue> Dialogue::mergedVars(
701 const std::unordered_map<std::string, VarValue> &params) const {
702 std::unordered_map<std::string, VarValue> m = globalVars_;
703 for (const auto &kv : sceneVars_) m[kv.first] = kv.second;
704 for (const auto &kv : params) m[kv.first] = kv.second;
705 return m;
706}
707
708std::unordered_map<std::string, std::string> Dialogue::stringParams(
709 const std::unordered_map<std::string, VarValue> &vars) const {
710 std::unordered_map<std::string, std::string> out;
711 for (const auto &kv : vars) out[kv.first] = kv.second.toString();
712 return out;
713}
714
715std::string Dialogue::interpolate(const std::string &tpl,
716 const std::unordered_map<std::string, VarValue> &vars) const {
717 std::string out;
718 out.reserve(tpl.size());
719 for (size_t i = 0; i < tpl.size();) {
720 if (tpl[i] == '{') {
721 const size_t close = tpl.find('}', i + 1);
722 if (close != std::string::npos) {
723 const std::string name = tpl.substr(i + 1, close - i - 1);
724 const auto it = vars.find(name);
725 if (it != vars.end()) {
726 out += it->second.toString();
727 i = close + 1;
728 continue;
729 }
730 }
731 }
732 out += tpl[i++];
733 }
734 return out;
735}
736
737// ---------------------------------------------------------------------------
738// RNG / weighted selection / play
739// ---------------------------------------------------------------------------
740
741uint32_t Dialogue::nextRandom() {
742 uint32_t x = rngState_;
743 x ^= x << 13;
744 x ^= x >> 17;
745 x ^= x << 5;
746 rngState_ = x;
747 return x;
748}
749
750double Dialogue::nextUnit() { return (nextRandom() & 0xFFFFFFu) / 16777216.0; }
751
753 rngState_ = seed ? uint32_t(seed) : 1u;
754 for (auto &p : pools_) p.recent.clear();
755}
756
757std::string Dialogue::pickLine(const std::string &poolId, ssq::Object params) {
758 std::unordered_map<std::string, VarValue> p;
759 objectToVarParams(vm_, params, p);
760 return pickLineWithParams(poolId, p);
761}
762
764 const std::string &poolId, const std::unordered_map<std::string, VarValue> &params) {
765 Pool *pool = findPool(poolId);
766 if (!pool) return "";
767 const auto merged = mergedVars(params);
768
769 auto collect = [&](std::vector<size_t> &out, bool allowRecent) {
770 for (size_t i = 0; i < pool->lines.size(); ++i) {
771 const Line &line = pool->lines[i];
772 if (line.weight <= 0.0) continue;
773 if (!evalConditionInternal(line.when, merged, params, line.id)) continue;
774 if (!allowRecent && pool->noRepeat > 0 &&
775 std::find(pool->recent.begin(), pool->recent.end(), i) != pool->recent.end())
776 continue;
777 out.push_back(i);
778 }
779 };
780
781 std::vector<size_t> candidates;
782 collect(candidates, false);
783 if (candidates.empty()) collect(candidates, true); // noRepeat must not deadlock
784 if (candidates.empty()) return "";
785
786 double total = 0.0;
787 for (const size_t i : candidates) total += pool->lines[i].weight;
788 double roll = nextUnit() * total;
789 size_t picked = candidates.front();
790 double acc = 0.0;
791 for (const size_t i : candidates) {
792 acc += pool->lines[i].weight;
793 if (roll < acc) {
794 picked = i;
795 break;
796 }
797 }
798 if (pool->noRepeat > 0) {
799 pool->recent.push_back(picked);
800 if (pool->recent.size() > size_t(pool->noRepeat)) pool->recent.erase(pool->recent.begin());
801 }
802 return pool->lines[picked].id;
803}
804
805bool Dialogue::playLine(const std::string &lineId, ssq::Object params) {
806 std::unordered_map<std::string, VarValue> p;
807 objectToVarParams(vm_, params, p);
808 return playLineWithParams(lineId, p);
809}
810
811bool Dialogue::playLineWithParams(const std::string &lineId,
812 const std::unordered_map<std::string, VarValue> &params) {
813 Line *line = findLine(lineId);
814 if (!line) return false;
815 const auto merged = mergedVars(params);
816
817 std::string text;
818 if (!line->text.empty()) {
819 text = interpolate(line->text, merged);
820 } else {
821 auto *i18n = eve::ModuleManager::getInstance<eve::i18n::I18n>("I18n");
822 text = i18n ? i18n->getWithParams(line->i18nKey, stringParams(merged)) : line->i18nKey;
823 }
824
825 if (line->speaker.empty()) narrate(text);
826 else say(line->speaker, text);
827
828 currentLineId_ = line->id;
829 currentLineMeta_ = line->meta;
830 currentLineTags_ = line->tags;
831 applyLineMeta(*line);
832 return true;
833}
834
835bool Dialogue::playPool(const std::string &poolId, ssq::Object params) {
836 std::unordered_map<std::string, VarValue> p;
837 objectToVarParams(vm_, params, p);
838 return playPoolWithParams(poolId, p);
839}
840
841bool Dialogue::playPoolWithParams(const std::string &poolId,
842 const std::unordered_map<std::string, VarValue> &params) {
843 const std::string lineId = pickLineWithParams(poolId, params);
844 return !lineId.empty() && playLineWithParams(lineId, params);
845}
846
847std::string Dialogue::getCurrentLineMeta(const std::string &field) const {
848 const auto it = currentLineMeta_.find(field);
849 return it == currentLineMeta_.end() ? std::string{} : it->second;
850}
851
852std::vector<std::string> Dialogue::getCurrentLineTags() const { return currentLineTags_; }
853
854void Dialogue::applyLineMeta(const Line &line) {
855 if (line.speaker.empty()) return;
856 const auto expr = line.meta.find("expression");
857 const auto motion = line.meta.find("motion");
858 if (expr == line.meta.end() && motion == line.meta.end()) return;
859 Character *c = findCharacter(line.speaker);
860 if (!c || !c->avatar) return;
861 if (expr != line.meta.end()) c->avatar->setExpression(expr->second);
862 if (motion != line.meta.end()) c->avatar->setMotion(motion->second);
863}
864
865// ---------------------------------------------------------------------------
866// Scene-scoped variables: clear when the selected Scene host changes
867// ---------------------------------------------------------------------------
868
869void Dialogue::pollSceneChange() {
870 auto *scn = eve::ModuleManager::getInstance<eve::scene::Scene>("Scene");
871 if (!scn) return;
872 eve::scene::SceneHost *host = scn->current();
873 const std::string name = host ? host->getName() : "";
874 if (!name.empty() && name != lastSceneName_) sceneVars_.clear();
875 if (!name.empty()) lastSceneName_ = name;
876}
877
878Dialogue::Character *Dialogue::findCharacter(const std::string &id) {
879 for (auto &c : characters_)
880 if (c.id == id) return &c;
881 return nullptr;
882}
883
884const Dialogue::Character *Dialogue::findCharacter(const std::string &id) const {
885 for (const auto &c : characters_)
886 if (c.id == id) return &c;
887 return nullptr;
888}
889
890bool Dialogue::registerCharacter(const std::string &id, const std::string &displayName) {
891 if (id.empty()) return false;
892 if (auto *c = findCharacter(id)) {
893 c->displayName = displayName.empty() ? id : displayName;
894 return true;
895 }
896 Character c;
897 c.id = id;
898 c.displayName = displayName.empty() ? id : displayName;
899 characters_.push_back(c);
900 return true;
901}
902
903bool Dialogue::hasCharacter(const std::string &id) const { return findCharacter(id) != nullptr; }
904
905std::string Dialogue::getDisplayName(const std::string &id) const {
906 const Character *c = findCharacter(id);
907 return c ? c->displayName : std::string{};
908}
909
910bool Dialogue::bindAvatar(const std::string &id, avatar::AvatarInstance *av) {
911 Character *c = findCharacter(id);
912 if (!c) return false;
913 // Drop the previous binding's destroy hook before replacing the pointer,
914 // otherwise the old avatar's hook would null the new binding on destroy.
915 if (c->avatar && c->avatarHook) {
916 c->avatar->removeDestroyHook(*c->avatarHook);
917 c->avatarHook.reset();
918 }
919 c->avatar = av;
920 if (av) {
921 c->avatarHook = av->addDestroyHook([this, key = id](avatar::AvatarInstance*) {
922 if (Character *ch = findCharacter(key))
923 ch->avatar = nullptr;
924 });
925 }
926 return true;
927}
928
929avatar::AvatarInstance *Dialogue::getAvatar(const std::string &id) const {
930 const Character *c = findCharacter(id);
931 return c ? c->avatar : nullptr;
932}
933
934int Dialogue::getCharacterCount() const { return int(characters_.size()); }
935
936std::string Dialogue::getCharacterId(int index) const {
937 if (index < 0 || size_t(index) >= characters_.size()) return {};
938 return characters_[size_t(index)].id;
939}
940
941bool Dialogue::show(const std::string &id, const std::string &slot) {
942 Character *c = findCharacter(id);
943 if (!c) return false;
944 c->shown = true;
945 c->slot = slot.empty() ? "center" : slot;
946 if (c->avatar) c->avatar->setVisible(true);
947 return true;
948}
949
950bool Dialogue::hide(const std::string &id) {
951 Character *c = findCharacter(id);
952 if (!c) return false;
953 c->shown = false;
954 if (c->avatar) c->avatar->setVisible(false);
955 return true;
956}
957
958bool Dialogue::isShown(const std::string &id) const {
959 const Character *c = findCharacter(id);
960 return c && c->shown;
961}
962
963std::string Dialogue::getSlot(const std::string &id) const {
964 const Character *c = findCharacter(id);
965 return c ? c->slot : std::string{};
966}
967
968void Dialogue::setSlotX(const std::string &slot, float xNorm) {
969 if (slot.empty()) return;
970 slotX_[slot] = xNorm;
971}
972
973float Dialogue::getSlotX(const std::string &slot) const {
974 auto it = slotX_.find(slot);
975 if (it != slotX_.end()) return it->second;
976 if (slot == "left") return 0.25f;
977 if (slot == "right") return 0.75f;
978 if (slot == "center") return 0.5f;
979 return 0.5f;
980}
981
982bool Dialogue::setExpression(const std::string &id, const std::string &expression) {
983 Character *c = findCharacter(id);
984 if (!c || !c->avatar) return false;
985 c->avatar->setExpression(expression);
986 return true;
987}
988
989bool Dialogue::setMotion(const std::string &id, const std::string &motion) {
990 Character *c = findCharacter(id);
991 if (!c || !c->avatar) return false;
992 c->avatar->setMotion(motion);
993 return true;
994}
995
996void Dialogue::syncStage(float stageWidth, float stageHeight) {
997 (void)stageHeight;
998 for (Character &c : characters_) {
999 if (!c.avatar) continue;
1000 c.avatar->setVisible(c.shown);
1001 if (!c.shown) {
1002 c.avatar->sync();
1003 continue;
1004 }
1005 const float xn = getSlotX(c.slot);
1006 const float x = xn * stageWidth;
1007 // Keep current Y; only drive X from slot.
1008 c.avatar->setPosition(x, c.avatar->getY());
1009 c.avatar->sync();
1010 }
1011}
1012
1013void Dialogue::beginLine(const std::string &speakerId, const std::string &text) {
1014 speakerId_ = speakerId;
1015 fullText_ = text;
1016 typed_ = 0.f;
1017 selectedChoiceId_.clear();
1018 lipSyncTime_ = 0.f;
1019 if (typeSpeed_ <= 0.f) {
1020 typed_ = float(utf8_codepoint_count(fullText_));
1021 phase_ = Phase::WaitingAdvance;
1022 lipSyncValue_ = 0.f;
1023 } else {
1024 phase_ = Phase::Typing;
1025 }
1026}
1027
1028void Dialogue::say(const std::string &speakerId, const std::string &text) {
1029 beginLine(speakerId, text);
1030}
1031
1032void Dialogue::narrate(const std::string &text) { beginLine("", text); }
1033
1034void Dialogue::setTypeSpeed(float charsPerSecond) { typeSpeed_ = charsPerSecond; }
1035
1037 if (phase_ == Phase::Typing) {
1038 typed_ = float(utf8_codepoint_count(fullText_));
1039 phase_ = Phase::WaitingAdvance;
1040 }
1041}
1042
1043bool Dialogue::isTyping() const { return phase_ == Phase::Typing; }
1044
1045bool Dialogue::isWaitingAdvance() const { return phase_ == Phase::WaitingAdvance; }
1046
1047bool Dialogue::isIdle() const { return phase_ == Phase::Idle; }
1048
1050 if (phase_ == Phase::Typing) {
1051 skipTyping();
1052 return;
1053 }
1054 if (phase_ == Phase::WaitingAdvance) phase_ = Phase::Idle;
1055}
1056
1057std::string Dialogue::getSpeakerName() const {
1058 if (speakerId_.empty()) return {};
1059 return getDisplayName(speakerId_);
1060}
1061
1062std::string Dialogue::getVisibleText() const {
1063 if (fullText_.empty()) return {};
1064 const size_t total = utf8_codepoint_count(fullText_);
1065 size_t n = size_t(std::floor(typed_ + 1e-4f));
1066 if (n == 0) return {};
1067 if (n >= total) return fullText_;
1068 return fullText_.substr(0, utf8_byte_offset_for_codepoints(fullText_, n));
1069}
1070
1071std::string Dialogue::getPhase() const {
1072 switch (phase_) {
1073 case Phase::Idle:
1074 return "idle";
1075 case Phase::Typing:
1076 return "typing";
1077 case Phase::WaitingAdvance:
1078 return "waiting_advance";
1079 case Phase::WaitingChoice:
1080 return "waiting_choice";
1081 }
1082 return "idle";
1083}
1084
1086 choices_.clear();
1087 selectedChoiceId_.clear();
1088}
1089
1090bool Dialogue::addChoice(const std::string &id, const std::string &label) {
1091 if (id.empty()) return false;
1092 for (auto &ch : choices_) {
1093 if (ch.id == id) {
1094 ch.label = label;
1095 return true;
1096 }
1097 }
1098 choices_.push_back(Choice{id, label});
1099 return true;
1100}
1101
1103 if (choices_.empty()) {
1104 phase_ = Phase::Idle;
1105 return;
1106 }
1107 if (phase_ == Phase::Typing) skipTyping();
1108 phase_ = Phase::WaitingChoice;
1109}
1110
1111bool Dialogue::isWaitingChoice() const { return phase_ == Phase::WaitingChoice; }
1112
1113int Dialogue::getChoiceCount() const { return int(choices_.size()); }
1114
1115std::string Dialogue::getChoiceId(int index) const {
1116 if (index < 0 || size_t(index) >= choices_.size()) return {};
1117 return choices_[size_t(index)].id;
1118}
1119
1120std::string Dialogue::getChoiceLabel(int index) const {
1121 if (index < 0 || size_t(index) >= choices_.size()) return {};
1122 return choices_[size_t(index)].label;
1123}
1124
1126 if (phase_ != Phase::WaitingChoice) return false;
1127 if (index < 0 || size_t(index) >= choices_.size()) return false;
1128 selectedChoiceId_ = choices_[size_t(index)].id;
1129 phase_ = Phase::Idle;
1130 return true;
1131}
1132
1133void Dialogue::setLipSyncEnabled(bool enabled) { lipSyncEnabled_ = enabled; }
1134
1135void Dialogue::setLipSyncParameter(const std::string &name) {
1136 if (!name.empty()) lipSyncParameter_ = name;
1137}
1138
1139void Dialogue::setLipSyncAmplitude(float amplitude) {
1140 if (amplitude < 0.f) amplitude = 0.f;
1141 if (amplitude > 2.f) amplitude = 2.f;
1142 lipSyncAmplitude_ = amplitude;
1143}
1144
1145void Dialogue::updateLipSync(float dt) {
1146 if (dt < 0.f) dt = 0.f;
1147 if (lipSyncEnabled_ && phase_ == Phase::Typing && !speakerId_.empty()) {
1148 lipSyncTime_ += dt;
1149 // Simple mouth envelope while characters appear (no audio dependency).
1150 const float wave = std::fabs(std::sin(lipSyncTime_ * 14.f));
1151 lipSyncValue_ = lipSyncAmplitude_ * (0.25f + 0.75f * wave);
1152 } else {
1153 // Ease shut when not typing.
1154 lipSyncValue_ *= std::max(0.f, 1.f - dt * 8.f);
1155 if (lipSyncValue_ < 0.01f) lipSyncValue_ = 0.f;
1156 }
1157 applyLipSyncToSpeaker();
1158}
1159
1160void Dialogue::applyLipSyncToSpeaker() {
1161 if (!lipSyncEnabled_ || speakerId_.empty() || lipSyncParameter_.empty()) return;
1162 Character *c = findCharacter(speakerId_);
1163 if (!c || !c->avatar) return;
1164 c->avatar->setParameter(lipSyncParameter_, lipSyncValue_);
1165}
1166
1168 if (dt < 0.f) dt = 0.f;
1169 if (phase_ == Phase::Typing) {
1170 const float total = float(utf8_codepoint_count(fullText_));
1171 typed_ += typeSpeed_ * dt;
1172 if (typed_ >= total) {
1173 typed_ = total;
1174 phase_ = Phase::WaitingAdvance;
1175 }
1176 }
1177 updateLipSync(dt);
1178 pollSceneChange();
1179}
1180
1182 phase_ = Phase::Idle;
1183 speakerId_.clear();
1184 fullText_.clear();
1185 typed_ = 0.f;
1186 choices_.clear();
1187 selectedChoiceId_.clear();
1188 lipSyncValue_ = 0.f;
1189 lipSyncTime_ = 0.f;
1190 currentLineId_.clear();
1191 currentLineMeta_.clear();
1192 currentLineTags_.clear();
1193 for (Character &c : characters_) {
1194 c.shown = false;
1195 if (c.avatar) c.avatar->setVisible(false);
1196 }
1197}
1198
1201 out.set("phase", StateValue::string(getPhase()));
1202 out.set("speakerId", StateValue::string(speakerId_));
1203 out.set("fullText", StateValue::string(fullText_));
1204 out.set("typed", StateValue::number(typed_));
1205 out.set("typeSpeed", StateValue::number(typeSpeed_));
1206 out.set("lipSyncEnabled", StateValue::boolean(lipSyncEnabled_));
1207 out.set("lipSyncParameter", StateValue::string(lipSyncParameter_));
1208 out.set("lipSyncAmplitude", StateValue::number(lipSyncAmplitude_));
1209 out.set("rngState", StateValue::integer(static_cast<int64_t>(rngState_)));
1210 out.set("currentLineId", StateValue::string(currentLineId_));
1211 out.set("selectedChoiceId", StateValue::string(selectedChoiceId_));
1212
1214 for (const auto& kv : globalVars_) global.set(kv.first, varValueToState(kv.second));
1215 out.set("globalVars", std::move(global));
1216
1218 for (const auto& kv : sceneVars_) scene.set(kv.first, varValueToState(kv.second));
1219 out.set("sceneVars", std::move(scene));
1220
1222 for (const auto& c : choices_) {
1224 item.set("id", StateValue::string(c.id));
1225 item.set("label", StateValue::string(c.label));
1226 choices.pushBack(std::move(item));
1227 }
1228 out.set("choices", std::move(choices));
1229
1230 StateValue chars = StateValue::array();
1231 for (const auto& c : characters_) {
1233 item.set("id", StateValue::string(c.id));
1234 item.set("displayName", StateValue::string(c.displayName));
1235 item.set("slot", StateValue::string(c.slot));
1236 item.set("shown", StateValue::boolean(c.shown));
1237 chars.pushBack(std::move(item));
1238 }
1239 out.set("characters", std::move(chars));
1240
1242 for (const auto& kv : slotX_) slotX.set(kv.first, StateValue::number(kv.second));
1243 out.set("slotX", std::move(slotX));
1244 return true;
1245}
1246
1247bool Dialogue::restoreState(const StateValue& in, std::string* err) {
1248 if (!in.isObject()) {
1249 if (err) *err = "dialogue: state is not an object";
1250 return false;
1251 }
1252 const StateValue* phase = in.find("phase");
1253 if (!phase || !phase->isString()) {
1254 if (err) *err = "dialogue: missing phase";
1255 return false;
1256 }
1257 const std::string phaseName = phase->asString();
1258 if (phaseName == "idle")
1259 phase_ = Phase::Idle;
1260 else if (phaseName == "typing")
1261 phase_ = Phase::Typing;
1262 else if (phaseName == "waiting_advance")
1263 phase_ = Phase::WaitingAdvance;
1264 else if (phaseName == "waiting_choice")
1265 phase_ = Phase::WaitingChoice;
1266 else {
1267 if (err) *err = "dialogue: unknown phase '" + phaseName + "'";
1268 return false;
1269 }
1270
1271 if (const StateValue* v = in.find("speakerId"); v && v->isString()) speakerId_ = v->asString();
1272 if (const StateValue* v = in.find("fullText"); v && v->isString()) fullText_ = v->asString();
1273 if (const StateValue* v = in.find("typed"); v && (v->isInt() || v->isFloat()))
1274 typed_ = static_cast<float>(v->isInt() ? double(v->asInt()) : v->asDouble());
1275 if (const StateValue* v = in.find("typeSpeed"); v && (v->isInt() || v->isFloat()))
1276 typeSpeed_ = static_cast<float>(v->isInt() ? double(v->asInt()) : v->asDouble());
1277 if (const StateValue* v = in.find("lipSyncEnabled"); v && v->isBool()) lipSyncEnabled_ = v->asBool();
1278 if (const StateValue* v = in.find("lipSyncParameter"); v && v->isString()) lipSyncParameter_ = v->asString();
1279 if (const StateValue* v = in.find("lipSyncAmplitude"); v && (v->isInt() || v->isFloat()))
1280 lipSyncAmplitude_ = static_cast<float>(v->isInt() ? double(v->asInt()) : v->asDouble());
1281 if (const StateValue* v = in.find("rngState"); v && v->isInt()) rngState_ = static_cast<uint32_t>(v->asInt());
1282 if (const StateValue* v = in.find("currentLineId"); v && v->isString()) currentLineId_ = v->asString();
1283 if (const StateValue* v = in.find("selectedChoiceId"); v && v->isString()) selectedChoiceId_ = v->asString();
1284
1285 globalVars_.clear();
1286 if (const StateValue* vars = in.find("globalVars"); vars && vars->isObject()) {
1287 for (const auto& key : vars->keys()) {
1289 if (stateToVarValue(*vars->find(key), val)) globalVars_[key] = val;
1290 }
1291 }
1292 sceneVars_.clear();
1293 if (const StateValue* vars = in.find("sceneVars"); vars && vars->isObject()) {
1294 for (const auto& key : vars->keys()) {
1296 if (stateToVarValue(*vars->find(key), val)) sceneVars_[key] = val;
1297 }
1298 }
1299
1300 choices_.clear();
1301 if (const StateValue *choices = in.find("choices"); choices && choices->isArray()) {
1302 for (size_t i = 0; i < choices->arraySize(); ++i) {
1303 const StateValue &item = choices->at(i);
1304 const StateValue *id = item.find("id");
1305 const StateValue *label = item.find("label");
1306 if (id && id->isString() && label && label->isString()) {
1307 choices_.push_back(Choice{id->asString(), label->asString()});
1308 }
1309 }
1310 }
1311
1312 if (const StateValue *chars = in.find("characters"); chars && chars->isArray()) {
1313 for (size_t i = 0; i < chars->arraySize(); ++i) {
1314 const StateValue &item = chars->at(i);
1315 const StateValue *id = item.find("id");
1316 if (!id || !id->isString()) continue;
1317 Character *c = findCharacter(id->asString());
1318 if (!c) {
1319 characters_.push_back(Character{});
1320 c = &characters_.back();
1321 c->id = id->asString();
1322 if (const StateValue *name = item.find("displayName"); name && name->isString())
1323 c->displayName = name->asString();
1324 }
1325 if (const StateValue *slot = item.find("slot"); slot && slot->isString())
1326 c->slot = slot->asString();
1327 if (const StateValue *shown = item.find("shown"); shown && shown->isBool()) {
1328 c->shown = shown->asBool();
1329 if (c->avatar) c->avatar->setVisible(c->shown);
1330 }
1331 }
1332 }
1333
1334 slotX_.clear();
1335 if (const StateValue *slots = in.find("slotX"); slots && slots->isObject()) {
1336 for (const auto &key : slots->keys()) {
1337 const StateValue *v = slots->find(key);
1338 if (v && (v->isInt() || v->isFloat()))
1339 slotX_[key] = static_cast<float>(v->isInt() ? double(v->asInt()) : v->asDouble());
1340 }
1341 }
1342 return true;
1343}
1344
1346 reset();
1347 return true;
1348}
1349
1350void Dialogue::expose(ssq::Table &table) {
1351 if (Dialogue *self = Dialogue::create()) self->vm_ = table.getHandle();
1352 auto cls = table.addClass(name, Dialogue::create, false);
1353 expose(cls);
1354}
1355
1356void Dialogue::expose(ssq::Class &cls) {
1357 cls.addFunc("getName", &Dialogue::getName);
1358 cls.addFunc("registerCharacter", &Dialogue::registerCharacter);
1359 cls.addFunc("hasCharacter", &Dialogue::hasCharacter);
1360 cls.addFunc("getDisplayName", &Dialogue::getDisplayName);
1361 cls.addFunc("bindAvatar", &Dialogue::bindAvatar);
1362 cls.addFunc("getAvatar", &Dialogue::getAvatar);
1363 cls.addFunc("getCharacterCount", &Dialogue::getCharacterCount);
1364 cls.addFunc("getCharacterId", &Dialogue::getCharacterId);
1365
1366 cls.addFunc("show", &Dialogue::show);
1367 cls.addFunc("hide", &Dialogue::hide);
1368 cls.addFunc("isShown", &Dialogue::isShown);
1369 cls.addFunc("getSlot", &Dialogue::getSlot);
1370 cls.addFunc("setSlotX", &Dialogue::setSlotX);
1371 cls.addFunc("getSlotX", &Dialogue::getSlotX);
1372 cls.addFunc("setExpression", &Dialogue::setExpression);
1373 cls.addFunc("setMotion", &Dialogue::setMotion);
1374 cls.addFunc("syncStage", &Dialogue::syncStage);
1375
1376 cls.addFunc("say", &Dialogue::say);
1377 cls.addFunc("narrate", &Dialogue::narrate);
1378 cls.addFunc("setTypeSpeed", &Dialogue::setTypeSpeed);
1379 cls.addFunc("getTypeSpeed", &Dialogue::getTypeSpeed);
1380 cls.addFunc("skipTyping", &Dialogue::skipTyping);
1381 cls.addFunc("isTyping", &Dialogue::isTyping);
1382 cls.addFunc("isWaitingAdvance", &Dialogue::isWaitingAdvance);
1383 cls.addFunc("isIdle", &Dialogue::isIdle);
1384 cls.addFunc("advance", &Dialogue::advance);
1385 cls.addFunc("getSpeakerId", &Dialogue::getSpeakerId);
1386 cls.addFunc("getSpeakerName", &Dialogue::getSpeakerName);
1387 cls.addFunc("getFullText", &Dialogue::getFullText);
1388 cls.addFunc("getVisibleText", &Dialogue::getVisibleText);
1389 cls.addFunc("getPhase", &Dialogue::getPhase);
1390
1391 cls.addFunc("setLipSyncEnabled", &Dialogue::setLipSyncEnabled);
1392 cls.addFunc("isLipSyncEnabled", &Dialogue::isLipSyncEnabled);
1393 cls.addFunc("setLipSyncParameter", &Dialogue::setLipSyncParameter);
1394 cls.addFunc("getLipSyncParameter", &Dialogue::getLipSyncParameter);
1395 cls.addFunc("setLipSyncAmplitude", &Dialogue::setLipSyncAmplitude);
1396 cls.addFunc("getLipSyncAmplitude", &Dialogue::getLipSyncAmplitude);
1397 cls.addFunc("getLipSyncValue", &Dialogue::getLipSyncValue);
1398
1399 cls.addFunc("clearChoices", &Dialogue::clearChoices);
1400 cls.addFunc("addChoice", &Dialogue::addChoice);
1401 cls.addFunc("presentChoices", &Dialogue::presentChoices);
1402 cls.addFunc("isWaitingChoice", &Dialogue::isWaitingChoice);
1403 cls.addFunc("getChoiceCount", &Dialogue::getChoiceCount);
1404 cls.addFunc("getChoiceId", &Dialogue::getChoiceId);
1405 cls.addFunc("getChoiceLabel", &Dialogue::getChoiceLabel);
1406 cls.addFunc("selectChoice", &Dialogue::selectChoice);
1407 cls.addFunc("getSelectedChoiceId", &Dialogue::getSelectedChoiceId);
1408
1409 cls.addFunc("setVar", &Dialogue::setVar);
1410 cls.addFunc("getVarType", &Dialogue::getVarType);
1411 cls.addFunc("getVarInt", &Dialogue::getVarInt);
1412 cls.addFunc("getVarFloat", &Dialogue::getVarFloat);
1413 cls.addFunc("getVarBool", &Dialogue::getVarBool);
1414 cls.addFunc("getVarString", &Dialogue::getVarString);
1415 cls.addFunc("hasVar", &Dialogue::hasVar);
1416 cls.addFunc("clearVar", &Dialogue::clearVar);
1417 cls.addFunc("clearVars", &Dialogue::clearVars);
1418
1419 cls.addFunc("registerCondition", &Dialogue::registerCondition);
1420 cls.addFunc("unregisterCondition", &Dialogue::unregisterCondition);
1421 cls.addFunc("evalCondition", &Dialogue::evalCondition);
1422
1423 // `loadPoolsFromTable` is the documented script entry point for pool registration
1424 // (`docs/dev/对话与Avatar模块设计.md` §池注册) and the table-taking counterpart of
1425 // `loadPoolsFromData`. The dnut refactor dropped the binding while keeping the method,
1426 // so `DialogueProcScriptTest.basicPools` called a name no VM could resolve.
1427 cls.addFunc("loadPoolsFromTable", &Dialogue::loadPoolsFromTable);
1428 cls.addFunc("clearPools", &Dialogue::clearPools);
1429 cls.addFunc("getPoolCount", &Dialogue::getPoolCount);
1430 cls.addFunc("getPoolId", &Dialogue::getPoolId);
1431 cls.addFunc("hasPool", &Dialogue::hasPool);
1432 cls.addFunc("getLastPoolsError", &Dialogue::getLastPoolsError);
1433
1434 cls.addFunc("setRandomSeed", &Dialogue::setRandomSeed);
1435 cls.addFunc("getRandomSeed", &Dialogue::getRandomSeed);
1436
1437 cls.addFunc("pickLine", &Dialogue::pickLine);
1438 cls.addFunc("playLine", &Dialogue::playLine);
1439 cls.addFunc("playPool", &Dialogue::playPool);
1440 cls.addFunc("getCurrentLineId", &Dialogue::getCurrentLineId);
1441 cls.addFunc("getCurrentLineMeta", &Dialogue::getCurrentLineMeta);
1442 cls.addFunc("getCurrentLineTags", &Dialogue::getCurrentLineTags);
1443
1444 cls.addFunc("update", &Dialogue::update);
1445 cls.addFunc("reset", &Dialogue::reset);
1446 // Compatibility alias: agents (and older samples) often guess dialogue.clear;
1447 // the authoritative wipe is reset(). DialogueVoice::clear is a different API.
1448 cls.addFunc("clear", &Dialogue::reset);
1449}
1450
1451} // namespace eve::dialogue
double y
double m[16]
double x
float w
Definition AnimClip.cpp:738
int root
Definition AnimSmr.cpp:119
struct SQVM * HSQUIRRELVM
glm::vec4 p[6]
HSQUIRRELVM vm
Definition ECS.cpp:38
HSQOBJECT cls
Definition ECS.cpp:39
SQObjectPtr key
Definition ECS.cpp:155
std::string name
Definition ECS.cpp:154
std::vector< std::string > fields
Definition ECS.cpp:42
double raw
glm::vec3 n
Definition Grass.cpp:63
float v
std::int32_t second
std::int32_t c
std::int32_t first
JobScope scope
std::set< std::string > choices
bool present
std::string label
std::string id
Poco::JSON::Object::Ptr result
double defaultValue
std::vector< RecipeParam > params
bool all
std::unordered_set< std::string > tags
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
#define Module_IMPL(ModuleName, newExpr)
Definition Module.h:27
double dt
std::string error
Definition Package.cpp:174
std::string script
Definition PlayHost.cpp:117
std::weak_ptr< PrimitiveScene > scene
Object::Ptr value
float d
float t
std::string slot
unsigned line
std::string text
ScriptStructure out
size_t begin
size_t end
std::map< std::array< int, 4 >, std::vector< const Subject * > > candidates
Definition Sensing.cpp:32
LocalPageCacheEntry slots[ShadowConfig::kLocalSlots]
Definition Shadow.cpp:159
The single Squirrel projection for common Result, Status and Value.
让脚本扮演 IStateQuery / IStateMutation(阶段 5 的第五、六个插座)。
Share string attribute map operations through the Windows Foundation DLL.
float phase
Heightmap global
uint32_t seed
Definition TreeMesh.cpp:276
int children
Definition TreeMesh.cpp:432
float size
Definition TreeMesh.cpp:158
UIHostHandle host
std::vector< std::string_view > lines
uint32_t index
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
virtual std::string getName() const =0
Returns the name.
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
JSON-compatible state value tree used by state hot reload.
Definition StateValue.h:30
static StateValue object()
Empty object.
Definition StateValue.h:50
static StateValue boolean(bool v)
Boolean value.
static StateValue array()
Empty array.
Definition StateValue.h:48
static StateValue integer(int64_t v)
Integer value.
void pushBack(StateValue v)
Append an element; only valid on arrays.
bool isString() const
Definition StateValue.h:59
bool isBool() const
Definition StateValue.h:58
bool isObject() const
Definition StateValue.h:60
bool isArray() const
Definition StateValue.h:61
static StateValue number(double v)
Floating-point value.
const StateValue * find(const std::string &key) const
Look up key; nullptr when absent.
static StateValue null()
Null value.
Definition StateValue.h:38
StateValue & at(size_t index)
Indexed element (bounds-checked); only valid on arrays.
Definition StateValue.h:77
bool isInt() const
Definition StateValue.h:56
static StateValue string(std::string v)
String value.
void set(const std::string &key, StateValue v)
Insert or replace key; only valid on objects.
The canonical owning dynamic value used by data-facing protocols.
Definition Value.h:31
const std::string & asString() const
Return the string payload; the caller must have checked the kind.
Definition Value.cpp:207
std::string typeName() const
Return the compatibility type name used by dialogue scripts.
Definition Value.cpp:270
std::map< std::string, Value > Object
Definition Value.h:34
static Value number(double value)
Compatibility factory for a Double value.
Definition Value.h:117
static Value string(std::string value)
Compatibility factory for a string value.
Definition Value.h:121
@ Int
Compatibility spelling used by the former dialogue value.
@ Float
Compatibility spelling used by the former dialogue value.
std::vector< Value > Array
Definition Value.h:33
static Value integer(std::int64_t value)
Compatibility factory for an Int64 value.
Definition Value.h:115
static Value boolean(bool value)
Compatibility factory for a boolean value.
Definition Value.h:119
const T * getIf() const noexcept
Return a typed pointer, or nullptr when the kind differs.
Definition Value.h:209
Value * find(const std::string &key) noexcept
Return an object member, or nullptr when absent.
Definition Value.cpp:244
Unified avatar instance. Kind is a string: "image" | "live2d" | "vroid". Script-facing API avoids ove...
size_t addDestroyHook(DestroyHook hook)
Register a destruction hook; returns an id usable with removeDestroyHook().
Runtime-state serialization for state hot reload.
Visual-novel style dialogue stage. Script: dlg <- eve.Dialogue();
Definition Dialogue.h:47
std::string pickLineWithParams(const std::string &poolId, const std::unordered_map< std::string, VarValue > &params)
Pick line with params.
Definition Dialogue.cpp:763
bool setExpression(const std::string &id, const std::string &expression)
Sets the expression.
Definition Dialogue.cpp:982
bool setMotion(const std::string &id, const std::string &motion)
Sets the motion.
Definition Dialogue.cpp:989
std::string getSpeakerName() const
Returns the speaker name.
void reset()
重置舞台与台词状态。
void advance()
Advance.
void presentChoices()
Present choices.
std::string getLastPoolsError() const
Returns the last pools error.
Definition Dialogue.h:212
float getLipSyncAmplitude() const
Returns the lip sync amplitude.
Definition Dialogue.h:135
bool clearVar(const std::string &name, const std::string &scope)
Clears var.
Definition Dialogue.cpp:269
bool playLineWithParams(const std::string &lineId, const std::unordered_map< std::string, VarValue > &params)
Play line with params.
Definition Dialogue.cpp:811
std::string getSpeakerId() const
Returns the speaker id.
Definition Dialogue.h:114
int getCharacterCount() const
Returns the character count.
Definition Dialogue.cpp:934
bool captureState(StateValue &out) const
Serialize conversation state (vars, rng, phase, choices, stage).
bool restoreState(const StateValue &in, std::string *err=nullptr)
Restore conversation state captured by captureState().
std::string getCurrentLineMeta(const std::string &field) const
Returns the current line meta.
Definition Dialogue.cpp:847
float getSlotX(const std::string &slot) const
Returns the slot x.
Definition Dialogue.cpp:973
bool isIdle() const
True when idle.
bool evalCondition(ssq::Object table)
Eval condition.
Definition Dialogue.cpp:312
std::string getCurrentLineId() const
Returns the current line id.
Definition Dialogue.h:238
std::string getFullText() const
Returns the full text.
Definition Dialogue.h:118
bool getVarBool(const std::string &name, bool defaultValue, const std::string &scope) const
Returns the var bool.
Definition Dialogue.cpp:249
bool registerCharacter(const std::string &id, const std::string &displayName)
角色:注册 / 查询 / 绑定 Avatar。
Definition Dialogue.cpp:890
bool playPool(const std::string &poolId, ssq::Object params)
Play pool.
Definition Dialogue.cpp:835
std::vector< std::string > getCurrentLineTags() const
Returns the current line tags.
Definition Dialogue.cpp:852
bool playLine(const std::string &lineId, ssq::Object params)
Play line.
Definition Dialogue.cpp:805
void narrate(const std::string &text)
Narrate.
int loadPoolsFromData(const DataValue &root)
Loads pools from data.
Definition Dialogue.cpp:599
void clearChoices()
选项:清空/添加/展示与选择。
int replacePoolsFromData(const DataValue &root)
Atomically replace all pools from a validated unified dnut workspace.
Definition Dialogue.cpp:601
bool isTyping() const
True when typing.
int getPoolCount() const
Returns the pool count.
Definition Dialogue.cpp:661
bool setVar(const std::string &name, ssq::Object value, const std::string &scope)
Sets the var.
Definition Dialogue.cpp:210
bool selectChoice(int index)
Select choice.
bool hasCharacter(const std::string &id) const
True when character.
Definition Dialogue.cpp:903
std::string getCharacterId(int index) const
Returns the character id.
Definition Dialogue.cpp:936
void setLipSyncParameter(const std::string &name)
Sets the lip sync parameter.
bool addChoice(const std::string &id, const std::string &label)
Adds choice.
VarValue getVarValue(const std::string &name, const std::string &scope) const
Returns the var value.
Definition Dialogue.cpp:221
bool show(const std::string &id, const std::string &slot)
舞台:显示/隐藏角色、槽位与表情/动作。
Definition Dialogue.cpp:941
void setTypeSpeed(float charsPerSecond)
Sets the type speed.
float getVarFloat(const std::string &name, float defaultValue, const std::string &scope) const
Returns the var float.
Definition Dialogue.cpp:240
int loadPoolsFromTable(ssq::Object table)
Loads pools from table.
Definition Dialogue.cpp:518
bool hasPool(const std::string &id) const
True when pool.
Definition Dialogue.cpp:668
std::string getChoiceId(int index) const
Returns the choice id.
avatar::AvatarInstance * getAvatar(const std::string &id) const
Returns the avatar.
Definition Dialogue.cpp:929
bool playPoolWithParams(const std::string &poolId, const std::unordered_map< std::string, VarValue > &params)
Play pool with params.
Definition Dialogue.cpp:841
bool unregisterCondition(const std::string &name)
Unregisters condition.
Definition Dialogue.cpp:304
void skipTyping()
Skip typing.
void update(float dt)
推进打字机 / 口型同步 / 阶段机;每帧调用。
void say(const std::string &speakerId, const std::string &text)
台词:说话/旁白、打字机效果与推进。
bool evalConditionData(const DataValue &cond)
Eval condition data.
Definition Dialogue.cpp:463
bool isWaitingChoice() const
True when waiting choice.
float getLipSyncValue() const
Returns the lip sync value.
Definition Dialogue.h:137
std::string pickLine(const std::string &poolId, ssq::Object params)
Pick line.
Definition Dialogue.cpp:757
std::string getChoiceLabel(int index) const
Returns the choice label.
bool bindAvatar(const std::string &id, avatar::AvatarInstance *av)
Binds avatar.
Definition Dialogue.cpp:910
void setRandomSeed(int seed)
Sets the random seed.
Definition Dialogue.cpp:752
bool resetToDefaults()
Reset stage and line state (restore fallback).
std::string getVarType(const std::string &name, const std::string &scope) const
Returns the var type.
Definition Dialogue.cpp:228
void setSlotX(const std::string &slot, float xNorm)
Sets the slot x.
Definition Dialogue.cpp:968
bool registerCondition(const std::string &name, ssq::Object fn)
Registers condition.
Definition Dialogue.cpp:289
std::string getVarString(const std::string &name, const std::string &defaultValue, const std::string &scope) const
Returns the var string.
Definition Dialogue.cpp:258
int getRandomSeed() const
Returns the random seed.
Definition Dialogue.h:219
bool isShown(const std::string &id) const
True when shown.
Definition Dialogue.cpp:958
std::string getLipSyncParameter() const
Returns the lip sync parameter.
Definition Dialogue.h:131
void syncStage(float stageWidth, float stageHeight)
Synchronizes stage.
Definition Dialogue.cpp:996
bool setVarValue(const std::string &name, const VarValue &value, const std::string &scope)
Sets the var value.
Definition Dialogue.cpp:202
~Dialogue() override
Dialogue.
Definition Dialogue.cpp:174
std::string getSlot(const std::string &id) const
Returns the slot.
Definition Dialogue.cpp:963
int getChoiceCount() const
Returns the choice count.
void setLipSyncEnabled(bool enabled)
口型同步:打字时驱动说话者 Avatar 参数。
std::string getSelectedChoiceId() const
Returns the selected choice id.
Definition Dialogue.h:156
int getVarInt(const std::string &name, int defaultValue, const std::string &scope) const
Returns the var int.
Definition Dialogue.cpp:232
void setLipSyncAmplitude(float amplitude)
Sets the lip sync amplitude.
std::string getPoolId(int index) const
Returns the pool id.
Definition Dialogue.cpp:663
bool hide(const std::string &id)
Hide.
Definition Dialogue.cpp:950
void clearVars(const std::string &scope)
Clears vars.
Definition Dialogue.cpp:274
bool isWaitingAdvance() const
True when waiting advance.
bool isLipSyncEnabled() const
True when lip sync enabled.
Definition Dialogue.h:127
std::string getDisplayName(const std::string &id) const
Returns the display name.
Definition Dialogue.cpp:905
std::string getVisibleText() const
Returns the visible text.
float getTypeSpeed() const
Returns the type speed.
Definition Dialogue.h:101
void clearPools()
Clears pools.
Definition Dialogue.cpp:659
bool hasVar(const std::string &name, const std::string &scope) const
True when var.
Definition Dialogue.cpp:264
std::string getPhase() const
Returns the phase.
bool isObject() const
True when object.
Definition Json.cpp:332
bool isArray() const
True when array.
Definition Json.cpp:333
bool isNull() const
True when null.
Definition Json.cpp:326
ECS mount point for one scene graph (full scene or nested subtree root). Isomorphic to eve::ui::UIHos...
Definition SceneHost.h:89
const std::string & getName()
SQInteger top
Definition Snapshot.cpp:115
const Value * field(const Value &value, const char *key)
Borrow an optional object field.
EVENGINE_API_ORCHESTRATION void withdrawScriptStateQuerySeam()
撤回 IStateQuery 接缝与仍然在位的脚本适配器。
EVENGINE_API_ORCHESTRATION void declareScriptStateQuerySeam()
声明"`IStateQuery` 可以由脚本提供"这条接缝。
EVENGINE_API_ORCHESTRATION void withdrawScriptStateMutationSeam()
撤回 IStateMutation 接缝与仍然在位的脚本适配器。
eve::Value DataValue
Canonical data value used by dialogue pools, conditions and scripts.
Definition Dialogue.h:37
eve::Value VarValue
Definition Dialogue.h:38
EVENGINE_API_ORCHESTRATION void declareScriptStateMutationSeam()
声明"`IStateMutation` 可以由脚本提供"这条接缝。
WGPUStringView sv(const char *s)
Build a WGPUStringView from a C string (null-safe, length auto-computed).
Definition wgpu_types.h:20
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...
Result< void > pushValue(HSQUIRRELVM vm, const Value &value, const SquirrelValueOptions &options)
Push a canonical Value into the active Squirrel VM.
Result< Value > valueFromSquirrel(HSQUIRRELVM vm, SQInteger index, const SquirrelValueOptions &options)
Convert one Squirrel value into the canonical owning Value tree.
StateValue toLegacyStateValue(const Value &value)
Project a canonical value into the legacy reload snapshot format.
Value toCanonicalStateValue(const StateValue &value)
Copy a legacy reload tree into the canonical owning value protocol.
size_t utf8_codepoint_count(const std::string &s)
Count UTF-8 code points in a string. Invalid / truncated sequences stop the scan.
Definition utf8.cpp:23
size_t utf8_byte_offset_for_codepoints(const std::string &s, size_t codepoints)
Byte offset of the N-th UTF-8 code point (0-based count of code points). Returns s....
Definition utf8.cpp:37
SettlementPipeline::Stage fn
bool enabled