6#include <simplesquirrel/simplesquirrel.hpp>
15#include "sqpcheader.h"
26#include <unordered_map>
37struct ScriptComponentEntry {
50 ScriptComponentEntry() { sq_resetobject(&
cls); }
58using ScriptComponentKey = std::pair<std::string, std::uint64_t>;
59using ScriptComponentMap = std::map<ScriptComponentKey, ScriptComponentEntry>;
61ScriptComponentMap& currentScriptComponents() {
62 static ScriptComponentMap
m;
68std::vector<ScriptComponentRecord>& retiredScriptComponents() {
69 static std::vector<ScriptComponentRecord>
v;
78int allocEntityId() {
return nextEntityId()++; }
81std::unordered_map<const void*, CppEntityViewFn>& cppEntityViews() {
82 static std::unordered_map<const void*, CppEntityViewFn> views;
86std::vector<std::function<void(ssq::Table&)>>& postEcsHooks() {
87 static std::vector<std::function<void(ssq::Table&)>> hooks;
91bool& ecsScriptInjected() {
92 static bool injected =
false;
96size_t& postEcsHooksFlushed() {
105bool isSubclassOf(
HSQUIRRELVM vm, HSQOBJECT child, HSQOBJECT base) {
106 if (
child._type != OT_CLASS || base._type != OT_CLASS)
return false;
107 const SQInteger
top = sq_gettop(
vm);
108 sq_pushobject(
vm, child);
109 for (
int guard = 0; guard < 64; ++guard) {
110 if (sq_gettype(
vm, -1) != OT_CLASS)
break;
112 sq_getstackobj(
vm, -1, &cur);
113 if (cur._unVal.pClass == base._unVal.pClass) {
117 if (SQ_FAILED(sq_getbase(
vm, -1)))
break;
119 if (sq_gettype(
vm, -1) != OT_CLASS)
break;
126void collectClassFields(
HSQUIRRELVM vm, HSQOBJECT clsObj, HSQOBJECT outTable) {
127 const SQInteger
top = sq_gettop(
vm);
128 sq_pushobject(
vm, outTable);
129 sq_pushobject(
vm, clsObj);
131 while (SQ_SUCCEEDED(sq_next(
vm, -2))) {
133 if (sq_gettype(
vm, -2) == OT_STRING) {
134 const SQChar*
key =
nullptr;
135 sq_getstring(
vm, -2, &
key);
136 if (
key &&
key[0] !=
'_') {
137 const SQObjectType vt = sq_gettype(
vm, -1);
138 if (vt != OT_CLOSURE && vt != OT_NATIVECLOSURE && vt != OT_GENERATOR) {
153struct DeclaredField {
170std::vector<DeclaredField> declaredFields(HSQOBJECT clsObj) {
171 std::vector<std::pair<SQInteger, DeclaredField>>
ordered;
172 SQClass* klass = _class(clsObj);
173 if (klass ==
nullptr || klass->_members ==
nullptr)
return {};
179 while ((
index = klass->_members->Next(
false, refpos,
key,
value)) != -1) {
180 refpos = SQObjectPtr(
index);
181 if (sq_type(
key) != OT_STRING || !_isfield(
value))
continue;
182 const SQChar*
name = _stringval(
key);
183 if (
name ==
nullptr ||
name[0] ==
'_')
continue;
184 ordered.emplace_back(
static_cast<SQInteger
>(_member_idx(
value)), DeclaredField{
name,
key});
186 std::sort(
ordered.begin(),
ordered.end(), [](
const auto&
a,
const auto&
b) { return a.first < b.first; });
188 std::vector<DeclaredField>
out;
195std::vector<std::string> fieldNames(
const std::vector<DeclaredField>&
fields) {
196 std::vector<std::string> names;
197 names.reserve(
fields.size());
202ssq::Table inspectClassFields(ssq::Object clsObj) {
205 if (clsObj.getType() != ssq::Type::CLASS)
return out;
206 collectClassFields(
vm, clsObj.getRaw(),
out.getRaw());
211Result<Value> classFieldDefault(
HSQUIRRELVM vm, HSQOBJECT clsObj,
const std::string& field) {
212 const SQInteger
top = sq_gettop(
vm);
213 sq_pushobject(
vm, clsObj);
214 sq_pushstring(
vm,
field.c_str(),
static_cast<SQInteger
>(
field.size()));
215 if (SQ_FAILED(sq_get(
vm, -2))) {
220 const SQInteger valueIndex = sq_gettop(
vm);
227struct ScriptComponentSchema {
230 const std::vector<Value>*
defaults =
nullptr;
240bool schemaOfComponentClass(HSQOBJECT
cls, ScriptComponentSchema*
out) {
241 const SQClass* klass = _class(
cls);
242 if (klass ==
nullptr)
return false;
243 for (
const auto& [
key, entry] : currentScriptComponents()) {
244 if (_class(entry.cls) != klass)
continue;
245 if (
out !=
nullptr) {
246 out->record.name =
key.first;
248 out->record.generation = entry.generation;
249 out->record.retired =
false;
250 out->record.fields = entry.fields;
251 out->defaults = &entry.defaults;
266 const SQInteger
top = sq_gettop(
vm);
268 sq_pushstring(
vm,
name, -1);
269 if (SQ_FAILED(sq_get(
vm, self))) {
273 if (
out !=
nullptr) sq_getstackobj(
vm, -1,
out);
283 if (!instanceSlot(
vm,
index,
"_ownerEid", &eid) || sq_type(eid) != OT_INTEGER)
return false;
284 if (!instanceSlot(
vm,
index,
"_componentName", &
name) || sq_type(
name) != OT_STRING)
return false;
285 if (!instanceSlot(
vm,
index,
"_componentVersion", &
version) || sq_type(
version) != OT_INTEGER)
return false;
286 if (_integer(eid) <= 0 || _stringval(
name)[0] ==
'\0')
return false;
287 out->entityId =
static_cast<std::uint64_t
>(_integer(eid));
295 const SQChar*
text =
nullptr;
296 if (SQ_FAILED(sq_getstring(
vm,
index, &
text)) ||
text ==
nullptr)
return {};
302 const SQInteger
top = sq_gettop(
vm);
303 ScriptComponentStoreKey
key;
304 if (!instanceIdentity(
vm, 1, &
key))
return sq_throwerror(
vm, _SC(
"component instance is not bound to an entity"));
305 if (sq_gettype(
vm, 2) != OT_STRING)
return sq_throwerror(
vm, _SC(
"component field name must be a string"));
307 const std::string
field = stackFieldName(
vm, 2);
311 return sq_throwerror(
vm, (
"'" + field +
"' is not a declared field of component '" +
key.name +
"'").c_str());
316 return sq_throwerror(
vm, pushed.status().describe().c_str());
323 const SQInteger
top = sq_gettop(
vm);
324 ScriptComponentStoreKey
key;
325 if (!instanceIdentity(
vm, 1, &
key))
return sq_throwerror(
vm, _SC(
"component instance is not bound to an entity"));
326 if (sq_gettype(
vm, 2) != OT_STRING)
return sq_throwerror(
vm, _SC(
"component field name must be a string"));
328 const std::string
field = stackFieldName(
vm, 2);
332 return sq_throwerror(
vm,
value.status().describe().c_str());
337 return sq_throwerror(
vm, (
"'" + field +
"' is not a declared field of component '" +
key.name +
"'").c_str());
345bool classDefinesFieldSeam(HSQOBJECT clsObj) {
346 SQClass* klass = _class(clsObj);
347 if (klass ==
nullptr)
return false;
348 return sq_type(klass->_metamethods[MT_GET]) != OT_NULL || sq_type(klass->_metamethods[MT_SET]) != OT_NULL;
352void installInstanceDelegateMembers(
HSQUIRRELVM vm, HSQOBJECT clsObj);
363Result<void> installComponentFieldSeam(
HSQUIRRELVM vm, HSQOBJECT clsObj,
const std::vector<DeclaredField>&
fields) {
364 if (classDefinesFieldSeam(clsObj))
367 "component class defines _get/_set itself; the engine field seam needs those two names",
368 {}, {},
"ecs.component"));
370 const SQInteger
top = sq_gettop(
vm);
371 sq_pushobject(
vm, clsObj);
372 const auto install = [&](
const char*
name, SQFUNCTION
fn) {
373 sq_pushstring(
vm,
name, -1);
374 sq_newclosure(
vm,
fn, 0);
375 sq_newslot(
vm, -3, SQFalse);
377 install(
"_get", scriptComponentFieldGet);
378 install(
"_set", scriptComponentFieldSet);
380 if (_class(clsObj) !=
nullptr) {
383 installInstanceDelegateMembers(
vm, clsObj);
399void installInstanceDelegateMembers(
HSQUIRRELVM vm, HSQOBJECT clsObj) {
400 SQClass* klass = _class(clsObj);
401 if (klass ==
nullptr)
return;
402 SQTable* delegates = _table(_ss(
vm)->_instance_default_delegate);
403 if (delegates ==
nullptr)
return;
409 while ((
index = delegates->Next(
false, refpos,
key,
value)) != -1) {
410 refpos = SQObjectPtr(
index);
411 if (sq_type(
key) != OT_STRING || sq_type(
value) != OT_NATIVECLOSURE)
continue;
430ssq::Object bindComponentValues(std::uint64_t entityId, ssq::Object instance) {
432 ssq::Object none(
vm);
433 if (instance.getType() != ssq::Type::INSTANCE)
return none;
437 const SQInteger
top = sq_gettop(
vm);
438 sq_pushobject(
vm, instance.getRaw());
440 if (SQ_FAILED(sq_getclass(
vm, -1))) {
444 sq_getstackobj(
vm, -1, &
cls);
446 ScriptComponentSchema schema;
447 const bool known = schemaOfComponentClass(
cls, &schema);
449 if (!known)
return none;
451 const ScriptComponentStoreKey
key{entityId, schema.record.name, schema.record.version};
452 const auto stamp = [&](
const char*
name,
const auto& push) {
453 const SQInteger inner = sq_gettop(
vm);
454 sq_pushobject(
vm, instance.getRaw());
455 sq_pushstring(
vm,
name, -1);
458 sq_settop(
vm, inner);
460 stamp(
"_ownerEid", [&] { sq_pushinteger(
vm,
static_cast<SQInteger
>(entityId)); });
461 stamp(
"_componentName", [&] { sq_pushstring(
vm, schema.record.name.c_str(), -1); });
462 stamp(
"_componentVersion", [&] { sq_pushinteger(
vm,
static_cast<SQInteger
>(schema.record.version.value())); });
466 const std::vector<Value>& declared = *schema.defaults;
467 const std::vector<std::string>&
fields = schema.record.fields;
468 for (std::size_t i = 0; i <
fields.size(); ++i)
471 .
ignore(
"a component whose values cannot be stored would silently lose its data if this succeeded");
474 ssq::Array names(
vm);
479bool scriptIsSubclass(ssq::Object child, ssq::Object base) {
480 if (
child.getType() != ssq::Type::CLASS || base.getType() != ssq::Type::CLASS)
return false;
481 return isSubclassOf(
child.getHandle(),
child.getRaw(), base.getRaw());
484ssq::Object getClassBase(ssq::Object
cls) {
487 if (
cls.getType() != ssq::Type::CLASS)
return ret;
488 const SQInteger
top = sq_gettop(
vm);
489 sq_pushobject(
vm,
cls.getRaw());
490 if (SQ_FAILED(sq_getbase(
vm, -1)) || sq_gettype(
vm, -1) != OT_CLASS) {
494 sq_getstackobj(
vm, -1, &ret.getRaw());
495 sq_addref(
vm, &ret.getRaw());
504const char* kEcsScript = R
"SQ(
505// Script ECS: define Component / Entity classes, create instances, view & System.
506// Mirrors ECS.hpp's class + component model for Squirrel game logic.
508if (!("Number" in eve)) eve.Number <- "number"
509if (!("Boolean" in eve)) eve.Boolean <- "boolean"
510if (!("String" in eve)) eve.String <- "string"
512eve._ecsTypes <- {} // EntityClass -> { cls, instances }
514// --- 性能缓存(万级实体稳态零分配) ---
515// view 结果缓存:create/destroy 时按类链失效;C++ 桥接类(_cppHasView=true)不缓存。
516eve._ecsViewCache <- {} // EntityClass -> array
517eve._ecsSlotsCache <- {} // EntityClass -> { fieldName = ComponentClass }
518eve._ecsFieldSlotsCache <- {} // EntityClass -> { fieldName = true }:只有这些槽位有真实字段
519eve._ecsCompDefaults <- {} // ComponentClass -> { fieldName = resolvedDefault }
520eve._ecsRevision <- 0 // increments on script entity structural changes
522function eve::_ecsResolveMarker(v) {
523 if (v == this.Number || v == "number") return 0.0
524 if (v == this.Boolean || v == "boolean") return false
525 if (v == this.String || v == "string") return ""
529function eve::_ecsIsComponentClass(obj) {
530 if (typeof obj != "class") return false
531 return this.isSubclass(obj, this.Component)
534// 解析"类型标记"(`x = eve.Number` → `0.0`):只处理**当前值本身是标记**的字段,其它字段
535// 一律不碰,所以这个函数可以重复跑(实例化、热重载迁移都调它),不会覆盖已有数据。
537// `declared` 是引擎侧给的字段名数组(登记组件)或 null(未登记组件)。登记组件的声明默认值
538// 已经按 schema 落在引擎侧存储里,`c[name]` 走 `_get` 读到的就是它;未登记组件从类声明读。
539// 两种组件因此共用同一段解析,标记规则仍然只有这一处实现(§9.64.4)。
540function eve::_ecsResolveComponentMarkers(compClass, c, declared) {
542 if (declared != null) {
543 foreach (name in declared) fields[name] <- true
545 fields = this.inspectClassFields(compClass)
548 foreach (name, val in fields) {
550 try { cur = c[name] } catch (e) { cur = null }
551 if (cur == this.Number || cur == this.Boolean || cur == this.String
552 || cur == "number" || cur == "boolean" || cur == "string") {
553 c[name] = this._ecsResolveMarker(cur)
554 resolved[name] <- c[name]
560function eve::_ecsInstantiateComponent(compClass, ownerEid = 0) {
561 local c = compClass()
562 // 先盖归属、按 schema 建引擎侧数据条目,**再**写默认值:已登记组件的字段槽位在登记时就被摘掉、
563 // `_set` 已装好,所以下面那些 `c[name] = val` 实际上是**写进引擎存储**,必须有个已绑定的条目
564 // 接着(顺序反了就会报 "not bound to an entity")。
565 // 返回值是这一代的字段名(声明顺序):槽位摘掉之后 `inspectClassFields` 什么也看不到,
566 // 而"类型标记"还得按声明顺序解析。未登记组件返回 null。
567 local declared = eve._ecsBindComponentValues(ownerEid, c)
568 if (compClass in this._ecsCompDefaults) {
569 foreach (name, val in this._ecsCompDefaults[compClass]) c[name] = val
571 this._ecsCompDefaults[compClass] <- this._ecsResolveComponentMarkers(compClass, c, declared)
576function eve::_ecsCollectSlots(cls) {
577 if (cls in this._ecsSlotsCache) return this._ecsSlotsCache[cls]
578 // { fieldName = ComponentClass } walking base classes (Entity → … → cls).
582 while (cur != null && guard < 64) {
583 if (!this.isSubclass(cur, this.Entity)) break
585 local declared = null
586 try { declared = cur.components } catch (e) { declared = null }
587 if (typeof declared == "table") {
588 foreach (k, v in declared) {
589 if (!(k in slots) && this._ecsIsComponentClass(v))
594 local fields = this.inspectClassFields(cur)
595 foreach (k, v in fields) {
596 if (k == "components") continue
597 if (!(k in slots) && this._ecsIsComponentClass(v))
601 cur = this.getClassBase(cur)
604 this._ecsSlotsCache[cls] <- slots
608// 哪些槽位在实体类里有**真实字段**(`pos = Pos` 或 `pos = null`),哪些只是登记在
609// `static components` 表里。判据是"这个类有没有声明同名的非函数成员",而不是"它的值
610// 是不是组件类"——`static components = { pos = Pos }` + `pos = null` 这种写法里字段值
611// 是 null,但字段确实存在、可以赋值。
613// 只有有字段的槽位能用 `e.pos` 访问:Squirrel 拒绝对 class 实例新建槽位,所以
614// `e[name] = c` 对未声明的键会抛 "the index 'name' does not exist"(`=` 编译成
615// _OP_SET;只有 `<-` 才是 new-slot 操作码,报的是另一句
616// "class instances do not support the new slot operator")。
617function eve::_ecsCollectFieldSlots(cls) {
618 if (cls in this._ecsFieldSlotsCache) return this._ecsFieldSlotsCache[cls]
622 while (cur != null && guard < 64) {
623 if (!this.isSubclass(cur, this.Entity)) break
624 foreach (k, v in this.inspectClassFields(cur)) {
625 if (k == "components") continue
626 if (!(k in fields)) fields[k] <- true
628 cur = this.getClassBase(cur)
631 this._ecsFieldSlotsCache[cls] <- fields
635function eve::_ecsInvalidateViews(cls) {
638 while (cur != null && guard < 64) {
639 if (cur in this._ecsViewCache) delete this._ecsViewCache[cur]
640 if (!this.isSubclass(cur, this.Entity)) break
641 cur = this.getClassBase(cur)
646function eve::_ecsEnsureType(cls) {
647 if (cls in this._ecsTypes) return this._ecsTypes[cls]
648 local info = { cls = cls, instances = [] }
649 this._ecsTypes[cls] <- info
653function eve::_ecsRegisterInstance(entity, cls) {
654 this._ecsEnsureType(cls).instances.push(entity)
655 this._ecsRevision += 1
656 this._ecsInvalidateViews(cls)
659function eve::_ecsUnregisterInstance(entity, cls) {
660 if (!(cls in this._ecsTypes)) return
661 local arr = this._ecsTypes[cls].instances
662 for (local i = arr.len() - 1; i >= 0; --i) {
663 if (arr[i] == entity) {
664 // O(1) swap-remove(顺序不保证);视图缓存随后失效重建
665 local last = arr.len() - 1
666 if (i != last) arr[i] = arr[last]
668 this._ecsRevision += 1
672 this._ecsInvalidateViews(cls)
675function eve::_ecsCollectInstances(cls, out) {
676 foreach (key, info in this._ecsTypes) {
677 if (info.cls == cls || this.isSubclass(info.cls, cls)) {
678 foreach (e in info.instances) {
679 if (e != null && e.isAlive()) out.push(e)
683 // 稳定顺序:按实体 id 升序(= 创建顺序)。
685 // `_ecsUnregisterInstance` 用 swap-remove 保持 O(1) 销毁,所以 instances 数组本身的
686 // 顺序在删除后会变——实测 [1,2,3,4] 删掉 2 得到 [1,4,3]。而 GPU System 按**视图顺序**
687 // 把实体打包成 buffer 的行,回读时又按同一顺序写回(`unpackEcsFloats(ents, …)`),
688 // `requestUploadRange/requestReadbackRange(first, count)` 更是直接按行号寻址:顺序一变,
689 // "第 i 行是哪个实体"就变了,回读的值会落到另一个实体上。
691 // id 由 `eve.allocEntityId()` 单调分配且**不复用**,所以按 id 排序给出一个跨子类也
692 // 成立的全序;`_ecsTypes` 的散列遍历顺序因此不再影响结果。排序只发生在缓存重建时
693 // (结构性变更后第一次取视图),每帧取视图仍然是 O(n) 拷贝。
694 out.sort(function(a, b) { return a._eid - b._eid })
697// ---------------------------------------------------------------------------
698// 热重载迁移(方案文档实施顺序第 3 步)
699// ---------------------------------------------------------------------------
701// 未登记组件的字段只存在实例槽位里,换实例就会丢:把旧实例**声明过的**字段值搬到新实例上。
702// 枚举类而不是实例——实例不可枚举(`foreach (k, v in instance)` 抛 "_nexti failed"),类可枚举;
703// 而 `fresh[name] = old[name]` 对新类声明过的成员成功、对没声明的抛错,正是这里要的过滤
704// (与 `load.nut` 的 `migrate_instance` 同一套理由)。
706// 已登记组件的字段槽位在登记时就被摘掉了,所以 `inspectClassFields(旧类)` 是空表、这里什么也
707// 不搬——那些数据本来就在引擎侧存储里,按 (实体, 名字, 版本) 寻址,换代时由 C++ 侧对齐 schema。
708function eve::_ecsCopyDeclaredFields(old, fresh) {
709 if (typeof old != "instance") return 0
710 local declared = null
711 try { declared = this.inspectClassFields(old.getclass()) } catch (e) { return 0 }
713 foreach (name, value in declared) {
714 try { fresh[name] = old[name]; copied += 1 } catch (e) { }
719// 把一个实体的一个组件槽位换到**新代类**的实例上。返回 false 表示换不了(调用方据此报出来)。
720function eve::_ecsRepointComponent(e, slotName, oldComp, compClass, fieldSlots) {
721 local fresh = compClass()
722 local declared = eve._ecsBindComponentValues(e._eid, fresh)
723 if (declared == null && typeof oldComp == "instance" && oldComp._componentName != "") {
724 // 旧实例是**已登记**组件的实例,而新类不是同一身份的登记(登记没跟着换代):
725 // 接管过去只会得到一个读不了字段的实例,宁可留着旧的并报出来。
728 if (!(compClass in this._ecsCompDefaults)) {
729 this._ecsCompDefaults[compClass] <- this._ecsResolveComponentMarkers(compClass, fresh, declared)
730 } else if (declared != null) {
731 // 已登记组件:默认值在引擎侧存储里,这里**不能**把缓存默认值写回去——那会把迁移
732 // 保留下来的旧值冲掉。只补新字段的类型标记。
733 this._ecsResolveComponentMarkers(compClass, fresh, declared)
735 foreach (name, val in this._ecsCompDefaults[compClass]) fresh[name] = val
737 if (declared == null) this._ecsCopyDeclaredFields(oldComp, fresh)
738 e._comps[slotName] = fresh
739 if (slotName in fieldSlots) e[slotName] = fresh
759function eve::_ecsMigrateAfterReload(oldBindings, rootTable) {
760 local replacements = {};
761 if (rootTable == null) return { entities = 0, components = 0, unresolved = 0 };
762 foreach (name, oldClass in oldBindings) {
763 if (typeof oldClass != "class" || !(name in rootTable)) continue;
764 local newClass = rootTable[name];
765 if (typeof newClass != "class" || newClass == oldClass) continue;
766 if (!this.isSubclass(newClass, this.Component) && !this.isSubclass(newClass, this.Entity)) continue;
767 replacements[oldClass] <- newClass;
770 // 第 1 步:换键。旧项一律删掉,否则热重载每来一次就多一组看不见的实例(§9.42.5 第 5 点)。
771 foreach (oldClass, newClass in replacements) {
772 if (oldClass in this._ecsTypes) {
773 this._ecsTypes[newClass] <- this._ecsTypes[oldClass];
774 this._ecsTypes[newClass].cls = newClass;
775 delete this._ecsTypes[oldClass];
777 if (oldClass in this._ecsViewCache) delete this._ecsViewCache[oldClass];
778 if (oldClass in this._ecsSlotsCache) delete this._ecsSlotsCache[oldClass];
779 if (oldClass in this._ecsFieldSlotsCache) delete this._ecsFieldSlotsCache[oldClass];
780 if (oldClass in this._ecsCompDefaults) delete this._ecsCompDefaults[oldClass];
785 local components = 0;
786 local unresolved = 0;
787 foreach (etype, info in this._ecsTypes) {
788 local slots = this._ecsCollectSlots(etype); // 按新类重算:它引用的是新组件类
789 local fieldSlots = this._ecsCollectFieldSlots(etype);
790 foreach (e in info.instances) {
791 if (e == null || !e.isAlive()) continue;
794 foreach (slotName, compClass in slots) {
795 if (!(slotName in e._comps)) continue;
796 local old = e._comps[slotName];
797 if (old == null) continue;
798 if (compClass in replacements) {
799 // 实体类没被重写:槽位还指向**旧**组件类,引擎改不了类的字段默认值。
803 if (typeof old == "instance" && old.getclass() == compClass) continue;
804 if (this._ecsRepointComponent(e, slotName, old, compClass, fieldSlots)) components += 1;
805 else unresolved += 1;
809 this._ecsInvalidateViews(etype);
811 if (entities > 0) this._ecsRevision += 1;
812 return { entities = entities, components = components, unresolved = unresolved };
815eve.Component <- class {
816 // 引擎侧数据条目的归属。必须是**已声明**成员:Squirrel 的实例只能写已声明槽位,而
817 // `_get`/`_set` 要靠它们找到"这份数据属于哪个实体的哪个组件"。`_` 前缀保证它们
818 // 不会被当成组件字段收进 schema(见 declaredInstanceFields 的过滤)。
821 _componentVersion = 0
826 _componentVersion = 0
845 static function create() {
848 e._eid = eve.allocEntityId()
850 e._slots = eve._ecsCollectSlots(this)
852 local fieldSlots = eve._ecsCollectFieldSlots(this)
853 foreach (name, compClass in e._slots) {
854 // 传实体 id:已登记组件据此盖归属、建引擎侧数据条目(见 `_ecsInstantiateComponent`)。
855 local c = eve._ecsInstantiateComponent(compClass, e._eid)
857 // 已声明的槽位(`pos = Pos`)同时写进实体字段,于是 `e.pos` 与
858 // `e.getComponent(Pos)` 是**同一个对象**,两条路径读写一致(实测,见 §9.38)。
859 // 只登记在 `static components` 表里、没有同名字段的槽位没有字段可写,它只
860 // 能经 getComponent()/hasComponent() 访问。这里因此按"是否真实字段"分流,
861 // 而不是用 try/catch 把真正的失败吞掉。
862 if (name in fieldSlots) e[name] = c
864 eve._ecsRegisterInstance(e, this)
868 // Declare a component slot on this entity class (optional sugar).
869 static function component(name, compClass) {
870 if (!("components" in this) || typeof this.components != "table")
871 this.components <- {}
872 this.components[name] <- compClass
876 function getId() { return _eid }
877 function isAlive() { return _alive }
879 function getComponent(compClass) {
880 if (_slots == null || _comps == null) return null
881 foreach (name, cls in _slots) {
882 if (cls == compClass) {
883 if (name in _comps) return _comps[name]
890 function hasComponent(compClass) {
891 return getComponent(compClass) != null
897 if (_etype != null) eve._ecsUnregisterInstance(this, _etype)
898 // 组件状态一并释放。留着它的话,销毁后的实体仍然可读可写、却对任何 view 无效
899 // (静默 no-op),而且每个组件对象都被这个已销毁的实体继续引用着。
900 // 两条引用都要清:`_comps` 是槽位表,已声明字段槽位是 `e.pos` 那条路。只清前者
901 // 会让 `e.pos` 继续指向一个活着的组件实例,于是对已销毁实体写 `e.pos.x = 1`
902 // 会静默改一个孤儿——正是上面要避免的状态。`this[name] = null` 对**已声明**成员
903 // 是普通赋值,实测不抛("会抛"的旧结论是把 `<-` 的行为记到了 `=` 上,见 §9.38)。
904 if (_slots != null && _etype != null) {
905 local fieldSlots = eve._ecsCollectFieldSlots(_etype)
906 foreach (name, compClass in _slots) {
907 if (name in fieldSlots) this[name] = null
911 // 引擎侧的组件数据也要清:它是权威存储,留着就是"销毁后仍可读"的孤儿数据。
912 eve._ecsDropComponentValues(_eid)
916// Historical name from early game examples
917eve.EntityContainer <- eve.Entity
922 constructor(query = null) {
926 function setQuery(query) { _query = query }
928 function entities() {
929 if (_query == null) return []
930 if (typeof _query == "array") {
932 foreach (q in _query) {
933 foreach (e in eve.view(q)) out.push(e)
937 return eve.view(_query)
940 function update(dt) {}
943// GPU-backed System: pack float component fields → SSBO → compute shader → unpack.
944// Requires eve.Gpgpu / eve.EcsShaderSystem (gpgpu module). Push constants:
945// pc.data[0] = dt, pc.data[1] = entityCount. Each bindFields() maps one binding.
946eve.ShaderSystem <- class extends eve.System {
953 constructor(query = null, gpu = null, glsl = null, localSize = 64) {
954 base.constructor(query)
957 _localSize = localSize
958 if (gpu != null) setGpgpu(gpu)
959 if (gpu != null && glsl != null) setShaderSource(glsl)
962 function setGpgpu(gpu) {
964 if (_backend == null) {
965 if (!("EcsShaderSystem" in eve))
966 throw "eve.ShaderSystem requires gpgpu module (eve.EcsShaderSystem)"
967 _backend = eve.EcsShaderSystem()
969 _backend.setGpgpu(gpu)
970 _backend.setLocalSize(_localSize)
974 function setShaderSource(glsl) {
975 if (_backend == null) throw "eve.ShaderSystem.setShaderSource: call setGpgpu first"
976 _backend.setShaderSource(glsl)
980 function setLocalSize(n) {
982 if (_backend != null) _backend.setLocalSize(n)
986 function setReadback(enabled) {
991 // binding: SSBO index; slot: entity component field name; fields: ["x","y",...]
992 // uploadEachUpdate=false keeps the buffer GPU-resident after its initial upload.
993 // readback=false leaves results resident until requestReadback() is called.
994 function bindFields(binding, slot, fields, uploadEachUpdate = true, readback = null) {
995 _bindings.push({ binding = binding, slot = slot, fields = fields,
996 uploadEachUpdate = uploadEachUpdate,
997 readback = readback, uploadedRevision = -1,
998 uploadRequested = false, readbackRequested = false,
999 uploadFirst = 0, uploadCount = 0,
1000 readbackFirst = 0, readbackCount = 0,
1001 source = null, sourceBinding = -1,
1002 initializeFromCpu = true, schema = null })
1006 // Typed binding schema: { slot, fields, scalar="f32", access="read_write" }.
1007 // write-only bindings allocate storage without an unnecessary CPU upload.
1008 function bindSchema(binding, schema, uploadEachUpdate = false, readback = false) {
1009 if (typeof schema != "table" || !("slot" in schema) || !("fields" in schema))
1010 throw "eve.ShaderSystem.bindSchema: schema requires slot and fields"
1011 if (typeof schema.slot != "string" || typeof schema.fields != "array" ||
1012 schema.fields.len() <= 0)
1013 throw "eve.ShaderSystem.bindSchema: invalid slot or fields"
1014 foreach (field in schema.fields)
1015 if (typeof field != "string")
1016 throw "eve.ShaderSystem.bindSchema: every field must be a string"
1017 local scalar = "scalar" in schema ? schema.scalar : "f32"
1018 if (scalar != "f32")
1019 throw "eve.ShaderSystem.bindSchema: only f32 is currently supported"
1020 local access = "access" in schema ? schema.access : "read_write"
1021 if (access != "read" && access != "write" && access != "read_write")
1022 throw "eve.ShaderSystem.bindSchema: access must be read, write, or read_write"
1023 local normalized = { slot = schema.slot, fields = schema.fields,
1024 scalar = scalar, access = access,
1025 strideFloats = schema.fields.len() }
1026 _bindings.push({ binding = binding, slot = schema.slot, fields = schema.fields,
1027 uploadEachUpdate = access == "write" ? false : uploadEachUpdate,
1028 readback = readback, uploadedRevision = -1,
1029 uploadRequested = false, readbackRequested = false,
1030 uploadFirst = 0, uploadCount = 0,
1031 readbackFirst = 0, readbackCount = 0,
1032 source = null, sourceBinding = -1,
1033 initializeFromCpu = access != "write", schema = normalized })
1037 function getBindingSchema(binding) {
1038 foreach (b in _bindings) if (b.binding == binding) return b.schema
1042 // Generate backend declaration boilerplate; the kernel body remains explicit.
1043 function shaderDeclarations(language = "glsl") {
1045 foreach (b in _bindings) {
1046 if (b.schema == null) continue
1047 if (language == "glsl") {
1048 local qualifier = b.schema.access == "read" ? "readonly " :
1049 b.schema.access == "write" ? "writeonly " : ""
1050 out += "layout(set = 0, binding = " + b.binding + ") " + qualifier +
1051 "buffer EcsBinding" + b.binding + " { float data[]; } ecs" +
1053 } else if (language == "wgsl") {
1054 local access = b.schema.access == "read" ? "read" : "read_write"
1055 out += "@group(0) @binding(" + b.binding + ") var<storage, " + access +
1056 "> ecs" + b.binding + " : array<f32>;\n"
1058 throw "eve.ShaderSystem.shaderDeclarations: language must be glsl or wgsl"
1064 // Reuse another ShaderSystem's resident buffer without a CPU round trip.
1065 // The source system is retained and must be prepared before this consumer.
1066 function bindSharedFields(binding, sourceSystem, sourceBinding, slot, fields,
1068 if (sourceSystem == null)
1069 throw "eve.ShaderSystem.bindSharedFields: source system is null"
1070 _bindings.push({ binding = binding, slot = slot, fields = fields,
1071 uploadEachUpdate = false, readback = readback,
1072 uploadedRevision = -1, uploadRequested = false,
1073 readbackRequested = false, uploadFirst = 0, uploadCount = 0,
1074 readbackFirst = 0, readbackCount = 0,
1075 source = sourceSystem, sourceBinding = sourceBinding,
1076 initializeFromCpu = false, schema = null })
1080 function setBindingUpload(binding, enabled) {
1081 foreach (b in _bindings) if (b.binding == binding) b.uploadEachUpdate = enabled
1085 function setBindingReadback(binding, enabled) {
1086 foreach (b in _bindings) if (b.binding == binding) b.readback = enabled
1090 // Re-upload CPU component values on the next update. binding < 0 selects all.
1091 function requestUpload(binding = -1) {
1092 foreach (b in _bindings) {
1093 if ((binding < 0 || b.binding == binding) && b.source == null) {
1094 b.uploadRequested = true
1102 // Re-upload a stable contiguous entity range. Repeated requests are coalesced.
1103 function requestUploadRange(binding, firstEntity, entityCount) {
1104 if (firstEntity < 0 || entityCount <= 0)
1105 throw "eve.ShaderSystem.requestUploadRange: invalid entity range"
1106 foreach (b in _bindings) {
1107 if (b.binding != binding) continue
1108 if (b.source != null)
1109 throw "eve.ShaderSystem.requestUploadRange: shared binding is GPU-owned"
1110 if (!b.uploadRequested || b.uploadCount == 0) {
1111 b.uploadFirst = firstEntity
1112 b.uploadCount = entityCount
1113 } else if (b.uploadCount >= 0) {
1114 local oldEnd = b.uploadFirst + b.uploadCount
1115 local newEnd = firstEntity + entityCount
1116 local end = oldEnd > newEnd ? oldEnd : newEnd
1117 b.uploadFirst = b.uploadFirst < firstEntity ? b.uploadFirst : firstEntity
1118 b.uploadCount = end - b.uploadFirst
1120 b.uploadRequested = true
1125 // Read GPU values back after the next update. binding < 0 selects all.
1126 function requestReadback(binding = -1) {
1127 foreach (b in _bindings) {
1128 if (binding < 0 || b.binding == binding) {
1129 b.readbackRequested = true
1131 b.readbackCount = -1
1137 // Read back a stable contiguous entity range. Repeated requests are coalesced.
1138 function requestReadbackRange(binding, firstEntity, entityCount) {
1139 if (firstEntity < 0 || entityCount <= 0)
1140 throw "eve.ShaderSystem.requestReadbackRange: invalid entity range"
1141 foreach (b in _bindings) {
1142 if (b.binding != binding) continue
1143 if (!b.readbackRequested || b.readbackCount == 0) {
1144 b.readbackFirst = firstEntity
1145 b.readbackCount = entityCount
1146 } else if (b.readbackCount >= 0) {
1147 local oldEnd = b.readbackFirst + b.readbackCount
1148 local newEnd = firstEntity + entityCount
1149 local end = oldEnd > newEnd ? oldEnd : newEnd
1150 b.readbackFirst = b.readbackFirst < firstEntity ? b.readbackFirst : firstEntity
1151 b.readbackCount = end - b.readbackFirst
1153 b.readbackRequested = true
1158 function setFloat(index, value) {
1159 if (_backend != null) _backend.setFloat(index, value)
1163 function getBackend() { return _backend }
1165 // Register renderer resources and submit a standard 80-byte GpuInstance binding
1166 // without copying the instance stream back through the CPU.
1167 function setGpuDrivenEnabled(enabled) {
1168 if (_gpu == null) throw "eve.ShaderSystem.setGpuDrivenEnabled: call setGpgpu first"
1169 _gpu.setGpuDrivenEnabled(enabled)
1173 function gpuDrivenMeshRecord(mesh) {
1174 if (_gpu == null) throw "eve.ShaderSystem.gpuDrivenMeshRecord: call setGpgpu first"
1175 return _gpu.gpuDrivenMeshRecord(mesh)
1178 function gpuDrivenMaterialRecord(material) {
1180 throw "eve.ShaderSystem.gpuDrivenMaterialRecord: call setGpgpu first"
1181 return _gpu.gpuDrivenMaterialRecord(material)
1184 function submitResidentInstances(binding, buckets, instanceCount = -1,
1186 if (_gpu == null || _backend == null)
1187 throw "eve.ShaderSystem.submitResidentInstances: call setGpgpu first"
1188 local buffer = _backend.getBuffer(binding)
1190 throw "eve.ShaderSystem.submitResidentInstances: binding has no buffer"
1191 if (instanceCount < 0) instanceCount = entities().len()
1192 return _gpu.submitResidentInstances(buffer, buckets, instanceCount, offsetBytes)
1195 function _prepareGpuBatch() {
1196 if (_backend == null || _gpu == null) return
1197 if (!("packEcsFloats" in eve) || !("unpackEcsFloats" in eve)) return
1199 local ents = entities()
1200 local n = ents.len()
1201 if (n <= 0) return null
1203 foreach (b in _bindings) {
1204 local floatsPer = b.fields.len()
1205 if (floatsPer <= 0) continue
1206 if (b.source != null) {
1207 local sourceBackend = b.source.getBackend()
1208 local sourceBuffer = sourceBackend == null ? null :
1209 sourceBackend.getBuffer(b.sourceBinding)
1210 if (sourceBuffer == null)
1211 throw "eve.ShaderSystem shared source must be prepared before consumer"
1212 if (sourceBuffer.getSize() < n * floatsPer * 4)
1213 throw "eve.ShaderSystem shared buffer is smaller than consumer view"
1214 _backend.attachBuffer(b.binding, sourceBuffer)
1217 local buf = _backend.ensureBuffer(b.binding, n * floatsPer)
1218 local structureChanged = b.uploadedRevision != eve._ecsRevision
1219 local fullUpload = (structureChanged && (b.initializeFromCpu || b.uploadRequested)) ||
1220 b.uploadEachUpdate ||
1221 (b.uploadRequested && b.uploadCount < 0)
1223 eve.packEcsFloats(ents, b.slot, b.fields, buf)
1224 b.uploadedRevision = eve._ecsRevision
1225 b.uploadRequested = false
1227 } else if (structureChanged) {
1228 // Output-only schema: capacity/order changed, but the shader is
1229 // authoritative and promises to initialize every accessed record.
1230 b.uploadedRevision = eve._ecsRevision
1231 } else if (b.uploadRequested) {
1232 if (!("packEcsFloatsRange" in eve))
1233 throw "eve.ShaderSystem.requestUploadRange requires gpgpu range packing"
1234 eve.packEcsFloatsRange(ents, b.slot, b.fields, buf,
1235 b.uploadFirst, b.uploadCount)
1236 b.uploadRequested = false
1240 return { entities = ents, count = n }
1243 function _completeGpuBatch(batch) {
1244 if (batch == null) return
1245 local ents = batch.entities
1246 local n = batch.count
1247 foreach (b in _bindings) {
1248 local shouldReadback = b.readback == null ? _readback : b.readback
1249 if (shouldReadback || (b.readbackRequested && b.readbackCount < 0)) {
1250 local floatsPer = b.fields.len()
1251 if (floatsPer <= 0) continue
1252 local buf = _backend.getBuffer(b.binding)
1253 eve.unpackEcsFloats(ents, b.slot, b.fields, buf, n)
1254 b.readbackRequested = false
1256 } else if (b.readbackRequested) {
1257 if (!("unpackEcsFloatsRange" in eve))
1258 throw "eve.ShaderSystem.requestReadbackRange requires gpgpu range unpacking"
1259 local buf = _backend.getBuffer(b.binding)
1260 eve.unpackEcsFloatsRange(ents, b.slot, b.fields, buf,
1261 b.readbackFirst, b.readbackCount)
1262 b.readbackRequested = false
1268 // Record into a shared GpuSequence. Call completeRecorded(batch) after submit().
1269 function record(sequence, dt) {
1270 if (sequence == null) throw "eve.ShaderSystem.record: sequence is null"
1271 local batch = _prepareGpuBatch()
1272 if (batch != null) _backend.recordDispatch(sequence, batch.count, dt)
1276 function completeRecorded(batch) {
1277 _completeGpuBatch(batch)
1281 function update(dt) {
1282 local batch = _prepareGpuBatch()
1283 if (batch == null) return
1284 _backend.dispatch(batch.count, dt)
1285 _completeGpuBatch(batch)
1289function eve::view(entityClass) {
1290 if (entityClass == null) return []
1291 // C++ 桥接类的实体在脚本外增删(无法通知脚本),不缓存,每次新鲜收集
1292 local cppBacked = false
1293 if ("_cppHasView" in this) cppBacked = this._cppHasView(entityClass)
1295 // 每次调用都返回**新数组**:缓存只保存脚本侧收集结果(遍历 _ecsTypes 才是贵的
1296 // 那一步),绝不外借。否则调用方 sort/pop/append 自己的视图就会污染其他使用者。
1299 this._ecsCollectInstances(entityClass, out)
1301 if (!(entityClass in this._ecsViewCache)) {
1302 local collected = []
1303 this._ecsCollectInstances(entityClass, collected)
1304 this._ecsViewCache[entityClass] <- collected
1306 local cached = this._ecsViewCache[entityClass]
1307 local count = cached.len()
1309 for (local i = 0; i < count; ++i) out[i] = cached[i]
1311 if ("_cppCollect" in this) this._cppCollect(entityClass, out)
1312 // No sort here. Entities appended by a registered C++ collector
1313 // (registerCppEntityView) are not `eve.Entity` instances and have no `_eid`; sorting them
1314 // threw "the index '_eid' does not exist" (caught by ECS.script.cppCreatedEntitiesVisible).
1315 // The collector owns their order; the id-ordered contract covers script instances, which
1316 // `_ecsCollectInstances` already sorted.
1320function eve::ecsReady() {
1321 // This function is installed only after the complete ECS script has run.
1322 // Avoid probing the delegated eve table here: Squirrel's `in` lookup may
1323 // invoke its lazy _get handler and turn a readiness query into an error.
1328void injectEcsScript(ssq::Table& eveTable) {
1330 const SQInteger
top = sq_gettop(
vm);
1331 if (SQ_FAILED(sq_compilebuffer(
vm, kEcsScript,
1332 static_cast<SQInteger
>(std::strlen(kEcsScript)),
1333 "ecs.nut", SQTrue))) {
1336 std::fprintf(stderr,
"EVEngine: ECS bootstrap script failed to compile: %s\n",
1337 ctx.empty() ?
"unknown error" : ctx.
message.c_str());
1340 sq_pushroottable(
vm);
1341 if (SQ_FAILED(sq_call(
vm, 1, SQFalse, SQTrue))) {
1343 std::fprintf(stderr,
"EVEngine: ECS bootstrap script failed to run: %s\n",
1344 ctx.empty() ?
"unknown error"
1355void cppCollect(ssq::Class
cls, ssq::Array
out) {
1357 const SQInteger
top = sq_gettop(
vm);
1358 sq_pushobject(
vm,
cls.getRaw());
1359 for (
int guard = 0; guard < 64; ++guard) {
1360 if (sq_gettype(
vm, -1) != OT_CLASS)
1363 sq_getstackobj(
vm, -1, &cur);
1364 auto it = cppEntityViews().find(cur._unVal.pClass);
1365 if (it != cppEntityViews().
end()) {
1370 if (SQ_FAILED(sq_getbase(
vm, -1)))
1382bool cppHasView(ssq::Object
cls) {
1383 if (
cls.getType() != ssq::Type::CLASS)
return false;
1385 const SQInteger
top = sq_gettop(
vm);
1386 sq_pushobject(
vm,
cls.getRaw());
1387 for (
int guard = 0; guard < 64; ++guard) {
1388 if (sq_gettype(
vm, -1) != OT_CLASS)
break;
1390 sq_getstackobj(
vm, -1, &cur);
1391 if (cppEntityViews().find(cur._unVal.pClass) != cppEntityViews().
end()) {
1395 if (SQ_FAILED(sq_getbase(
vm, -1)))
break;
1405 if (instance.getType() != ssq::Type::INSTANCE)
1407 "component field access needs a component instance", field, {},
1412 "component field access needs a live script VM", field, {},
1415 const SQInteger
top = sq_gettop(
vm);
1416 sq_pushobject(
vm, instance.getRaw());
1418 ScriptComponentStoreKey
key;
1419 if (instanceIdentity(
vm, -1, &
key)) {
1428 sq_pushstring(
vm,
field.c_str(),
static_cast<SQInteger
>(
field.size()));
1429 if (SQ_FAILED(sq_get(
vm, -2))) {
1440 if (instance.getType() != ssq::Type::INSTANCE)
1442 "component field access needs a component instance", field, {},
1447 "component field access needs a live script VM", field, {},
1450 const SQInteger
top = sq_gettop(
vm);
1451 sq_pushobject(
vm, instance.getRaw());
1453 ScriptComponentStoreKey
key;
1454 if (instanceIdentity(
vm, -1, &
key)) {
1460 sq_pushstring(
vm,
field.c_str(),
static_cast<SQInteger
>(
field.size()));
1468 if (SQ_FAILED(sq_set(
vm, -3))) {
1483 "script component version must be a positive integer",
name, {},
1485 if (
cls.getType() != ssq::Type::CLASS)
1487 "eve.component needs a class, not a value or instance",
name, {},
1491 HSQOBJECT o =
cls.getRaw();
1496 const std::vector<DeclaredField>
fields = declaredFields(o);
1497 const std::vector<std::string> names = fieldNames(
fields);
1503 for (
const std::string& field : names) {
1504 Result<Value>
value = classFieldDefault(
vm, o, field);
1510 Result<void>
seam = installComponentFieldSeam(
vm, o,
fields);
1516 auto&
current = currentScriptComponents();
1533 "script component generation counter is exhausted",
name, {},
1545 found->second = ScriptComponentEntry(
vm, o, *next, names, std::move(
defaults));
1551 const auto&
current = currentScriptComponents();
1559 std::vector<ScriptComponentRecord>
out;
1560 out.reserve(currentScriptComponents().
size() + retiredScriptComponents().
size());
1561 for (
const auto& [
key, entry] : currentScriptComponents())
1564 for (
const ScriptComponentRecord&
retired : retiredScriptComponents())
out.push_back(
retired);
1565 std::sort(
out.begin(),
out.end(), [](
const ScriptComponentRecord&
a,
const ScriptComponentRecord&
b) {
1566 if (a.name != b.name) return a.name < b.name;
1567 if (a.version != b.version) return a.version < b.version;
1568 return a.generation < b.generation;
1574 const auto&
current = currentScriptComponents();
1578 DiagnosticCode::NotFound,
"script component is not registered in this VM",
name, {},
"ecs.component"));
1583 out.generation =
found->second.generation;
1585 out.defaults =
found->second.defaults;
1590 table.set(
"Number", std::string(
"number"));
1591 table.set(
"Boolean", std::string(
"boolean"));
1592 table.set(
"String", std::string(
"string"));
1595 table.addFunc(
"inspectClassFields", inspectClassFields);
1596 table.addFunc(
"isSubclass", scriptIsSubclass);
1597 table.addFunc(
"getClassBase", getClassBase);
1598 table.addFunc(
"allocEntityId", allocEntityId);
1599 table.addFunc(
"_cppHasView", cppHasView);
1603 table.addFunc(
"component", [
vm = table.getHandle()](std::string
name,
int version, ssq::Object
cls) {
1604 return script::projectResult(
1605 vm, registerScriptComponent(name, SchemaVersion(static_cast<std::uint64_t>(version)), cls));
1607 table.addFunc(
"_cppCollect", std::function<
void(ssq::Class, ssq::Array)>(cppCollect));
1611 table.addFunc(
"_ecsBindComponentValues",
1612 [](std::uint64_t entityId, ssq::Object instance) {
return bindComponentValues(entityId, instance); });
1613 table.addFunc(
"_ecsDropComponentValues",
1614 [](std::uint64_t entityId) {
return dropScriptComponentValues(entityId); });
1616 injectEcsScript(table);
1618 ecsScriptInjected() =
true;
1620 postEcsHooksFlushed() = 0;
1627 cppEntityViews().clear();
1634 currentScriptComponents().clear();
1635 retiredScriptComponents().clear();
1638 ecsScriptInjected() =
false;
1639 postEcsHooksFlushed() = 0;
1643 cppEntityViews()[
cls.getRaw()._unVal.pClass] = std::move(
fn);
1647 postEcsHooks().push_back(std::move(
fn));
1651 if (!ecsScriptInjected())
return;
1652 auto& hooks = postEcsHooks();
1653 auto&
n = postEcsHooksFlushed();
1654 while (
n < hooks.size()) {
1666 ssq::Table eveTable(
vm.find(
"eve"));
std::vector< std::unique_ptr< ScriptClimbingEventSink > > retired
struct SQVM * HSQUIRRELVM
std::vector< Value > defaults
ScriptComponentRecord record
std::vector< std::string > fields
std::vector< std::uint8_t > stored
std::shared_ptr< const OceanSprayFrame > previous
std::set< std::string > values
The single Squirrel projection for common Result, Status and Value.
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
void ignore(std::string_view reason={}) const noexcept
Explicitly discard this result after documenting the reason.
Move-only operation result carrying either a value or Status.
static Result success(T value)
Construct a successful result owning value.
static Result failure(Status status)
Construct a failed result from a structured status.
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
static Value null()
Compatibility factory for a null value.
std::map< std::string, Value > Object
static Value object(Object value)
Compatibility factory for an object value.
const Value * field(const Value &value, const char *key)
Borrow an optional object field.
std::variant< std::monostate, std::int64_t, double, std::string, bool > Value
constexpr HexDirection next(HexDirection d) noexcept
The next direction clockwise (NW wraps to NE).
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...
std::string formatScriptError(const ScriptErrorContext &ctx)
Formats a context into a human-readable multi-line report.
ScriptErrorContext takeLastScriptError(HSQUIRRELVM vm)
Consumes and clears the last recorded error for a VM.
Result< void > pushValue(HSQUIRRELVM vm, const Value &value, const SquirrelValueOptions &options)
Push a canonical Value into the active Squirrel VM.
ScriptErrorContext captureCompileError(HSQUIRRELVM vm)
Captures the last compilation error recorded by the VM.
Result< Value > valueFromSquirrel(HSQUIRRELVM vm, SQInteger index, const SquirrelValueOptions &options)
Convert one Squirrel value into the canonical owning Value tree.
Build metadata (engine git commit, build time, third-party version).
std::size_t removeScriptComponentValues(std::uint64_t entityId)
实体销毁时清掉它的全部组件数据。
void exposeECSToVM(ssq::VM &vm)
在 ModuleManager::expose 之后调用;保证 eve.Component 等不被其它模块覆盖。
const Value * findScriptComponentValues(const ScriptComponentStoreKey &key)
读一条组件数据。
detail::StrongUint64< detail::GenerationTag > Generation
Registry/object replacement generation used to reject stale handles.
Result< ScriptComponentDeclaredSchema > scriptComponentDeclaredSchema(const std::string &name, SchemaVersion version)
读一条已登记组件的声明 schema(字段名 + 声明默认值)。
Result< void > setScriptComponentValues(const ScriptComponentStoreKey &key, Value values)
写入一条组件的引擎侧数据(创建实体、或迁移到新代时调用)。
void exposeECS(ssq::Table &table)
脚本侧 ECS:Entity / Component / System / ShaderSystem / view(见 ECS.cpp)。 C++ 游戏实体仍直接用 ECS....
void prepareEcsScriptInjection()
Resets per-VM script injection bookkeeping before a new VM is exposed.
EVENGINE_API_FOUNDATION Result< Value > readScriptComponentField(const ssq::Object &instance, const std::string &field)
读一个脚本组件实例的字段,**不关心这个字段存在哪**。
void registerPostEcsHook(PostEcsHook fn)
Registers post ecs hook.
detail::StrongUint64< detail::SchemaVersionTag > SchemaVersion
Persistent data-format version; not a runtime replacement generation.
std::function< void(ssq::Table &table)> PostEcsHook
在脚本 ECS 基类(eve.Component / eve.Entity / eve.System)注入之后执行的回调。 模块用它注入"extends eve.Entity"的脚本基类(例如 eve....
void flushPostEcsHooks(ssq::Table &table)
Run post-ECS hooks that were registered after exposeECS already ran.
std::function< void(ssq::Array &out)> CppEntityViewFn
C++ 实体 → 脚本 eve.view() 桥接。 用 registerCppEntityView(cls, fn) 登记脚本类的收集函数; 脚本 eve.view(cls) 沿类链找到登记的 C++...
Result< void > setScriptComponentField(const ScriptComponentStoreKey &key, const std::string &field, Value value)
写一个字段(脚本侧的写入与原生侧的写入都走这里)。
void clearScriptComponentStore()
换 VM 时清空:脚本世界连同它的组件数据一起消失。
void registerCppEntityView(const ssq::Class &cls, CppEntityViewFn fn)
Registers cpp entity view.
std::vector< ScriptComponentRecord > scriptComponentRecords()
当前 VM 的全部登记(含 retired 历史),按名字、版本、代际排序。 @cost 一次拷贝;仅供编辑器/诊断/测试等非热路径使用。
EVENGINE_API_FOUNDATION Result< void > writeScriptComponentField(const ssq::Object &instance, const std::string &field, const Value &value)
写一个脚本组件实例的字段,归属规则见 readScriptComponentField。
void reconcileScriptComponentValues(const std::string &name, SchemaVersion version, const std::vector< std::string > &fields, const std::vector< Value > &defaults)
把某个组件(名字 + 版本)在**所有实体**上的数据重建到新 schema 上(热重载换代)。
Result< Value > scriptComponentField(const ScriptComponentStoreKey &key, const std::string &field)
读一个字段。
Result< void > registerScriptComponent(const std::string &name, SchemaVersion version, const ssq::Object &cls)
登记一个脚本组件:eve.component(name, version, cls) 的 C++ 侧。
const ScriptComponentRecord * findScriptComponent(const std::string &name, SchemaVersion version)
当前未退役的那条登记。
SettlementPipeline::Stage fn
一条已登记组件的**声明 schema**:字段名与它们的声明默认值。
Generation generation
代际:同名同版本每次重新登记 +1。