载入中...
搜索中...
未找到
SceneCameraQueries.cpp
浏览该文件的文档.
1#include <algorithm>
2#include <cmath>
3#include <cstring>
4#include <glm/glm.hpp>
5#include <string>
6#include <utility>
7#include <vector>
8#include "common/Capability.h"
9#include "scene/Scene.h"
10#include "scene/SceneBounds.h"
13#include "scene/SceneHost.h"
14#include "scene/SceneLink.h"
15#include "scene/SceneNodeRef.h"
17
18// SceneCameraQueries.cpp
19// Picking / culling entry points whose camera math belongs to graphics.
20//
21// The traversal and mutation stay here because the scene owns them; only the
22// screen ray and the clip matrix come from the ISceneCameraProjection
23// capability (graphics/ScenePicking.cpp registers it). Querying a capability
24// instead of calling graphics keeps this module free of an upward include while
25// still defining these symbols in scene, which a per-layer DLL split needs:
26// graphics (L4) cannot be imported by scene (L1).
27//
28// Split out of Scene.cpp (already past the ~1000 line limit) rather than
29// appended to it.
30
31
32namespace eve::scene {
33
34std::string Scene::pickScreenAt(const std::string &hostName, graphics::Camera3D *cam, float screenX, float screenY,
35 float viewW, float viewH) const {
36 if (!cam) return {};
37 auto *projection = eve::cap::query<ISceneCameraProjection>();
38 if (!projection) return {};
39 const auto ray = projection->screenRay(*cam, screenX, screenY, viewW, viewH);
40 if (!ray) return {};
41 return pickRayAt(hostName, ray->origin.x, ray->origin.y, ray->origin.z, ray->direction.x, ray->direction.y,
42 ray->direction.z);
43}
44
45std::vector<std::string> Scene::collectFrustumIdsAt(const std::string &hostName, graphics::Camera3D *cam, float viewW,
46 float viewH) const {
47 SceneHost *h = resolveHost(hostName);
48 std::vector<std::string> out;
49 if (!h || !cam || viewW <= 0.f || viewH <= 0.f) return out;
50 auto *projection = eve::cap::query<ISceneCameraProjection>();
51 if (!projection) return out;
52 const auto clip = projection->clipForViewport(*cam, viewW, viewH);
53 if (!clip) return out;
54
55 h->walkDepthFirst([&](SceneHost *, int, SceneNode &n) {
56 if (!n.hasBounds) return;
57 if (aabbIntersectsFrustum(clip->clip, clip->inverse, worldBoundsOf(n))) {
58 out.push_back(n.id);
59 }
60 });
61 return out;
62}
63
64Result<int> Scene::applyPcgTerrainCullingAt(const std::string &hostName, graphics::Camera3D *cam, float viewW,
65 float viewH, const std::string &tag) {
66 SceneHost *host = resolveHost(hostName);
67 if (!host || !cam || !std::isfinite(viewW) || !std::isfinite(viewH) || viewW <= 0.f || viewH <= 0.f || tag.empty())
69 DiagnosticCode::InvalidArgument, "Pcg terrain culling requires host, camera, positive viewport and tag",
70 "scene.pcgTerrainCulling"));
71 auto *projection = eve::cap::query<ISceneCameraProjection>();
72 if (!projection)
74 DiagnosticCode::Unsupported, "Pcg terrain culling needs the graphics camera projection capability",
75 "scene.pcgTerrainCulling"));
76 const auto clip = projection->clipForViewport(*cam, viewW, viewH);
77 if (!clip)
79 "Pcg terrain culling requires a usable camera viewport",
80 "scene.pcgTerrainCulling"));
81
82 std::vector<std::pair<std::string, bool>> changes;
83 host->walkDepthFirst([&](SceneHost *, int, SceneNode &node) {
84 if (!node.hasBounds || std::find(node.tags.begin(), node.tags.end(), tag) == node.tags.end()) return;
85 const bool visible = aabbIntersectsFrustum(clip->clip, clip->inverse, worldBoundsOf(node));
86 if (node.visible != visible) changes.emplace_back(node.id, visible);
87 });
88 for (const auto &[id, visible] : changes) {
89 auto node = host->findById(id);
90 if (!node) continue;
91 node.value()->visible = visible;
92 host->markSubtreeDirtyById(id);
93 }
94 return Result<int>::success(static_cast<int>(changes.size()));
95}
96
97} // namespace eve::scene
98
99// SceneComponent.cpp
100#include <vector>
101#include "scene/SceneComponent.h"
102
103#include "scene/Scene.h"
105
106#include <utility>
107
108namespace eve::scene {
109namespace detail {
111 SceneComponent *component = nullptr; // Owner invalidates before destruction; never exposed as a handle.
112 bool queued = false;
113};
114namespace {
115std::vector<std::weak_ptr<ComponentSchedule>> pending;
116std::vector<std::weak_ptr<ComponentSchedule>> draining;
117bool flushing = false;
118} // namespace
120 if (flushing) return;
121 flushing = true;
122 struct FlushGuard {
123 ~FlushGuard() {
124 draining.clear();
125 flushing = false;
126 }
127 } guard;
128 draining.swap(pending);
129 for (size_t i = 0; i < draining.size(); ++i) {
130 auto &entry = draining[i];
131 auto registration = entry.lock();
132 if (!registration || !registration->component) continue;
133 registration->queued = false;
134 try {
135 registration->component->updateIfDirty();
136 } catch (...) {
137 pending.insert(pending.end(), draining.begin() + i + 1, draining.end());
138 throw;
139 }
140 }
141}
142} // namespace detail
143
144SceneComponent::SceneComponent() : schedule_(std::make_shared<detail::ComponentSchedule>()) {
145 schedule_->component = this;
146}
147SceneComponent::~SceneComponent() { schedule_->component = nullptr; }
149 dirty_ = true;
150 if (schedule_->queued) return;
151 detail::pending.push_back(schedule_);
152 schedule_->queued = true;
153}
154
155
156SceneHost *SceneComponent::host() const { return dynamic_cast<SceneHost *>(ecs::try_get(hostHandle_)); }
157
159 if (host() != nextHost) {
160 hostHandle_ = ecs::handle_of(nextHost);
161 onMount(nextHost);
162 }
163 markDirty();
164}
165
166void SceneComponent::mountAs(const std::string &hostName) {
167 SceneHost *h = nullptr;
168 auto found = Scene::create()->findHost(hostName);
169 if (found.ok()) {
170 h = std::move(found).takeValue();
171 } else {
172 auto created = SceneHost::createHost(hostName);
173 if (!created.ok()) return;
174 h = std::move(created).takeValue();
175 }
176 attach(h);
177 rebuild(true);
178}
179
180void SceneComponent::rebuild(bool forceFull) {
181 if (!host() || building_) return;
182 building_ = true;
183 dirty_ = false;
184 try {
185 auto tree = build();
186 auto *target = host();
187 if (target) {
188 if (forceFull)
189 target->setTree(std::move(tree));
190 else
191 target->setTreeReconcile(std::move(tree));
193 }
194 } catch (...) {
195 building_ = false;
196 markDirty();
197 throw;
198 }
199 building_ = false;
200}
201
203 if (building_ || !dirty_ || !host()) return false;
204 rebuild(false);
205 return true;
206}
207
208} // namespace eve::scene
209
210// SceneLink.cpp
211namespace eve::scene {
212namespace {
213
214struct Entry {
215 std::string name;
216 LinkOps ops;
217};
218
224std::vector<Entry> &table() {
225 static std::vector<Entry> t;
226 return t;
227}
228
229} // namespace
230
232 if (!ops.kind || !ops.pushWorld) return -1;
233 const int existing = findLinkKind(ops.kind);
234 if (existing >= 0) return existing;
235 table().push_back({ops.kind, ops});
236 // Point the stored ops at our own copy of the name so a caller may pass a
237 // temporary.
238 Entry &e = table().back();
239 e.ops.kind = e.name.c_str();
240 return int(table().size()) - 1;
241}
242
243int findLinkKind(const char *kind) {
244 if (!kind) return -1;
245 const auto &t = table();
246 for (size_t i = 0; i < t.size(); ++i)
247 if (t[i].name == kind) return int(i);
248 return -1;
249}
250
251const LinkOps *linkOps(int kindId) {
252 const auto &t = table();
253 if (kindId < 0 || size_t(kindId) >= t.size()) return nullptr;
254 return &t[size_t(kindId)].ops;
255}
256
257const char *linkKindName(int kindId) {
258 const LinkOps *ops = linkOps(kindId);
259 return ops ? ops->kind : "";
260}
261
262} // namespace eve::scene
263
264// SceneNodeRef.cpp
265namespace eve::scene {
266namespace {
267
268template <class T>
269T *borrowSceneResult(eve::Result<T *> result) {
270 if (!result.ok()) return nullptr;
271 return std::move(result).takeValue();
272}
273
274SceneHost *resolveHost(const std::string &hostName) {
275 Scene *s = Scene::create();
276 if (!s) return nullptr;
277 if (hostName.empty()) return s->current();
278 return borrowSceneResult(s->findHost(hostName));
279}
280
281SceneNode *resolveNode(const std::string &hostName, const std::string &nodeId) {
282 if (nodeId.empty()) return nullptr;
283 SceneHost *h = resolveHost(hostName);
284 return h ? borrowSceneResult(h->findById(nodeId)) : nullptr;
285}
286
287glm::vec3 normalizedColumn(const glm::mat4 &m, int col) {
288 glm::vec3 v(m[col]);
289 const float len = glm::length(v);
290 if (len > 1e-8f) v /= len;
291 return v;
292}
293
294} // namespace
295
296bool SceneNodeRef::isValid() const { return resolveNode(hostName_, nodeId_) != nullptr; }
297
299 const SceneNode *node = resolveNode(hostName_, nodeId_);
300 return node ? node->persistentId : eve::SceneObjectId::nil();
301}
302
303Scene *SceneNodeRef::getScene() const { return Scene::create(); }
304
305bool SceneNodeRef::setPosition(float x, float y, float z) {
306 SceneHost *h = resolveHost(hostName_);
307 SceneNode *n = resolveNode(hostName_, nodeId_);
308 if (!h || !n) return false;
309 n->x = x;
310 n->y = y;
311 n->z = z;
312 h->markSubtreeDirtyById(nodeId_);
313 return true;
314}
315
317 const SceneNode *n = resolveNode(hostName_, nodeId_);
318 return n ? n->x : 0.f;
319}
320
322 const SceneNode *n = resolveNode(hostName_, nodeId_);
323 return n ? n->y : 0.f;
324}
325
327 const SceneNode *n = resolveNode(hostName_, nodeId_);
328 return n ? n->z : 0.f;
329}
330
331std::vector<float> SceneNodeRef::getPosition() const {
332 const SceneNode *n = resolveNode(hostName_, nodeId_);
333 if (!n) return {0.f, 0.f, 0.f};
334 return {n->x, n->y, n->z};
335}
336
337bool SceneNodeRef::setRotation(float yaw, float pitch, float roll) {
338 SceneHost *h = resolveHost(hostName_);
339 SceneNode *n = resolveNode(hostName_, nodeId_);
340 if (!h || !n) return false;
341 n->yaw = yaw;
342 n->pitch = pitch;
343 n->roll = roll;
344 h->markSubtreeDirtyById(nodeId_);
345 return true;
346}
347
349 const SceneNode *n = resolveNode(hostName_, nodeId_);
350 return n ? n->yaw : 0.f;
351}
352
354 const SceneNode *n = resolveNode(hostName_, nodeId_);
355 return n ? n->pitch : 0.f;
356}
357
359 const SceneNode *n = resolveNode(hostName_, nodeId_);
360 return n ? n->roll : 0.f;
361}
362
363std::vector<float> SceneNodeRef::getRotation() const {
364 const SceneNode *n = resolveNode(hostName_, nodeId_);
365 if (!n) return {0.f, 0.f, 0.f};
366 return {n->yaw, n->pitch, n->roll};
367}
368
369bool SceneNodeRef::setScale(float sx, float sy, float sz) {
370 SceneHost *h = resolveHost(hostName_);
371 SceneNode *n = resolveNode(hostName_, nodeId_);
372 if (!h || !n) return false;
373 n->sx = sx;
374 n->sy = sy;
375 n->sz = sz;
376 h->markSubtreeDirtyById(nodeId_);
377 return true;
378}
379
381 const SceneNode *n = resolveNode(hostName_, nodeId_);
382 return n ? n->sx : 0.f;
383}
384
386 const SceneNode *n = resolveNode(hostName_, nodeId_);
387 return n ? n->sy : 0.f;
388}
389
391 const SceneNode *n = resolveNode(hostName_, nodeId_);
392 return n ? n->sz : 0.f;
393}
394
395std::vector<float> SceneNodeRef::getScale() const {
396 const SceneNode *n = resolveNode(hostName_, nodeId_);
397 if (!n) return {0.f, 0.f, 0.f};
398 return {n->sx, n->sy, n->sz};
399}
400
402 SceneNode *n = resolveNode(hostName_, nodeId_);
403 if (!n) return false;
404 n->visible = v;
405 SceneHost *h = resolveHost(hostName_);
406 if (h) h->markSubtreeDirtyById(nodeId_);
407 return true;
408}
409
411 const SceneNode *n = resolveNode(hostName_, nodeId_);
412 return n ? n->visible : false;
413}
414
416 const SceneNode *n = resolveNode(hostName_, nodeId_);
417 return n ? n->world[3][0] : 0.f;
418}
419
421 const SceneNode *n = resolveNode(hostName_, nodeId_);
422 return n ? n->world[3][1] : 0.f;
423}
424
426 const SceneNode *n = resolveNode(hostName_, nodeId_);
427 return n ? n->world[3][2] : 0.f;
428}
429
430std::vector<float> SceneNodeRef::getWorldPosition() const {
431 const SceneNode *n = resolveNode(hostName_, nodeId_);
432 if (!n) return {0.f, 0.f, 0.f};
433 return {n->world[3][0], n->world[3][1], n->world[3][2]};
434}
435
436std::vector<float> SceneNodeRef::getWorldMatrix() const {
437 const SceneNode *n = resolveNode(hostName_, nodeId_);
438 if (!n) return std::vector<float>(16, 0.f);
439 std::vector<float> out;
440 out.reserve(16);
441 for (int c = 0; c < 4; ++c)
442 for (int r = 0; r < 4; ++r) out.push_back(n->world[c][r]);
443 return out;
444}
445
446std::vector<float> SceneNodeRef::getForward() const {
447 const SceneNode *n = resolveNode(hostName_, nodeId_);
448 if (!n) return {0.f, 0.f, 1.f};
449 glm::vec3 v = normalizedColumn(n->world, 2);
450 return {v.x, v.y, v.z};
451}
452
453std::vector<float> SceneNodeRef::getRight() const {
454 const SceneNode *n = resolveNode(hostName_, nodeId_);
455 if (!n) return {1.f, 0.f, 0.f};
456 glm::vec3 v = normalizedColumn(n->world, 0);
457 return {v.x, v.y, v.z};
458}
459
460std::vector<float> SceneNodeRef::getUp() const {
461 const SceneNode *n = resolveNode(hostName_, nodeId_);
462 if (!n) return {0.f, 1.f, 0.f};
463 glm::vec3 v = normalizedColumn(n->world, 1);
464 return {v.x, v.y, v.z};
465}
466
467std::string SceneNodeRef::getParentId() const {
468 SceneHost *h = resolveHost(hostName_);
469 if (!h) return {};
470 SceneNode *p = h->getParentById(nodeId_);
471 return p ? p->id : std::string{};
472}
473
475 SceneHost *h = resolveHost(hostName_);
476 return h ? h->getChildCountById(nodeId_) : 0;
477}
478
479std::string SceneNodeRef::getChildIdAt(int ordinal) const {
480 SceneHost *h = resolveHost(hostName_);
481 if (!h) return {};
482 SceneNode *c = h->getChildAtById(nodeId_, ordinal);
483 return c ? c->id : std::string{};
484}
485
486std::string SceneNodeRef::getPath() const {
487 SceneHost *h = resolveHost(hostName_);
488 return h ? h->getPathById(nodeId_) : std::string{};
489}
490
491} // namespace eve::scene
double z
double y
double m[16]
double x
LogicalId target
std::vector< QuestEvent > pending
const std::string & s
float yaw
Definition BushMesh.cpp:37
bool draining
glm::vec4 p[6]
std::string nodeId
std::string name
Definition ECS.cpp:154
glm::vec4 clip
glm::vec3 n
Definition Grass.cpp:63
double r
float v
std::int32_t c
int h
Poco::JSON::Object::Ptr result
const std::string * tag
int detail
float t
const RoadNode * node
bool found
LinkOps ops
int created
ScriptStructure out
std::string kind
bool visible
float size
Definition TreeMesh.cpp:158
UIHostHandle host
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
Id128 public API.
Definition Identity.h:111
static constexpr Id128 nil() noexcept
Returns the all-zero nil value.
Definition Identity.h:141
EVENGINE_API_BACKENDS public API.
React-style scene component: implement build(); setState / markDirty schedules one update before tran...
virtual ~SceneComponent()
Scene component.
SceneHost * host() const
Returns the currently attached host, or null before attach.
SceneComponent()
Create an unmounted component; attaching schedules its first update.
void mountAs(const std::string &hostName)
Mounts as.
void attach(SceneHost *host)
Attaches .
virtual void onMount(SceneHost *host)
Called once when the component is attached to a host.
bool updateIfDirty()
Compatibility-only synchronous update; normal edits are flushed automatically.
virtual NodeDesc build()=0
Builds .
void markDirty()
Schedule one rebuild; repeated calls before the next preparation phase coalesce. @thread Owner thread...
void rebuild(bool forceFull=false)
Compatibility-only synchronous refresh; normal edits use markDirty / setState. @cost Builds the compl...
ECS mount point for one scene graph (full scene or nested subtree root). Isomorphic to eve::ui::UIHos...
Definition SceneHost.h:89
static eve::Result< SceneHost * > createHost(const std::string &name="")
Creates an ECS-owned scene host with an explicit Result contract.
float getPositionX() const
Returns the position x.
float getWorldPositionZ() const
Returns the world position z.
std::vector< float > getForward() const
Normalized local axes in world space (forward = +Z).
bool isValid() const
True when host + node currently resolve.
float getWorldPositionX() const
Returns the world position x.
float getRotationYaw() const
Returns the rotation yaw.
float getWorldPositionY() const
Returns the world position y.
float getRotationPitch() const
Returns the rotation pitch.
bool setVisible(bool v)
Sets the visible.
float getScaleZ() const
Returns the scale z.
float getScaleX() const
Returns the scale x.
Scene * getScene() const
Returns the eve.Scene module instance for entity-binding forwarding.
std::string getPath() const
Returns the path.
std::string getChildIdAt(int ordinal) const
Returns the child id at.
std::vector< float > getPosition() const
Returns the position.
eve::SceneObjectId persistentId() const
Return the persisted UUID of the resolved node, or nil if absent.
std::vector< float > getWorldPosition() const
Returns the world position.
std::vector< float > getRotation() const
Returns the rotation.
bool setPosition(float x, float y, float z)
Sets the position.
float getPositionY() const
Returns the position y.
bool setScale(float sx, float sy, float sz)
Sets the scale.
float getRotationRoll() const
Returns the rotation roll.
std::vector< float > getScale() const
Returns the scale.
int getChildCount() const
Returns the child count.
bool isVisible() const
True when visible.
float getScaleY() const
Returns the scale y.
std::string getParentId() const
Returns the parent id.
std::vector< float > getUp() const
Returns the up.
bool setRotation(float yaw, float pitch, float roll)
Sets the rotation.
std::vector< float > getRight() const
Returns the right.
float getPositionZ() const
Returns the position z.
std::vector< float > getWorldMatrix() const
Column-major 4x4 world matrix, 16 floats.
Declarative scene module (eve.Scene).
Definition Scene.h:52
SceneHost * resolveHost(const std::string &hostName) const
Host-qualified resolution: empty hostName → currently selected host.
Definition Scene.cpp:869
std::string pickScreenAt(const std::string &hostName, graphics::Camera3D *cam, float screenX, float screenY, float viewW, float viewH) const
Screen-space picking through a Camera3D (camera.screenToRay).
Result< int > applyPcgTerrainCullingAt(const std::string &hostName, graphics::Camera3D *cam, float viewW, float viewH, const std::string &tag)
Apply PcgScenePlayer frustum visibility to bounded nodes carrying a tag.
std::vector< std::string > collectFrustumIdsAt(const std::string &hostName, graphics::Camera3D *cam, float viewW, float viewH) const
Ids of nodes whose world AABB intersects the camera frustum.
std::string pickRayAt(const std::string &hostName, float ox, float oy, float oz, float dx, float dy, float dz) const
Nearest node id hit by a world ray (nodes with bounds), or "".
static void updateHost(SceneHost *host)
Updates host.
std::unordered_map< std::string, SkillDefinition > & table()
Definition Skill.cpp:73
void flushPendingComponents()
Flush one batch of live dirty components before host traversal. @thread Owner thread; newly queued ed...
bool aabbIntersectsFrustum(const glm::mat4 &clip, const glm::mat4 &invClip, const AABB3f &b)
Conservative AABB ↔ frustum overlap (AABB corners + frustum corners).
Definition SceneBounds.h:81
const char * linkKindName(int kindId)
Link kind name.
AABB3f worldBoundsOf(const SceneNode &n)
World-space AABB of a node's local bounds (8 corners through world matrix).
Definition SceneBounds.h:26
int registerLinkKind(const LinkOps &ops)
Registers link kind.
int findLinkKind(const char *kind)
Finds link kind.
const LinkOps * linkOps(int kindId)
Link ops.
LinkOps public API.
Definition SceneLink.h:28
void(* pushWorld)(const SceneNode &node, void *target)
Void.
Definition SceneLink.h:34
const char * kind
Definition SceneLink.h:30
Retained scene node (arena). Conceptual GameObject; isomorphic to eve::ui::UINode.
Definition SceneHost.h:46