载入中...
搜索中...
未找到
CrowdBatchBindings.cpp
浏览该文件的文档.
3
4#include <limits>
5
6namespace eve::crowd {
7namespace {
8std::int64_t integerField(const ssq::Table& table, const char* key) {
9 const auto value = table.find(key);
10 if (value.getType() != ssq::Type::INTEGER) throw ssq::TypeException("Agent reference needs integer fields");
11 return value.to<std::int64_t>();
12}
13AgentRef parseReference(const ssq::Table& table) {
14 const auto owner = integerField(table, "owner"), index = integerField(table, "index"),
15 generation = integerField(table, "generation");
16 if (owner <= 0 || index < 0 || index >= AgentHandle::invalidIndex || generation <= 0 ||
17 generation > std::numeric_limits<std::uint32_t>::max())
18 throw ssq::TypeException("Agent reference out of range");
19 return {AgentHandle(static_cast<std::uint32_t>(index), static_cast<std::uint32_t>(generation)),
20 static_cast<std::uint64_t>(owner)};
21}
22Value projectReference(AgentRef reference) {
23 return Value(Value::Object{{"owner", Value(static_cast<std::int64_t>(reference.owner))},
24 {"index", Value(static_cast<std::int64_t>(reference.handle.index()))},
25 {"generation", Value(static_cast<std::int64_t>(reference.handle.generation()))}});
26}
27Value projectState(AgentState state) {
28 return Value(Value::Object{
29 {"x", Value(state.x)},
30 {"y", Value(state.y)},
31 {"heading", Value(state.heading)},
32 {"vx", Value(state.vx)},
33 {"vy", Value(state.vy)},
34 {"speed", Value(state.speed)},
35 {"action", Value(state.action)},
36 {"data", Value(state.data)},
37 {"avoidancePriority", Value(state.avoidancePriority)},
38 {"flowGeneration", Value(std::to_string(state.flowGeneration))},
39 {"movement", Value(Value::Object{{"classId", Value(std::to_string(state.movement.movement.value()))},
40 {"revision", Value(std::to_string(state.movement.revision))}})}});
41}
42Value projectReceipt(AgentBatchReceipt receipt) {
43 return Value(Value::Object{{"applied", Value(static_cast<std::int64_t>(receipt.applied))}});
44}
45template <class T>
46std::optional<T> optionalField(const ssq::Table& table, const char* key) {
47 try {
48 return table.find(key).to<T>();
49 } catch (const ssq::NotFoundException&) {
50 return std::nullopt;
51 }
52}
53AgentUpdate parseUpdate(Crowd& crowd, const ssq::Table& table) {
54 AgentUpdate update;
55 update.reference = parseReference(table.find("reference").to<ssq::Table>());
56 const auto flow = optionalField<ssq::Table>(table, "flowRequest");
57 const auto defaultFlow = optionalField<bool>(table, "useDefaultFlow");
58 if (flow && defaultFlow) throw ssq::TypeException("flowRequest and useDefaultFlow cannot be combined");
59 if (flow) {
60 auto resolved = resolveFlowRequestLease(crowd, *flow);
61 if (!resolved) throw ssq::TypeException("Invalid, stale or foreign request-owned lease");
62 update.flow = std::move(resolved).takeValue();
63 }
64 if (defaultFlow && *defaultFlow) update.flow = FlowLease{};
65
66 if (auto item = optionalField<ssq::Table>(table, "movement")) update.movement = parseMovementBinding(*item);
67 update.maxSpeed = optionalField<float>(table, "maxSpeed");
68 update.maxAcceleration = optionalField<float>(table, "maxAcceleration");
69 update.headingTurnRate = optionalField<float>(table, "headingTurnRate");
70 update.radius = optionalField<float>(table, "radius");
71 update.avoidancePriority = optionalField<int>(table, "avoidancePriority");
72 update.data = optionalField<int>(table, "data");
73 update.holdPosition = optionalField<bool>(table, "holdPosition");
74 if (auto item = optionalField<ssq::Table>(table, "interaction")) {
75 update.interaction = {item->get<float>("pushability"), item->get<bool>("holdPosition"), item->get<int>("layer"),
76 item->get<int>("mask")};
77 }
78 if (auto item = optionalField<ssq::Table>(table, "policy")) update.policy = parseInteractionPolicy(*item);
79 if (auto item = optionalField<ssq::Table>(table, "intent")) {
80 const auto action = item->get<std::string>("action");
81 AgentAction mode;
82 if (action == "idle")
83 mode = AgentAction::Idle;
84 else if (action == "flow")
85 mode = AgentAction::Flow;
86 else if (action == "seek")
87 mode = AgentAction::Seek;
88 else if (action == "boids")
89 mode = AgentAction::Boids;
90 else
91 throw ssq::TypeException("Unknown steering action");
92 update.intent = {mode, item->get<bool>("hasTarget"), item->get<float>("targetX"), item->get<float>("targetY")};
93 }
94 return update;
95}
96template <class T>
97Result<T> malformed(const std::exception& error) {
99}
100Value projectFrame(const AgentFrame& frame) {
102 rows.reserve(frame.agents.size());
103 for (const auto& entry : frame.agents)
104 rows.emplace_back(
105 Value::Object{{"reference", projectReference(entry.reference)}, {"state", projectState(entry.state)}});
106 return Value(Value::Object{{"agents", Value(std::move(rows))},
107 {"tick", Value(std::to_string(frame.tick.value()))},
108 {"simulationSeconds", Value(frame.simulationSeconds)}});
109}
110} // namespace
111
112MovementBinding parseMovementBinding(const ssq::Table& table) {
113 const auto identity = integerField(table, "classId"), revision = integerField(table, "revision");
114 if (identity < 0 || revision < 0 || ((identity == 0) != (revision == 0)))
115 throw ssq::TypeException("Movement class needs both positive identities or both zero");
116 return {MovementClassId(static_cast<std::uint64_t>(identity)), static_cast<std::uint64_t>(revision)};
117}
118
120 const auto mask = [&](const char* key) {
121 const auto value = integerField(table, key);
122 if (value < 0 || value > std::numeric_limits<int>::max())
123 throw ssq::TypeException("Interaction mask out of range");
124 return static_cast<int>(value);
125 };
126 return {table.get<float>("pushability"),
127 table.get<bool>("holdPosition"),
128 mask("avoidanceLayer"),
129 mask("avoidanceMask"),
130 mask("contactLayer"),
131 mask("contactMask")};
132}
133
134void exposeAgentBatches(ssq::Class& cls) {
135 cls.addFunc("advanceTick", [vm = cls.getHandle()](Crowd* crowd, ssq::Table input) {
136 CrowdStep step;
137 try {
138 const auto tick = integerField(input, "tick");
139 if (tick < 0) throw ssq::TypeException("Tick must be nonnegative");
140 step.tick = SimulationTick(static_cast<std::uint64_t>(tick));
141 step.delta = Duration::fromNanoseconds(integerField(input, "deltaNanoseconds"));
142 if (auto budget = optionalField<ssq::Table>(input, "budget")) {
143 const auto boundedInt = [&](const char* key, int& destination) {
144 if (budget->find(key).getType() != ssq::Type::INTEGER)
145 throw ssq::TypeException("Budget needs integer fields");
146 const auto value = integerField(*budget, key);
147 if (value < 0 || value > std::numeric_limits<int>::max())
148 throw ssq::TypeException("Budget out of range");
149 destination = static_cast<int>(value);
150 };
151 boundedInt("maxSubsteps", step.budget.maxSubsteps);
152 boundedInt("maxContactPasses", step.budget.maxContactPasses);
153 step.budget.maxGridCells = integerField(*budget, "maxGridCells");
154 step.budget.maxNeighborVisits = integerField(*budget, "maxNeighborVisits");
155 step.budget.maxPredictionChecks = integerField(*budget, "maxPredictionChecks");
156 step.budget.maxContactChecks = integerField(*budget, "maxContactChecks");
157 try {
158 step.budget.maxSpatialVisits = integerField(*budget, "maxSpatialVisits");
159 } catch (const ssq::NotFoundException&) {
160 // Absent extension retains the canonical unlimited query budget.
161 }
162 try {
163 step.budget.maxContactPairs = integerField(*budget, "maxContactPairs");
164 } catch (const ssq::NotFoundException&) {
165 }
166 try {
167 step.budget.maxPairVisits = integerField(*budget, "maxPairVisits");
168 } catch (const ssq::NotFoundException&) {
169 }
170 try {
171 step.budget.maxPreferredNeighbors = integerField(*budget, "maxPreferredNeighbors");
172 } catch (const ssq::NotFoundException&) {
173 }
174 try {
175 step.budget.maxPreferredVisits = integerField(*budget, "maxPreferredVisits");
176 } catch (const ssq::NotFoundException&) {
177 }
178 }
179 } catch (const std::exception& error) {
180 return script::projectResult(vm, malformed<StepReport>(error), [](StepReport) { return Value(); });
181 }
182 return script::projectResult(vm, crowd->advance(step), [](StepReport report) {
183 return Value(Value::Object{{"tick", Value(std::to_string(report.tick.value()))},
184 {"elapsedNanoseconds", Value(report.elapsed.nanoseconds())},
185 {"quality", Value(static_cast<int>(report.quality))},
186 {"navigationState", Value(static_cast<int>(report.navigation.state))},
187 {"navigationRevision", Value(std::to_string(report.navigation.revision))},
188 {"navigationClassMismatches", Value(report.navigationClassMismatches)},
189 {"candidatesVisited", Value(report.candidatesVisited)},
190 {"gridBuilds", Value(report.gridBuilds)},
191 {"gridCellsPeak", Value(report.gridCellsPeak)},
192 {"cellsVisited", Value(report.cellsVisited)},
193 {"gridEntriesPeak", Value(report.gridEntriesPeak)},
194 {"gridSortComparisons", Value(report.gridSortComparisons)},
195 {"spatialVisits", Value(report.spatialVisits)},
196 {"contactPairsPeak", Value(report.contactPairsPeak)},
197 {"pairVisits", Value(report.pairVisits)},
198 {"preferredNeighborsPeak", Value(report.preferredNeighborsPeak)},
199 {"preferredVisits", Value(report.preferredVisits)},
200 {"contactPairsChecked", Value(report.contactPairsChecked)},
201 {"residualPairsChecked", Value(report.residualPairsChecked)},
202 {"avoidanceChecks", Value(report.avoidanceChecks)},
203 {"substeps", Value(report.substeps)}});
204 });
205 });
206 cls.addFunc("setInteractionPolicy", [vm = cls.getHandle()](Crowd* crowd, ssq::Table reference, ssq::Table policy) {
207 AgentRef ref;
208 InteractionPolicy settings;
209 try {
210 ref = parseReference(reference);
211 settings = parseInteractionPolicy(policy);
212 } catch (const std::exception& error) {
213 return script::projectResult(vm, malformed<void>(error));
214 }
215 return script::projectResult(vm, crowd->setInteractionPolicy(ref, settings));
216 });
217 cls.addFunc("readInteractionPolicy", [vm = cls.getHandle()](Crowd* crowd, ssq::Table reference) {
218 const auto project = [](InteractionPolicy policy) {
219 return Value(Value::Object{{"pushability", Value(policy.pushability)},
220 {"holdPosition", Value(policy.holdPosition)},
221 {"avoidanceLayer", Value(policy.avoidanceLayer)},
222 {"avoidanceMask", Value(policy.avoidanceMask)},
223 {"contactLayer", Value(policy.contactLayer)},
224 {"contactMask", Value(policy.contactMask)}});
225 };
226 AgentRef ref;
227 try {
228 ref = parseReference(reference);
229 } catch (const std::exception& error) {
230 return script::projectResult(vm, malformed<InteractionPolicy>(error), project);
231 }
232 return script::projectResult(vm, crowd->readInteractionPolicy(ref), project);
233 });
234 cls.addFunc("agentRef", [vm = cls.getHandle()](Crowd* crowd, int slot) {
235 return script::projectResult(vm, crowd->agentRef(slot), projectReference);
236 });
237 cls.addFunc("resolveNamedAgent", [vm = cls.getHandle()](Crowd* crowd, std::string name) {
238 return script::projectResult(vm, crowd->resolveNamedAgent(name), projectReference);
239 });
240 cls.addFunc("isAgentAlive", [](Crowd* crowd, ssq::Table reference) {
241 try {
242 return crowd->isAgentAlive(parseReference(reference));
243 } catch (const std::exception&) {
244 return false;
245 }
246 });
247 cls.addFunc("readAgent", [vm = cls.getHandle()](Crowd* crowd, ssq::Table reference) {
248 try {
249 return script::projectResult(vm, crowd->readAgent(parseReference(reference)), projectState);
250 } catch (const std::exception& error) {
251 return script::projectResult(vm, malformed<AgentState>(error), projectState);
252 }
253 });
254 cls.addFunc("updateAgents", [vm = cls.getHandle()](Crowd* crowd, ssq::Array agents) {
255 AgentUpdateBatch batch;
256 try {
257 batch.agents.reserve(agents.size());
258 for (std::size_t index = 0; index < agents.size(); ++index)
259 batch.agents.push_back(parseUpdate(*crowd, agents.get<ssq::Table>(index)));
260 } catch (const std::exception& error) {
261 return script::projectResult(vm, malformed<AgentBatchReceipt>(error), projectReceipt);
262 }
263 return script::projectResult(vm, crowd->updateAgents(batch), projectReceipt);
264 });
265 cls.addFunc("removeAgents", [vm = cls.getHandle()](Crowd* crowd, ssq::Array agents) {
266 AgentRemovalBatch batch;
267 try {
268 batch.agents.reserve(agents.size());
269 for (std::size_t index = 0; index < agents.size(); ++index)
270 batch.agents.push_back(parseReference(agents.get<ssq::Table>(index)));
271 } catch (const std::exception& error) {
272 return script::projectResult(vm, malformed<AgentBatchReceipt>(error), projectReceipt);
273 }
274 return script::projectResult(vm, crowd->removeAgents(batch), projectReceipt);
275 });
276 cls.addFunc("relocateAgents", [vm = cls.getHandle()](Crowd* crowd, ssq::Array agents, int maxChecks) {
277 AgentRelocationBatch batch;
278 batch.maxChecks = maxChecks;
279 try {
280 if (agents.size() > 1024) throw ssq::TypeException("Relocation batches support at most 1024 agents");
281 batch.agents.reserve(agents.size());
282 for (std::size_t index = 0; index < agents.size(); ++index) {
283 auto item = agents.get<ssq::Table>(index);
284 batch.agents.push_back(
285 {parseReference(item.get<ssq::Table>("reference")), item.get<float>("x"), item.get<float>("y")});
286 }
287 } catch (const std::exception& error) {
288 return script::projectResult(vm, malformed<AgentBatchReceipt>(error), projectReceipt);
289 }
290 return script::projectResult(vm, crowd->relocateAgents(batch), projectReceipt);
291 });
292 cls.addFunc("copyAgentFrame", [vm = cls.getHandle()](Crowd* crowd) {
293 AgentFrame frame;
294 auto copied = crowd->copyAgentFrame(frame);
295 if (!copied)
296 return script::projectResult(vm, Result<Value>::failure(copied.status()),
297 [](Value value) { return value; });
298 return script::projectResult(vm, Result<Value>::success(projectFrame(frame)),
299 [](Value value) { return value; });
300 });
301 cls.addFunc("copyAgentStates", [vm = cls.getHandle()](Crowd* crowd, ssq::Array agents) {
302 try {
303 std::vector<AgentRef> references;
304 references.reserve(agents.size());
305 for (std::size_t index = 0; index < agents.size(); ++index)
306 references.push_back(parseReference(agents.get<ssq::Table>(index)));
307 AgentFrame frame;
308 auto copied = crowd->copyAgentStates(references, frame);
309 if (!copied)
310 return script::projectResult(vm, Result<Value>::failure(copied.status()),
311 [](Value value) { return value; });
312 return script::projectResult(vm, Result<Value>::success(projectFrame(frame)),
313 [](Value value) { return value; });
314 } catch (const std::exception& error) {
315 return script::projectResult(vm, malformed<Value>(error), [](Value value) { return value; });
316 }
317 });
318}
319
320} // namespace eve::crowd
std::uint64_t revision
AuthorityStoreHandleRef reference
Definition Authority.cpp:24
int mask
HSQUIRRELVM vm
Definition ECS.cpp:38
HSQOBJECT cls
Definition ECS.cpp:39
SQObjectPtr key
Definition ECS.cpp:155
Generation generation
Definition ECS.cpp:40
std::string name
Definition ECS.cpp:154
EvpackChunkInput input
Definition Evpack.cpp:170
int rows
OceanWakeSettings settings
std::shared_ptr< OceanGpuSpectrum > owner
ssq::Object frame
std::string error
Definition Package.cpp:174
std::string action
Definition PlayHost.cpp:118
Object::Ptr value
std::string slot
RoadNetwork resolved
The single Squirrel projection for common Result, Status and Value.
float step
Definition TreeMesh.cpp:451
uint32_t index
uint64_t identity
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
static constexpr index_type invalidIndex
Reserved index value shared by all invalid handles.
The canonical owning dynamic value used by data-facing protocols.
Definition Value.h:31
std::map< std::string, Value > Object
Definition Value.h:34
std::vector< Value > Array
Definition Value.h:33
群体行为模块:连续流场寻路 + 海量单位移动/转向/行动 + Boids 鸟群。
Definition Crowd.h:266
Result< StepReport > advance(float dt)
Advance using bounded simultaneous integration and contact projection.
Result< FlowLease > resolveFlowRequestLease(Crowd &crowd, const ssq::Table &token)
Resolve a checked request-owned lease without retaining script table references.
MovementBinding parseMovementBinding(const ssq::Table &table)
Decode exact integer movement identities; no floating-point identity coercion.
void exposeAgentBatches(ssq::Class &cls)
Compose public numeric identity/batch bindings without accessing private storage.
RuntimeHandle< CrowdAgentTag > AgentHandle
Generation-qualified runtime agent identity; never persist its packed representation.
Definition CrowdTypes.h:82
InteractionPolicy parseInteractionPolicy(ssq::Table table)
Decode a canonical policy at the script boundary; throws on missing or wrongly typed fields.
AgentAction
Strong locomotion intent; numeric values retain compatibility action codes.
Definition Crowd.h:153
std::variant< std::monostate, std::int64_t, double, std::string, bool > Value
Definition Database.h:27
Snapshot project(Files files, Object::Ptr stats, std::string defaultProjectId, std::string projectDir)
Build a candidate evidence graph without touching the published snapshot.
std::unordered_map< std::string, SkillDefinition > & table()
Definition Skill.cpp:73
Canonical independent predictive-steering and body-contact policy; both filters are symmetric.
Definition Crowd.h:145
Agent-owned selection of a provider-defined movement policy. Zero identity and revision mean compatib...
Definition CrowdTypes.h:27
Owning observations of one completed advance; simulation-thread only.
Definition Crowd.h:94