载入中...
搜索中...
未找到
CameraController.cpp
浏览该文件的文档.
5
7#include "common/Capability.h"
8#include "common/Json.h"
12#include "scene/SceneNodeRef.h"
13
14#include <simplesquirrel/simplesquirrel.hpp>
15
16#include <algorithm>
17#include <cmath>
18#include <limits>
19#include <sstream>
20
21namespace eve::camera {
22
23namespace {
24
25std::string jsonString(const std::string& value) {
26 std::ostringstream out;
27 out << '"';
28 for (const unsigned char c : value) {
29 switch (c) {
30 case '"': out << "\\\""; break;
31 case '\\': out << "\\\\"; break;
32 case '\b': out << "\\b"; break;
33 case '\f': out << "\\f"; break;
34 case '\n': out << "\\n"; break;
35 case '\r': out << "\\r"; break;
36 case '\t': out << "\\t"; break;
37 default:
38 if (c < 0x20)
39 out << "\\u00" << "0123456789abcdef"[c >> 4] << "0123456789abcdef"[c & 0xf];
40 else
41 out << static_cast<char>(c);
42 }
43 }
44 out << '"';
45 return out.str();
46}
47
48glm::vec3 jsonVec3(eve::json::Value value, glm::vec3 fallback) {
49 if (!value.isArray() || value.size() != 3) return fallback;
50 return {value.at(0).asFloat(fallback.x), value.at(1).asFloat(fallback.y),
51 value.at(2).asFloat(fallback.z)};
52}
53
54} // namespace
55
57
59
61 cap::removeListener<action::IActionCameraCueSink>(this);
62 if (photoModeAuthority_) cap::removeListener<IPhotoModeFieldSink>(this);
63}
64
66 for (std::size_t index = 0; index < cap::listenerCount<action::IActionCameraCueSink>(); ++index)
67 if (cap::listenerAt<action::IActionCameraCueSink>(index) == this) return true;
68 return false;
69}
70
72 const bool current = getActionCuesEnabled();
73 if (enabled && !current)
74 cap::addListener<action::IActionCameraCueSink>(this);
75 else if (!enabled && current)
76 cap::removeListener<action::IActionCameraCueSink>(this);
77}
78
79bool CameraController::supports(const LogicalId&) const noexcept { return getActionCuesEnabled(); }
80
83 addImpulse(static_cast<float>(binding.positionAmplitude), static_cast<float>(binding.rotationAmplitude),
84 static_cast<float>(binding.duration.seconds()), binding.seed);
85 addFovImpulse(static_cast<float>(binding.fovAmplitude), static_cast<float>(binding.duration.seconds()));
87}
88
90 if(enabled==photoModeAuthority_)return;
91 if(enabled)cap::addListener<IPhotoModeFieldSink>(this);else cap::removeListener<IPhotoModeFieldSink>(this);
92 photoModeAuthority_=enabled;
93}
99 "camera roll must be finite","camera.photoMode.roll"));
100 cameraRollDeg_=degrees;
101 if(cam_){
102 glm::vec3 eye(cam_->getEyeX(),cam_->getEyeY(),cam_->getEyeZ());
103 glm::vec3 target(cam_->getTargetX(),cam_->getTargetY(),cam_->getTargetZ());
104 glm::vec3 forward=target-eye;const float length=glm::length(forward);
105 if(length>1e-6f){forward/=length;glm::vec3 up(0,1,0);if(std::abs(glm::dot(forward,up))>0.999f)up={0,0,-1};
106 glm::vec3 right=glm::normalize(glm::cross(forward,up));up=glm::normalize(glm::cross(right,forward));
107 const float roll=glm::radians(cameraRollDeg_);up=up*std::cos(roll)+right*std::sin(roll);cam_->setUp(up.x,up.y,up.z);}
108 }
109 return Result<void>::success();
110}
112 auto bad=[&](const std::string&m){return Result<void>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument,m,a.field,{},"camera.photoMode"));};
113 if(!cam_)return bad("photo-mode camera authority requires a bound Camera3D");
114 if(a.domain==PhotoModeDomain::PostFx)return applyPcgPostFx(a);
115 if(a.domain!=PhotoModeDomain::Camera)return bad("unsupported photo-mode camera domain");
116 auto number=std::get_if<float>(&a.value);if(!number||!std::isfinite(*number))return bad("camera field requires a finite float");
117 if(a.field=="m_fieldOfView"){if(*number<=0||*number>=180)return bad("field of view must be in (0,180)");fovDeg_=*number;cam_->setFov(*number);}
118 else if(a.field=="m_pcgCullinDistance"){pcgCullingDistance_=*number;const float distance=std::max(0.f,cam_->getFarClip()+*number);for(int layer=0;layer<32;++layer)cam_->setLayerCullDistance(layer,distance);}
119 else if(a.field=="m_cameraAperture"){if(*number<=0)return bad("camera aperture must be positive");cam_->setPhysicalLens(*number,cam_->getFocalLength());}
120 else if(a.field=="m_cameraFocalLength"){if(*number<=0)return bad("camera focal length must be positive");cam_->setPhysicalLens(cam_->getAperture(),*number);}
121 else if(a.field=="m_cameraRoll")return setCameraRoll(*number);
122 else if(a.field=="m_farClipPlane"){if(*number<=cam_->getNearClip())return bad("far clip must exceed near clip");cam_->setClipPlanes(cam_->getNearClip(),*number);const float distance=std::max(0.f,*number+pcgCullingDistance_);for(int layer=0;layer<32;++layer)cam_->setLayerCullDistance(layer,distance);}
123 else return bad("unsupported photo-mode camera field");
124 return Result<void>::success();
125}
126
127Result<void> CameraController::applyPcgPostFx(const PhotoModeAssignment&a){
128 auto bad=[&](const std::string&m){return Result<void>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument,m,a.field,{},"camera.photoMode.postFx"));};
129 PcgPhotoModePostFxState next=pcgPostFxState_;
130 auto number=std::get_if<float>(&a.value);auto integer=std::get_if<int64_t>(&a.value);auto flag=std::get_if<bool>(&a.value);
131 auto finitePositive=[&](float* target){if(!number||!std::isfinite(*number)||*number<=0.f)return false;*target=*number;return true;};
132 auto finiteNonNegative=[&](float* target){if(!number||!std::isfinite(*number)||*number<0.f)return false;*target=*number;return true;};
133 if(a.field=="m_postFXExposure"){if(!number||!std::isfinite(*number))return bad("exposure requires a finite float");next.postFxExposure=*number;}
134 else if(a.field=="m_postFXExposureMode"){if(!integer||*integer<0)return bad("exposure mode requires a non-negative integer");next.postFxExposureMode=*integer;}
135 else if(a.field=="m_dofActive"){if(!flag)return bad("depth-of-field active requires a bool");next.depthOfFieldActive=*flag;}
136 else if(a.field=="m_autoDOFFocus"){if(!flag)return bad("automatic focus requires a bool");next.autoDepthOfFieldFocus=*flag;}
137 else if(a.field=="m_dofFocusDistance"){if(!finitePositive(&next.focusDistance))return bad("focus distance must be positive and finite");}
138 else if(a.field=="m_dofAperture"){if(!finitePositive(&next.aperture))return bad("aperture must be positive and finite");}
139 else if(a.field=="m_dofFocalLength"){if(!finitePositive(&next.focalLength))return bad("focal length must be positive and finite");}
140 else if(a.field=="m_dofKernelSize"){if(!integer||*integer<0||*integer>3)return bad("kernel size must be in [0,3]");next.kernelSize=*integer;}
141 else if(a.field=="m_savedDofFocusMode"){if(!integer||*integer<0)return bad("saved focus mode requires a non-negative integer");next.savedFocusMode=*integer;}
142 else if(a.field=="m_dofFocusModeHDRP"){if(!integer||*integer<0)return bad("HDRP focus mode requires a non-negative integer");next.focusModeHdrp=*integer;}
143 else if(a.field=="m_dofFocusModeURP"){if(!integer||*integer<0)return bad("URP focus mode requires a non-negative integer");next.focusModeUrp=*integer;}
144 else if(a.field=="m_dofQualityHDRP"){if(!integer||*integer<0)return bad("HDRP quality requires a non-negative integer");next.qualityHdrp=*integer;}
145 else if(a.field=="m_dofNearBlurStart"){if(!finiteNonNegative(&next.nearBlurStart))return bad("near blur start must be finite and non-negative");}
146 else if(a.field=="m_dofNearBlurEnd"){if(!finiteNonNegative(&next.nearBlurEnd))return bad("near blur end must be finite and non-negative");}
147 else if(a.field=="m_dofFarBlurStart"){if(!finiteNonNegative(&next.farBlurStart))return bad("far blur start must be finite and non-negative");}
148 else if(a.field=="m_dofFarBlurEnd"){if(!finiteNonNegative(&next.farBlurEnd))return bad("far blur end must be finite and non-negative");}
149 else if(a.field=="m_dofStartBlurURP"){if(!finiteNonNegative(&next.blurStartUrp))return bad("URP blur start must be finite and non-negative");}
150 else if(a.field=="m_dofEndBlurURP"){if(!finiteNonNegative(&next.blurEndUrp))return bad("URP blur end must be finite and non-negative");}
151 else if(a.field=="m_dofMaxRadiusBlur"){if(!finiteNonNegative(&next.maximumBlurRadius))return bad("maximum blur radius must be finite and non-negative");}
152 else if(a.field=="m_dofHighQualityURP"){if(!flag)return bad("URP high quality requires a bool");next.highQualityUrp=*flag;}
153 else return bad("unsupported photo-mode post-processing field");
154 pcgPostFxState_=next;projectPcgPostFx();return Result<void>::success();
155}
156
157void CameraController::projectPcgPostFx(){
158 if(!cam_)return;
159 const auto&s=pcgPostFxState_;
160 cam_->setExposure(s.postFxExposure);
161 cam_->setAutoExposure(s.postFxExposureMode!=0);
162 cam_->setPhysicalLens(s.aperture,s.focalLength);
163 if(!s.depthOfFieldActive){cam_->clearDepthOfField();return;}
164 const float urpRange=std::max(0.01f,s.blurEndUrp-s.blurStartUrp);
165 const float hdrpRange=std::max(0.01f,s.farBlurStart-s.nearBlurEnd);
166 const float focusRange=s.focusModeUrp==0?urpRange:hdrpRange;
167 const float qualityScale=(s.highQualityUrp?1.5f:1.f)*(1.f+0.25f*float(s.qualityHdrp));
168 const float blurPixels=std::max(0.01f,s.maximumBlurRadius*qualityScale*float(s.kernelSize+1));
169 cam_->setDepthOfField(s.focusDistance,blurPixels,focusRange);
170}
172
174
175void CameraController::setTarget(float x, float y, float z) {
176 targetNodeHost_.clear();
177 targetNodeId_.clear();
178 target_ = glm::vec3(x, y, z);
179}
180
182 targetNodeHost_ = node ? node->getHostName() : std::string();
183 targetNodeId_ = node ? node->getNodeId() : std::string();
184}
185
186float CameraController::getTargetX() const { return target_.x; }
187float CameraController::getTargetY() const { return target_.y; }
188float CameraController::getTargetZ() const { return target_.z; }
189
190void CameraController::setOffset(float x, float y, float z) { offset_ = glm::vec3(x, y, z); }
191
192void CameraController::setLookAhead(float x, float y, float z) { lookAhead_ = glm::vec3(x, y, z); }
193
194void CameraController::setSecondaryTarget(float x, float y, float z) {
195 secondaryTarget_ = glm::vec3(x, y, z);
196 hasSecondaryTarget_ = true;
197}
198
200 secondaryTarget_ = glm::vec3(0.f);
201 hasSecondaryTarget_ = false;
202}
203
204float CameraController::getSecondaryTargetX() const { return secondaryTarget_.x; }
205float CameraController::getSecondaryTargetY() const { return secondaryTarget_.y; }
206float CameraController::getSecondaryTargetZ() const { return secondaryTarget_.z; }
207
208bool CameraController::validMode(const std::string& mode) {
209 return mode == "follow" || mode == "orbit" || mode == "topdown" || mode == "ortho" || mode == "firstperson" ||
210 mode == "cinematic" || mode == "lockon";
211}
212
213void CameraController::setMode(const std::string& mode) {
214 if (!validMode(mode)) return;
215 if (mode_ == "ortho" && mode != "ortho" && cam_) cam_->setPerspective();
216 mode_ = mode;
217}
218
220 if (!std::isfinite(height) || height <= 0.f) return;
221 orthoHeight_ = height;
222}
223
224std::string CameraController::getMode() const { return mode_; }
225
226void CameraController::setRadius(float r) { radius_ = glm::clamp(r, minimumRadius_, maximumRadius_); }
228 if (!std::isfinite(minimum) || !std::isfinite(maximum) || minimum <= 0.f || maximum < minimum)
229 return Result<void>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument, "camera radius limits are invalid", "camera.radiusLimits"));
230 minimumRadius_ = minimum; maximumRadius_ = maximum; radius_ = glm::clamp(radius_, minimum, maximum);
231 return Result<void>::success();
232}
233void CameraController::setAzimuth(float deg) { azimuthDeg_ = deg; }
234void CameraController::setElevation(float deg) { elevationDeg_ = glm::clamp(deg, -89.f, 89.f); }
235void CameraController::setOrbitSpeed(float degPerSec) { orbitSpeedDeg_ = degPerSec; }
236
237void CameraController::setYaw(float deg) { yawDeg_ = deg; }
238void CameraController::setPitch(float deg) { pitchDeg_ = glm::clamp(deg, -89.f, 89.f); }
239void CameraController::addInput(float yawDeltaDeg, float pitchDeltaDeg, float zoomDelta) {
240 yawDeg_ += yawDeltaDeg;
241 azimuthDeg_ += yawDeltaDeg;
242 setPitch(pitchDeg_ + pitchDeltaDeg);
243 setElevation(elevationDeg_ + pitchDeltaDeg);
244 setRadius(radius_ + zoomDelta);
245}
246
247void CameraController::setComposition(float screenX, float screenY) {
248 composition_ = glm::clamp(glm::vec2(screenX, screenY), glm::vec2(-0.9f), glm::vec2(0.9f));
249}
250
251void CameraController::setDeadZone(float radius) { deadZone_ = std::max(0.f, radius); }
252void CameraController::setFov(float degrees) { fovDeg_ = glm::clamp(degrees, 1.f, 179.f); }
253float CameraController::getFov() const { return fovDeg_; }
254
255void CameraController::setSmooth(float damping) {
256 smooth_ = std::max(0.f, damping);
257 positionSmooth_ = smooth_;
258 targetSmooth_ = smooth_;
259}
260void CameraController::setPositionSmooth(float damping) { positionSmooth_ = std::max(0.f, damping); }
261void CameraController::setTargetSmooth(float damping) { targetSmooth_ = std::max(0.f, damping); }
262
263void CameraController::setMaxSpeed(float unitsPerSec) { maxSpeed_ = std::max(0.f, unitsPerSec); }
264
265void CameraController::setCollisionEnabled(bool enabled) { collisionEnabled_ = enabled; }
266void CameraController::setCollisionRadius(float radius) { collisionRadius_ = std::max(0.f, radius); }
267void CameraController::setCollisionRecovery(float damping) { collisionRecovery_ = std::max(0.f, damping); }
268void CameraController::setCollisionMask(uint64_t maskBits) { collisionMask_ = maskBits; }
269void CameraController::setCollisionIgnoredBody(int bodyId) { collisionIgnoredBody_ = bodyId; }
270void CameraController::clearCollisionBoxes() { collisionBoxes_.clear(); }
271void CameraController::addCollisionBox(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) {
272 CollisionBox b;
273 b.min = glm::min(glm::vec3(minX, minY, minZ), glm::vec3(maxX, maxY, maxZ));
274 b.max = glm::max(glm::vec3(minX, minY, minZ), glm::vec3(maxX, maxY, maxZ));
275 collisionBoxes_.push_back(b);
276}
277bool CameraController::isObstructed() const { return obstructed_; }
278int CameraController::getCollisionBodyId() const { return collisionBodyId_; }
279
280bool CameraController::addRig(const std::string& name, const std::string& mode, int priority) {
281 if (name.empty() || !validMode(mode)) return false;
282 for (const auto& rig : rigs_)
283 if (rig.name == name) return false;
284 Rig rig;
285 rig.name = name;
286 rig.mode = mode;
287 rig.priority = priority;
288 rigs_.push_back(rig);
290 directorEnabled_ = true;
291 return true;
292}
293
294bool CameraController::removeRig(const std::string& name) {
295 auto it = std::find_if(rigs_.begin(), rigs_.end(), [&](const Rig& r) { return r.name == name; });
296 if (it == rigs_.end()) return false;
297 rigs_.erase(it);
298 if (activeRig_ == name) activeRig_.clear();
299 return true;
300}
301
302bool CameraController::setRigPriority(const std::string& name, int priority) {
303 for (auto& rig : rigs_)
304 if (rig.name == name) {
305 rig.priority = priority;
306 return true;
307 }
308 return false;
309}
310
311bool CameraController::setRigEnabled(const std::string& name, bool enabled) {
312 for (auto& rig : rigs_)
313 if (rig.name == name) {
314 rig.enabled = enabled;
315 return true;
316 }
317 return false;
318}
319
320bool CameraController::saveRigState(const std::string& name) {
321 for (auto& rig : rigs_) {
322 if (rig.name != name) continue;
323 rig.target = target_;
324 rig.offset = offset_;
325 rig.lookAhead = lookAhead_;
326 rig.composition = composition_;
327 rig.radius = radius_;
328 rig.azimuth = azimuthDeg_;
329 rig.elevation = elevationDeg_;
330 rig.yaw = yawDeg_;
331 rig.pitch = pitchDeg_;
332 rig.fov = fovDeg_;
333 rig.smooth = smooth_;
334 rig.maxSpeed = maxSpeed_;
335 return true;
336 }
337 return false;
338}
339
340bool CameraController::activateRig(const std::string& name, float blendTime) {
341 auto it = std::find_if(rigs_.begin(), rigs_.end(), [&](const Rig& r) { return r.name == name && r.enabled; });
342 if (it == rigs_.end()) return false;
343 const View from = initialized_ ? cur_ : desired();
344 activeRig_ = name;
345 mode_ = it->mode;
346 target_ = it->target;
347 offset_ = it->offset;
348 lookAhead_ = it->lookAhead;
349 composition_ = it->composition;
350 radius_ = it->radius;
351 azimuthDeg_ = it->azimuth;
352 elevationDeg_ = it->elevation;
353 yawDeg_ = it->yaw;
354 pitchDeg_ = it->pitch;
355 fovDeg_ = it->fov;
356 setSmooth(it->smooth);
357 maxSpeed_ = it->maxSpeed;
358 const bool wasBlending = blending_;
359 blending_ = false;
360 const View to = desired();
361 blending_ = wasBlending;
362 if (blendTime > 0.f) {
363 blendFrom_ = from;
364 blendTo_ = to;
365 blendDur_ = blendTime;
366 blendT_ = 0.f;
367 blending_ = true;
368 } else {
369 blending_ = false;
370 }
371 return true;
372}
373
374std::string CameraController::getActiveRig() const { return activeRig_; }
375
376void CameraController::addImpulse(float positionAmplitude, float rotationAmplitude, float duration, unsigned int seed) {
377 if (duration <= 0.f || (positionAmplitude <= 0.f && rotationAmplitude <= 0.f)) return;
378 impulses_.push_back({std::max(0.f, positionAmplitude), std::max(0.f, rotationAmplitude), duration, 0.f, seed, 0.f});
379}
381 if (duration <= 0.f || degrees == 0.f) return;
382 impulses_.push_back({0.f, 0.f, duration, 0.f, 0u, degrees});
383}
384void CameraController::clearImpulses() { impulses_.clear(); }
385
386void CameraController::addView(const std::string& name, float ex, float ey, float ez, float tx, float ty, float tz) {
387 View v;
388 v.name = name;
389 v.eye = glm::vec3(ex, ey, ez);
390 v.target = glm::vec3(tx, ty, tz);
391 v.fov = fovDeg_;
392 views_.push_back(v);
393}
394
395Result<void> CameraController::setView(const std::string& name, float ex, float ey, float ez, float tx, float ty,
396 float tz, float fov) {
397 if (name.empty())
399 Diagnostic::error(DiagnosticCode::InvalidArgument, "view name is required", "camera.setView"));
400 if (!std::isfinite(ex) || !std::isfinite(ey) || !std::isfinite(ez) || !std::isfinite(tx) || !std::isfinite(ty) ||
401 !std::isfinite(tz) || !std::isfinite(fov))
403 Diagnostic::error(DiagnosticCode::InvalidArgument, "view pose must be finite", "camera.setView"));
404 if (fov <= 0.f || fov >= 180.f)
406 Diagnostic::error(DiagnosticCode::InvalidArgument, "view fov must be in (0,180)", "camera.setView"));
407 for (auto& view : views_) {
408 if (view.name == name) {
409 view.eye = glm::vec3(ex, ey, ez);
410 view.target = glm::vec3(tx, ty, tz);
411 view.fov = fov;
412 return Result<void>::success();
413 }
414 }
415 View v;
416 v.name = name;
417 v.eye = glm::vec3(ex, ey, ez);
418 v.target = glm::vec3(tx, ty, tz);
419 v.fov = fov;
420 views_.push_back(v);
421 return Result<void>::success();
422}
423
426 snap.mode = mode_;
427 snap.activeRig = activeRig_;
428 snap.targetX = target_.x;
429 snap.targetY = target_.y;
430 snap.targetZ = target_.z;
431 snap.offsetX = offset_.x;
432 snap.offsetY = offset_.y;
433 snap.offsetZ = offset_.z;
434 snap.lookAheadX = lookAhead_.x;
435 snap.lookAheadY = lookAhead_.y;
436 snap.lookAheadZ = lookAhead_.z;
437 snap.radius = radius_;
438 snap.azimuth = azimuthDeg_;
439 snap.elevation = elevationDeg_;
440 snap.yaw = yawDeg_;
441 snap.pitch = pitchDeg_;
442 snap.fov = fovDeg_;
443 snap.smooth = smooth_;
444 snap.positionSmooth = positionSmooth_;
445 snap.targetSmooth = targetSmooth_;
446 snap.maxSpeed = maxSpeed_;
447 snap.eyeX = cur_.eye.x;
448 snap.eyeY = cur_.eye.y;
449 snap.eyeZ = cur_.eye.z;
450 snap.lookX = cur_.target.x;
451 snap.lookY = cur_.target.y;
452 snap.lookZ = cur_.target.z;
453 snap.directorEnabled = directorEnabled_;
454 snap.timelinePlaying = timelinePlaying_;
455 return snap;
456}
457
459 if (!validMode(snapshot.mode))
461 Diagnostic::error(DiagnosticCode::InvalidArgument, "snapshot mode is unsupported", "camera.restoreFraming"));
462 if (!std::isfinite(blendTime) || blendTime < 0.f)
464 Diagnostic::error(DiagnosticCode::InvalidArgument, "blendTime must be finite and >= 0",
465 "camera.restoreFraming"));
466 if (!std::isfinite(snapshot.targetX) || !std::isfinite(snapshot.targetY) || !std::isfinite(snapshot.targetZ) ||
467 !std::isfinite(snapshot.offsetX) || !std::isfinite(snapshot.offsetY) || !std::isfinite(snapshot.offsetZ) ||
468 !std::isfinite(snapshot.lookAheadX) || !std::isfinite(snapshot.lookAheadY) ||
469 !std::isfinite(snapshot.lookAheadZ) || !std::isfinite(snapshot.radius) || !std::isfinite(snapshot.azimuth) ||
470 !std::isfinite(snapshot.elevation) || !std::isfinite(snapshot.yaw) || !std::isfinite(snapshot.pitch) ||
471 !std::isfinite(snapshot.fov) || !std::isfinite(snapshot.smooth) || !std::isfinite(snapshot.positionSmooth) ||
472 !std::isfinite(snapshot.targetSmooth) || !std::isfinite(snapshot.maxSpeed) || !std::isfinite(snapshot.eyeX) ||
473 !std::isfinite(snapshot.eyeY) || !std::isfinite(snapshot.eyeZ) || !std::isfinite(snapshot.lookX) ||
474 !std::isfinite(snapshot.lookY) || !std::isfinite(snapshot.lookZ))
476 Diagnostic::error(DiagnosticCode::InvalidArgument, "snapshot framing must be finite",
477 "camera.restoreFraming"));
478
479 const View from = initialized_ ? cur_ : desired();
480 stopSequence();
481 mode_ = snapshot.mode;
482 activeRig_ = snapshot.activeRig;
483 target_ = glm::vec3(snapshot.targetX, snapshot.targetY, snapshot.targetZ);
484 offset_ = glm::vec3(snapshot.offsetX, snapshot.offsetY, snapshot.offsetZ);
485 lookAhead_ = glm::vec3(snapshot.lookAheadX, snapshot.lookAheadY, snapshot.lookAheadZ);
486 radius_ = snapshot.radius;
487 azimuthDeg_ = snapshot.azimuth;
488 elevationDeg_ = snapshot.elevation;
489 yawDeg_ = snapshot.yaw;
490 pitchDeg_ = snapshot.pitch;
491 setFov(snapshot.fov);
492 setSmooth(snapshot.smooth);
493 positionSmooth_ = std::max(0.f, snapshot.positionSmooth);
494 targetSmooth_ = std::max(0.f, snapshot.targetSmooth);
495 maxSpeed_ = std::max(0.f, snapshot.maxSpeed);
496 directorEnabled_ = snapshot.directorEnabled;
497 timelinePlaying_ = snapshot.timelinePlaying;
498
499 View to = desired();
500 if (blendTime > 0.f) {
501 blendFrom_ = initialized_ ? from
502 : View{"", glm::vec3(snapshot.eyeX, snapshot.eyeY, snapshot.eyeZ),
503 glm::vec3(snapshot.lookX, snapshot.lookY, snapshot.lookZ), snapshot.fov};
504 blendTo_ = to;
505 blendDur_ = blendTime;
506 blendT_ = 0.f;
507 blending_ = true;
508 } else {
509 blending_ = false;
510 cur_ = to;
511 initialized_ = true;
512 applyView(cur_);
513 }
514 return Result<void>::success();
515}
516
517void CameraController::setDirectorEnabled(bool enabled) { directorEnabled_ = enabled; }
518
519bool CameraController::switchTo(const std::string& name, float blendTime) {
520 int idx = -1;
521 for (int i = 0; i < static_cast<int>(views_.size()); ++i) {
522 if (views_[i].name == name) {
523 idx = i;
524 break;
525 }
526 }
527 if (idx < 0) return false;
528
529 if (viewIndex_ >= 0 && viewIndex_ < static_cast<int>(views_.size())) {
530 blendFrom_ = views_[viewIndex_];
531 } else {
532 blendFrom_ = cur_;
533 }
534 blendTo_ = views_[idx];
535 viewIndex_ = idx;
536
537 if (blendTime > 0.f) {
538 blending_ = true;
539 blendDur_ = blendTime;
540 blendT_ = 0.f;
541 } else {
542 blending_ = false;
543 blendDur_ = 1.f;
544 blendT_ = 0.f;
545 }
546 return true;
547}
548
549void CameraController::playSequence(float stepTime) {
550 playing_ = true;
551 stepTime_ = stepTime > 0.f ? stepTime : 1.f;
552 timer_ = 0.f;
553 if (!blending_ && views_.empty()) return;
554 if (viewIndex_ < 0 || viewIndex_ >= static_cast<int>(views_.size())) {
555 switchTo(views_.front().name, 0.f);
556 }
557}
558
559void CameraController::stopSequence() { playing_ = false; }
560
561bool CameraController::isPlaying() const { return playing_; }
562
564 timelineCuts_.clear();
565 timelineEvents_.clear();
566 timelineFloats_.clear();
567 pendingTimelineEvents_.clear();
568 timelineDuration_ = 0.f;
569 stopTimeline();
570}
571
572bool CameraController::addTimelineFloat(float time, const std::string& property, float value) {
573 if (time < 0.f || (property != "fov" && property != "radius" && property != "smooth" &&
574 property != "compositionX" && property != "compositionY"))
575 return false;
576 timelineFloats_.push_back({time, property, value});
577 std::stable_sort(timelineFloats_.begin(), timelineFloats_.end(), [](const auto& a, const auto& b) {
578 return a.time < b.time;
579 });
580 timelineDuration_ = std::max(timelineDuration_, time);
581 return true;
582}
583
584bool CameraController::addTimelineCut(float time, const std::string& rigName, float blendTime) {
585 if (time < 0.f || blendTime < 0.f) return false;
586 const bool known = std::any_of(rigs_.begin(), rigs_.end(), [&](const Rig& r) { return r.name == rigName; });
587 if (!known) return false;
588 timelineCuts_.push_back({time, rigName, blendTime, false});
589 std::stable_sort(timelineCuts_.begin(), timelineCuts_.end(),
590 [](const TimelineCut& a, const TimelineCut& b) { return a.time < b.time; });
591 timelineDuration_ = std::max(timelineDuration_, time);
592 return true;
593}
594
595bool CameraController::addTimelineEvent(float time, const std::string& name, const std::string& data) {
596 if (time < 0.f || name.empty()) return false;
597 timelineEvents_.push_back({time, name, data, false});
598 std::stable_sort(timelineEvents_.begin(), timelineEvents_.end(),
599 [](const TimelineEvent& a, const TimelineEvent& b) { return a.time < b.time; });
600 timelineDuration_ = std::max(timelineDuration_, time);
601 return true;
602}
603
605
607 timelineLoop_ = loop;
608 timelinePlaying_ = !timelineCuts_.empty() || !timelineEvents_.empty();
609}
610void CameraController::pauseTimeline() { timelinePlaying_ = false; }
612 timelinePlaying_ = false;
613 timelineTime_ = 0.f;
614 for (auto& cut : timelineCuts_) cut.fired = false;
615 for (auto& event : timelineEvents_) event.fired = false;
616}
617void CameraController::seekTimeline(float time, bool fireEvents) {
618 timelineTime_ = glm::clamp(time, 0.f, std::max(0.f, timelineDuration_));
619 for (auto& cut : timelineCuts_) cut.fired = cut.time <= timelineTime_;
620 const TimelineCut* latest = nullptr;
621 for (const auto& cut : timelineCuts_)
622 if (cut.time <= timelineTime_) latest = &cut;
623 if (latest) activateRig(latest->rig, 0.f);
624 for (auto& marker : timelineEvents_) {
625 marker.fired = marker.time <= timelineTime_;
626 if (fireEvents && marker.fired) emitTimelineEvent(marker);
627 }
628 evaluateTimelineFloats();
629}
630bool CameraController::isTimelinePlaying() const { return timelinePlaying_; }
631float CameraController::getTimelineTime() const { return timelineTime_; }
633 if (pendingTimelineEvents_.empty()) return {};
634 auto [out, data] = std::move(pendingTimelineEvents_.front());
635 pendingTimelineEvents_.pop_front();
636 consumedTimelineEventData_ = std::move(data);
637 return out;
638}
639std::string CameraController::getTimelineEventData() const { return consumedTimelineEventData_; }
640int CameraController::getPendingTimelineEventCount() const { return static_cast<int>(pendingTimelineEvents_.size()); }
641float CameraController::getTimelineDuration() const { return timelineDuration_; }
642int CameraController::getRigCount() const { return static_cast<int>(rigs_.size()); }
643
645 std::ostringstream out;
646 out << "{\"version\":1,\"rigs\":[";
647 bool first = true;
648 for (const auto& rig : rigs_) {
649 if (!first) out << ',';
650 first = false;
651 out << "{\"name\":" << jsonString(rig.name) << ",\"mode\":" << jsonString(rig.mode)
652 << ",\"priority\":" << rig.priority << ",\"enabled\":" << (rig.enabled ? "true" : "false")
653 << ",\"target\":[" << rig.target.x << ',' << rig.target.y << ',' << rig.target.z
654 << "],\"offset\":[" << rig.offset.x << ',' << rig.offset.y << ',' << rig.offset.z
655 << "],\"lookAhead\":[" << rig.lookAhead.x << ',' << rig.lookAhead.y << ',' << rig.lookAhead.z
656 << "],\"composition\":[" << rig.composition.x << ',' << rig.composition.y << "]"
657 << ",\"radius\":" << rig.radius << ",\"azimuth\":" << rig.azimuth
658 << ",\"elevation\":" << rig.elevation << ",\"yaw\":" << rig.yaw << ",\"pitch\":" << rig.pitch
659 << ",\"fov\":" << rig.fov << ",\"smooth\":" << rig.smooth << ",\"maxSpeed\":" << rig.maxSpeed << '}';
660 }
661 out << "],\"cuts\":[";
662 first = true;
663 for (const auto& cut : timelineCuts_) {
664 if (!first) out << ',';
665 first = false;
666 out << "{\"time\":" << cut.time << ",\"rig\":" << jsonString(cut.rig) << ",\"blend\":" << cut.blend << '}';
667 }
668 out << "],\"events\":[";
669 first = true;
670 for (const auto& marker : timelineEvents_) {
671 if (!first) out << ',';
672 first = false;
673 out << "{\"time\":" << marker.time << ",\"name\":" << jsonString(marker.name)
674 << ",\"data\":" << jsonString(marker.data) << '}';
675 }
676 out << "],\"floats\":[";
677 first = true;
678 for (const auto& key : timelineFloats_) {
679 if (!first) out << ',';
680 first = false;
681 out << "{\"time\":" << key.time << ",\"property\":" << jsonString(key.property)
682 << ",\"value\":" << key.value << '}';
683 }
684 out << "]}";
685 return out.str();
686}
687
688bool CameraController::deserializeAsset(const std::string& text) {
689 const auto document = eve::json::Document::parse(text);
690 const auto root = document.root();
691 if (!root.isObject() || root.getInt("version", 0) != 1) return false;
692 std::vector<Rig> newRigs;
693 const auto rigs = root.get("rigs");
694 if (rigs && !rigs.isArray()) return false;
695 for (size_t i = 0; i < rigs.size(); ++i) {
696 const auto item = rigs.at(i);
697 if (!item.isObject()) return false;
698 Rig rig;
699 rig.name = item.getString("name");
700 rig.mode = item.getString("mode");
701 if (rig.name.empty() || !validMode(rig.mode)) return false;
702 rig.priority = item.getInt("priority");
703 rig.enabled = item.getBool("enabled", true);
704 rig.target = jsonVec3(item.get("target"), rig.target);
705 rig.offset = jsonVec3(item.get("offset"), rig.offset);
706 rig.lookAhead = jsonVec3(item.get("lookAhead"), rig.lookAhead);
707 const auto composition = item.get("composition");
708 if (composition.isArray() && composition.size() == 2)
709 rig.composition = {composition.at(0).asFloat(), composition.at(1).asFloat()};
710 rig.radius = item.getFloat("radius", rig.radius);
711 rig.azimuth = item.getFloat("azimuth", rig.azimuth);
712 rig.elevation = item.getFloat("elevation", rig.elevation);
713 rig.yaw = item.getFloat("yaw", rig.yaw);
714 rig.pitch = item.getFloat("pitch", rig.pitch);
715 rig.fov = item.getFloat("fov", rig.fov);
716 rig.smooth = item.getFloat("smooth", rig.smooth);
717 rig.maxSpeed = item.getFloat("maxSpeed", rig.maxSpeed);
718 newRigs.push_back(std::move(rig));
719 }
721 rigs_ = std::move(newRigs);
722 activeRig_.clear();
723 directorEnabled_ = !rigs_.empty();
724 const auto cuts = root.get("cuts");
725 if (cuts && !cuts.isArray()) return false;
726 for (size_t i = 0; i < cuts.size(); ++i) {
727 const auto item = cuts.at(i);
728 if (!item.isObject() || !addTimelineCut(item.getFloat("time", -1.f), item.getString("rig"),
729 item.getFloat("blend", 0.f)))
730 return false;
731 }
732 const auto events = root.get("events");
733 if (events && !events.isArray()) return false;
734 for (size_t i = 0; i < events.size(); ++i) {
735 const auto item = events.at(i);
736 if (!item.isObject() || !addTimelineEvent(item.getFloat("time", -1.f), item.getString("name"),
737 item.getString("data")))
738 return false;
739 }
740 const auto floats = root.get("floats");
741 if (floats && !floats.isArray()) return false;
742 for (size_t i = 0; i < floats.size(); ++i) {
743 const auto item = floats.at(i);
744 if (!item.isObject() || !addTimelineFloat(item.getFloat("time", -1.f), item.getString("property"),
745 item.getFloat("value")))
746 return false;
747 }
748 return true;
749}
750
751void CameraController::emitTimelineEvent(const TimelineEvent& marker) {
752 pendingTimelineEvents_.emplace_back(marker.name, marker.data);
753 if (eventSink_) eventSink_->pushData(marker.name, marker.data);
754}
755
756void CameraController::evaluateTimelineFloats() {
757 for (const std::string property : {"fov", "radius", "smooth", "compositionX", "compositionY"}) {
758 const TimelineFloat* before = nullptr;
759 const TimelineFloat* after = nullptr;
760 for (const auto& key : timelineFloats_) {
761 if (key.property != property) continue;
762 if (key.time <= timelineTime_) before = &key;
763 if (key.time >= timelineTime_) {
764 after = &key;
765 break;
766 }
767 }
768 if (!before && !after) continue;
769 if (!before) before = after;
770 if (!after) after = before;
771 const float span = after->time - before->time;
772 const float t = span > 1e-6f ? (timelineTime_ - before->time) / span : 0.f;
773 const float value = glm::mix(before->value, after->value, glm::clamp(t, 0.f, 1.f));
774 if (property == "fov") setFov(value);
775 else if (property == "radius") setRadius(value);
776 else if (property == "smooth") setSmooth(value);
777 else if (property == "compositionX") setComposition(value, composition_.y);
778 else setComposition(composition_.x, value);
779 }
780}
781
782void CameraController::updateTrackedTarget() {
783 if (targetNodeHost_.empty() || targetNodeId_.empty()) return;
784 const scene::SceneNodeRef node(targetNodeHost_, targetNodeId_);
785 if (!node.isValid()) return;
786 const glm::vec3 observed(node.getWorldPositionX(), node.getWorldPositionY(), node.getWorldPositionZ());
787 if (!deadZoneInitialized_ || deadZone_ <= 0.f) {
788 deadZoneTarget_ = observed;
789 deadZoneInitialized_ = true;
790 } else {
791 const glm::vec3 delta = observed - deadZoneTarget_;
792 const float length = glm::length(delta);
793 if (length > deadZone_ && length > 1e-6f) deadZoneTarget_ += delta * ((length - deadZone_) / length);
794 }
795 target_ = deadZoneTarget_;
796}
797
798void CameraController::updateDirector() {
799 if (!directorEnabled_ || timelinePlaying_) return;
800 const Rig* best = nullptr;
801 const Rig* active = nullptr;
802 for (const auto& rig : rigs_) {
803 if (rig.name == activeRig_ && rig.enabled) active = &rig;
804 if (rig.enabled && (!best || rig.priority > best->priority)) best = &rig;
805 }
806 if (active && best && active->priority >= best->priority) best = active;
807 if (best && best->name != activeRig_) activateRig(best->name, initialized_ ? 0.25f : 0.f);
808}
809
810void CameraController::updateTimeline(float dt) {
811 if (!timelinePlaying_) return;
812 float remaining = std::max(0.f, dt);
813 if (timelineDuration_ <= 0.f) remaining = 0.f;
814 timelineTime_ += remaining;
815 for (auto& cut : timelineCuts_) {
816 if (!cut.fired && cut.time <= timelineTime_) {
817 cut.fired = true;
818 activateRig(cut.rig, cut.blend);
819 }
820 }
821 for (auto& marker : timelineEvents_) {
822 if (!marker.fired && marker.time <= timelineTime_) {
823 marker.fired = true;
824 emitTimelineEvent(marker);
825 }
826 }
827 evaluateTimelineFloats();
828 if (timelineTime_ < timelineDuration_) return;
829 if (!timelineLoop_) {
830 timelinePlaying_ = false;
831 return;
832 }
833 timelineTime_ = timelineDuration_ > 0.f ? std::fmod(timelineTime_, timelineDuration_) : 0.f;
834 for (auto& cut : timelineCuts_) cut.fired = false;
835 for (auto& marker : timelineEvents_) marker.fired = false;
836 for (auto& cut : timelineCuts_)
837 if (cut.time <= timelineTime_) {
838 cut.fired = true;
839 activateRig(cut.rig, cut.blend);
840 }
841 for (auto& marker : timelineEvents_)
842 if (marker.time <= timelineTime_) {
843 marker.fired = true;
844 emitTimelineEvent(marker);
845 }
846 evaluateTimelineFloats();
847}
848
849void CameraController::applyCollision(View& v, float dt) {
850 obstructed_ = false;
851 collisionBodyId_ = -1;
852 const glm::vec3 ray = v.eye - v.target;
853 const float desiredDistance = glm::length(ray);
854 if (!collisionEnabled_ || desiredDistance < 1e-5f) {
855 collisionDistance_ = -1.f;
856 return;
857 }
858 const glm::vec3 dir = ray / desiredDistance;
859 float nearest = desiredDistance;
860 for (const auto& box : collisionBoxes_) {
861 const glm::vec3 bmin = box.min - glm::vec3(collisionRadius_);
862 const glm::vec3 bmax = box.max + glm::vec3(collisionRadius_);
863 float tmin = 0.f;
864 float tmax = desiredDistance;
865 bool hit = true;
866 for (int axis = 0; axis < 3; ++axis) {
867 if (std::abs(dir[axis]) < 1e-6f) {
868 if (v.target[axis] < bmin[axis] || v.target[axis] > bmax[axis]) {
869 hit = false;
870 break;
871 }
872 } else {
873 float a = (bmin[axis] - v.target[axis]) / dir[axis];
874 float b = (bmax[axis] - v.target[axis]) / dir[axis];
875 if (a > b) std::swap(a, b);
876 tmin = std::max(tmin, a);
877 tmax = std::min(tmax, b);
878 if (tmin > tmax) {
879 hit = false;
880 break;
881 }
882 }
883 }
884 if (hit && tmin >= 0.f && tmin < nearest) nearest = tmin;
885 }
886 if (auto* query = eve::cap::query<eve::ICameraObstructionQuery>()) {
888 if (query->sphereCast(v.target.x, v.target.y, v.target.z, v.eye.x, v.eye.y, v.eye.z,
889 collisionRadius_, collisionMask_, collisionIgnoredBody_, &hit) &&
890 hit.hit) {
891 const float distance = desiredDistance * glm::clamp(hit.fraction, 0.f, 1.f);
892 if (distance < nearest) {
893 nearest = distance;
894 collisionBodyId_ = hit.bodyId;
895 }
896 }
897 }
898 obstructed_ = nearest < desiredDistance;
899 const float safeDistance = obstructed_ ? std::max(0.05f, nearest - 0.02f) : desiredDistance;
900 if (collisionDistance_ < 0.f || safeDistance < collisionDistance_)
901 collisionDistance_ = safeDistance;
902 else {
903 const float k = 1.f - std::exp(-collisionRecovery_ * std::max(0.f, dt));
904 collisionDistance_ += (safeDistance - collisionDistance_) * k;
905 }
906 collisionDistance_ = std::min(collisionDistance_, desiredDistance);
907 v.eye = v.target + dir * collisionDistance_;
908}
909
910void CameraController::applyModifiers(View& v, float dt) {
911 for (auto& impulse : impulses_) {
912 impulse.age += std::max(0.f, dt);
913 const float life = glm::clamp(1.f - impulse.age / impulse.duration, 0.f, 1.f);
914 const float phase = impulse.age * 37.f + static_cast<float>(impulse.seed % 997u);
915 const glm::vec3 noise(std::sin(phase * 1.13f), std::sin(phase * 1.71f + 2.f), std::sin(phase * 2.07f + 4.f));
916 v.eye += noise * (impulse.positionAmplitude * life);
917 const glm::vec3 forward = glm::normalize(v.target - v.eye);
918 glm::vec3 right = glm::cross(forward, glm::vec3(0.f, 1.f, 0.f));
919 if (glm::length(right) > 1e-5f)
920 right = glm::normalize(right);
921 else
922 right = glm::vec3(1.f, 0.f, 0.f);
923 const glm::vec3 up = glm::normalize(glm::cross(right, forward));
924 const float angular = std::tan(glm::radians(impulse.rotationAmplitude * life));
925 v.target += (right * noise.x + up * noise.y) * angular * glm::length(v.target - v.eye);
926 v.fov = glm::clamp(v.fov + impulse.fovAmplitude * life, 1.f, 179.f);
927 }
928 impulses_.erase(
929 std::remove_if(impulses_.begin(), impulses_.end(), [](const Impulse& i) { return i.age >= i.duration; }),
930 impulses_.end());
931}
932
933CameraController::View CameraController::desired() const {
934 View v;
935 v.fov = fovDeg_;
936 if (blending_) {
937 float t = blendDur_ > 0.f ? glm::clamp(blendT_ / blendDur_, 0.f, 1.f) : 1.f;
938 t = t * t * (3.f - 2.f * t);
939 v.eye = glm::mix(blendFrom_.eye, blendTo_.eye, t);
940 v.target = glm::mix(blendFrom_.target, blendTo_.target, t);
941 v.fov = glm::mix(blendFrom_.fov, blendTo_.fov, t);
942 } else if (mode_ == "orbit") {
943 const float az = glm::radians(azimuthDeg_);
944 const float el = glm::radians(elevationDeg_);
945 glm::vec3 dir(std::cos(el) * std::sin(az), std::sin(el), std::cos(el) * std::cos(az));
946 v.eye = target_ + dir * radius_;
947 v.target = target_;
948 } else if (mode_ == "topdown" || mode_ == "ortho") {
949 v.eye = target_ + glm::vec3(0.f, radius_, 0.f);
950 v.target = target_;
951 } else if (mode_ == "firstperson") {
952 v.eye = target_;
953 const float yaw = glm::radians(yawDeg_);
954 const float pitch = glm::radians(pitchDeg_);
955 glm::vec3 dir(std::cos(pitch) * std::sin(yaw), std::sin(pitch), std::cos(pitch) * std::cos(yaw));
956 v.target = v.eye + dir * 100.f;
957 } else if (mode_ == "cinematic") {
958 if (viewIndex_ >= 0 && viewIndex_ < static_cast<int>(views_.size())) {
959 v = views_[viewIndex_];
960 } else {
961 v.target = target_ + lookAhead_;
962 v.eye = v.target + offset_;
963 }
964 } else if (mode_ == "lockon") {
965 glm::vec3 back(offset_.x, 0.f, offset_.z);
966 float distance = glm::length(glm::vec2(back.x, back.z));
967 if (distance > 1e-5f)
968 back /= distance;
969 else
970 distance = std::max(radius_, 0.01f);
971 if (glm::length(glm::vec2(back.x, back.z)) < 1e-5f) {
972 const float yaw = glm::radians(yawDeg_);
973 back = glm::vec3(-std::sin(yaw), 0.f, -std::cos(yaw));
974 }
975 glm::vec3 look = target_ + glm::vec3(0.f, lookAhead_.y, 0.f);
976 if (hasSecondaryTarget_) {
977 look = 0.5f * (target_ + secondaryTarget_) + glm::vec3(0.f, lookAhead_.y, 0.f);
978 glm::vec3 toTarget = secondaryTarget_ - target_;
979 toTarget.y = 0.f;
980 const float length = glm::length(toTarget);
981 if (length > 1e-5f) back = -toTarget / length;
982 }
983 v.target = look;
984 v.eye = target_ + glm::vec3(back.x * distance, offset_.y, back.z * distance);
985 } else { // follow (默认)
986 v.target = target_ + lookAhead_;
987 v.eye = v.target + offset_;
988 }
989 const glm::vec3 forward = glm::normalize(v.target - v.eye);
990 glm::vec3 right = glm::cross(forward, glm::vec3(0.f, 1.f, 0.f));
991 if (glm::length(right) < 1e-5f)
992 right = glm::vec3(1.f, 0.f, 0.f);
993 else
994 right = glm::normalize(right);
995 glm::vec3 up = glm::normalize(glm::cross(right, forward));
996 const float distance = glm::length(v.target - v.eye);
997 v.target += (right * composition_.x + up * composition_.y) * distance;
998 return v;
999}
1000
1001void CameraController::applyView(const View& v) {
1002 if (!cam_) return;
1003 cam_->setEye(v.eye.x, v.eye.y, v.eye.z);
1004 cam_->setTarget(v.target.x, v.target.y, v.target.z);
1005 const glm::vec3 forward = glm::normalize(v.target - v.eye);
1006 glm::vec3 up(0.f, 1.f, 0.f);
1007 if (std::abs(glm::dot(forward, up)) > 0.999f) up = glm::vec3(0.f, 0.f, -1.f);
1008 glm::vec3 right=glm::normalize(glm::cross(forward,up));
1009 up=glm::normalize(glm::cross(right,forward));
1010 const float roll=glm::radians(cameraRollDeg_);
1011 up=up*std::cos(roll)+right*std::sin(roll);
1012 cam_->setUp(up.x, up.y, up.z);
1013 if (mode_ == "ortho")
1014 cam_->setOrthographic(orthoHeight_);
1015 else
1016 cam_->setFov(v.fov);
1017}
1018
1019void CameraController::easeToward(const View& v, float dt) {
1020 const float eyeK = 1.f - std::exp(-positionSmooth_ * dt);
1021 const float targetK = 1.f - std::exp(-targetSmooth_ * dt);
1022 glm::vec3 deye = (v.eye - cur_.eye) * eyeK;
1023 glm::vec3 dtgt = (v.target - cur_.target) * targetK;
1024 if (maxSpeed_ > 0.f && dt > 0.f) {
1025 const float maxStep = maxSpeed_ * dt;
1026 const float le = glm::length(deye);
1027 if (le > maxStep && le > 1e-6f) deye *= maxStep / le;
1028 const float lt = glm::length(dtgt);
1029 if (lt > maxStep && lt > 1e-6f) dtgt *= maxStep / lt;
1030 }
1031 cur_.eye += deye;
1032 cur_.target += dtgt;
1033 cur_.fov += (v.fov - cur_.fov) * eyeK;
1034}
1035
1037 cur_ = desired();
1038 initialized_ = true;
1039 applyView(cur_);
1040}
1041
1043 if (!cam_) return;
1044
1045 dt = std::max(0.f, dt);
1046 updateTrackedTarget();
1047 updateTimeline(dt);
1048 updateDirector();
1049
1050 if (mode_ == "cinematic" && playing_ && !views_.empty()) {
1051 timer_ += dt;
1052 if (!blending_ && timer_ >= stepTime_) {
1053 const int next = (viewIndex_ + 1) % static_cast<int>(views_.size());
1054 switchTo(views_[next].name, blendDur_);
1055 timer_ = 0.f;
1056 }
1057 }
1058
1059 if (blending_) {
1060 blendT_ += dt;
1061 if (blendT_ >= blendDur_) {
1062 blending_ = false;
1063 blendT_ = blendDur_;
1064 }
1065 }
1066
1067 // orbit 自动盘旋:不断累积方位角
1068 if (mode_ == "orbit") {
1069 azimuthDeg_ += orbitSpeedDeg_ * dt;
1070 }
1071
1072 View d = desired();
1073 applyCollision(d, dt);
1074 applyModifiers(d, dt);
1075
1076 if (!initialized_) {
1077 cur_ = d;
1078 initialized_ = true;
1079 }
1080 easeToward(d, dt);
1081 applyView(cur_);
1082}
1083
1084void Camera::expose(ssq::Class& cls) {
1085 // 模块级方法(如需要可在此添加);当前只通过 eve.CameraController 暴露控制器。
1086}
1087
1088void Camera::expose(ssq::Table& table) {
1089 auto cls = table.addClass(name, Camera::create, false);
1090 expose(cls);
1091
1092 auto cc = table.addClass<CameraController>(
1093 "CameraController", std::function<CameraController*()>([]() { return new CameraController(); }), true);
1094
1095 cc.addFunc("setCamera", &CameraController::setCamera);
1096 cc.addFunc("getCamera", &CameraController::getCamera);
1097 cc.addFunc("setActionCuesEnabled", &CameraController::setActionCuesEnabled);
1098 cc.addFunc("getActionCuesEnabled", &CameraController::getActionCuesEnabled);
1099 cc.addFunc("setPhotoModeAuthority", &CameraController::setPhotoModeAuthority);
1100 cc.addFunc("getPhotoModeAuthority", [](const CameraController* self){return self->getPhotoModeAuthority();});
1101 cc.addFunc("setCameraRoll", [vm=table.getHandle()](CameraController* self,float value){return eve::script::projectResult(vm,self->setCameraRoll(value));});
1102 cc.addFunc("getCameraRoll", [](const CameraController* self){return self->getCameraRoll();});
1103 cc.addFunc("getPcgCullingDistance", [](const CameraController* self){return self->getPcgCullingDistance();});
1104
1105 cc.addFunc("setTarget", &CameraController::setTarget);
1106 cc.addFunc("setTargetNode", &CameraController::setTargetNode);
1107 cc.addFunc("getTargetX", &CameraController::getTargetX);
1108 cc.addFunc("getTargetY", &CameraController::getTargetY);
1109 cc.addFunc("getTargetZ", &CameraController::getTargetZ);
1110 cc.addFunc("setOffset", &CameraController::setOffset);
1111 cc.addFunc("setLookAhead", &CameraController::setLookAhead);
1112 cc.addFunc("setSecondaryTarget", &CameraController::setSecondaryTarget);
1113 cc.addFunc("clearSecondaryTarget", &CameraController::clearSecondaryTarget);
1114 cc.addFunc("hasSecondaryTarget", [](const CameraController* self) { return self->hasSecondaryTarget(); });
1115 cc.addFunc("getSecondaryTargetX", &CameraController::getSecondaryTargetX);
1116 cc.addFunc("getSecondaryTargetY", &CameraController::getSecondaryTargetY);
1117 cc.addFunc("getSecondaryTargetZ", &CameraController::getSecondaryTargetZ);
1118
1119 cc.addFunc("setMode", &CameraController::setMode);
1120 cc.addFunc("getMode", &CameraController::getMode);
1121
1122 cc.addFunc("setRadius", &CameraController::setRadius);
1123 cc.addFunc("getRadius", &CameraController::getRadius);
1124 cc.addFunc("setRadiusLimits", [vm=table.getHandle()](CameraController* self,float minimum,float maximum) { return eve::script::projectResult(vm,self->setRadiusLimits(minimum,maximum)); });
1125 cc.addFunc("getMinimumRadius", &CameraController::getMinimumRadius);
1126 cc.addFunc("getMaximumRadius", &CameraController::getMaximumRadius);
1127 cc.addFunc("setAzimuth", &CameraController::setAzimuth);
1128 cc.addFunc("setElevation", &CameraController::setElevation);
1129 cc.addFunc("setOrbitSpeed", &CameraController::setOrbitSpeed);
1130 cc.addFunc("setOrthoHeight", &CameraController::setOrthoHeight);
1131 cc.addFunc("getOrthoHeight", &CameraController::getOrthoHeight);
1132
1133 cc.addFunc("setYaw", &CameraController::setYaw);
1134 cc.addFunc("setPitch", &CameraController::setPitch);
1135 cc.addFunc("addInput", &CameraController::addInput);
1136 cc.addFunc("setComposition", &CameraController::setComposition);
1137 cc.addFunc("setDeadZone", &CameraController::setDeadZone);
1138 cc.addFunc("setFov", &CameraController::setFov);
1139 cc.addFunc("getFov", &CameraController::getFov);
1140
1141 cc.addFunc("setSmooth", &CameraController::setSmooth);
1142 cc.addFunc("setPositionSmooth", &CameraController::setPositionSmooth);
1143 cc.addFunc("setTargetSmooth", &CameraController::setTargetSmooth);
1144 cc.addFunc("setMaxSpeed", &CameraController::setMaxSpeed);
1145 cc.addFunc("snap", &CameraController::snap);
1146 cc.addFunc("setCollisionEnabled", &CameraController::setCollisionEnabled);
1147 cc.addFunc("setCollisionRadius", &CameraController::setCollisionRadius);
1148 cc.addFunc("setCollisionRecovery", &CameraController::setCollisionRecovery);
1149 cc.addFunc("setCollisionMask", &CameraController::setCollisionMask);
1150 cc.addFunc("setCollisionIgnoredBody", &CameraController::setCollisionIgnoredBody);
1151 cc.addFunc("clearCollisionBoxes", &CameraController::clearCollisionBoxes);
1152 cc.addFunc("addCollisionBox", &CameraController::addCollisionBox);
1153 cc.addFunc("getCollisionBodyId", &CameraController::getCollisionBodyId);
1154 cc.addFunc("isObstructed", &CameraController::isObstructed);
1155
1156 cc.addFunc("addRig", &CameraController::addRig);
1157 cc.addFunc("removeRig", &CameraController::removeRig);
1158 cc.addFunc("setRigPriority", &CameraController::setRigPriority);
1159 cc.addFunc("setRigEnabled", &CameraController::setRigEnabled);
1160 cc.addFunc("saveRigState", &CameraController::saveRigState);
1161 cc.addFunc("activateRig", &CameraController::activateRig);
1162 cc.addFunc("getActiveRig", &CameraController::getActiveRig);
1163 cc.addFunc("addImpulse", &CameraController::addImpulse);
1164 cc.addFunc("addFovImpulse", &CameraController::addFovImpulse);
1165 cc.addFunc("clearImpulses", &CameraController::clearImpulses);
1166
1167 cc.addFunc("addView", &CameraController::addView);
1168 cc.addFunc("setView", [vm = table.getHandle()](CameraController* self, const std::string& name, float ex, float ey,
1169 float ez, float tx, float ty, float tz, float fov) {
1170 return eve::script::projectResult(vm, self->setView(name, ex, ey, ez, tx, ty, tz, fov));
1171 });
1172 cc.addFunc("switchTo", &CameraController::switchTo);
1173 cc.addFunc("playSequence", &CameraController::playSequence);
1174 cc.addFunc("stopSequence", &CameraController::stopSequence);
1175 cc.addFunc("isPlaying", &CameraController::isPlaying);
1176 cc.addFunc("setDirectorEnabled", &CameraController::setDirectorEnabled);
1177 cc.addFunc("getDirectorEnabled", [](const CameraController* self) { return self->getDirectorEnabled(); });
1178
1179 cc.addFunc("clearTimeline", &CameraController::clearTimeline);
1180 cc.addFunc("addTimelineCut", &CameraController::addTimelineCut);
1181 cc.addFunc("addTimelineEvent", &CameraController::addTimelineEvent);
1182 cc.addFunc("addTimelineFloat", &CameraController::addTimelineFloat);
1183 cc.addFunc("setEventSink", &CameraController::setEventSink);
1184 cc.addFunc("playTimeline", &CameraController::playTimeline);
1185 cc.addFunc("pauseTimeline", &CameraController::pauseTimeline);
1186 cc.addFunc("stopTimeline", &CameraController::stopTimeline);
1187 cc.addFunc("seekTimeline", &CameraController::seekTimeline);
1188 cc.addFunc("isTimelinePlaying", &CameraController::isTimelinePlaying);
1189 cc.addFunc("getTimelineTime", &CameraController::getTimelineTime);
1190 cc.addFunc("consumeTimelineEvent", &CameraController::consumeTimelineEvent);
1191 cc.addFunc("getTimelineEventData", &CameraController::getTimelineEventData);
1192 cc.addFunc("getPendingTimelineEventCount", &CameraController::getPendingTimelineEventCount);
1193 cc.addFunc("getTimelineDuration", &CameraController::getTimelineDuration);
1194 cc.addFunc("getRigCount", &CameraController::getRigCount);
1195 cc.addFunc("serializeAsset", &CameraController::serializeAsset);
1196 cc.addFunc("deserializeAsset", &CameraController::deserializeAsset);
1197
1198 cc.addFunc("update", &CameraController::update);
1202}
1203
1204} // namespace eve::camera
double z
double y
double m[16]
double x
LogicalId target
bool & active
float duration
int root
Definition AnimSmr.cpp:119
const std::string & s
float yaw
Definition BushMesh.cpp:37
int priority
float degrees
Definition CardTypes.cpp:38
b3Vec3 angular
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
float maximum[3]
float minimum[3]
float u
Definition Grass.cpp:233
double r
float v
HexVec3 up
HexVec3 right
std::int32_t c
std::int32_t first
std::uint32_t height
float length
JointPoint2D axis
std::string to
std::string from
Snapshot snapshot
MeleePoint3 b
Definition MeleeHit.cpp:41
double radius
Definition MeleeHit.cpp:42
MeleePoint3 a
Definition MeleeHit.cpp:40
float distance
#define Module_IMPL(ModuleName, newExpr)
Definition Module.h:27
ScriptMotionSinkStore< ScriptMotionFloatSink > floats
double dt
OceanSprayView view
std::vector< particles::ParticleRecordEvent > events
eve::action::ActionVfxBinding binding
TileLayer * layer
int idx
bool hit
Object::Ptr value
float d
float t
glm::vec3 eye
const RoadNode * node
int cuts
Definition RockMesh.cpp:25
double number
std::string text
ScriptStructure out
double current
The single Squirrel projection for common Result, Status and Value.
float phase
std::map< Cell, int > best
uint32_t seed
Definition TreeMesh.cpp:276
V3 dir
Definition TreeMesh.cpp:151
uint32_t index
V forward
std::array< double, 3 > impulse
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Human-readable, scoped identifier in the form namespace:name.
Definition Identity.h:414
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Definition Status.cpp:19
int getRigCount() const
Returns the rig count.
void setCollisionMask(uint64_t maskBits)
Sets the Box3D category mask used by dynamic obstruction queries.
float getTimelineDuration() const
Returns the timeline duration.
bool deserializeAsset(const std::string &json)
Replaces rigs and timeline data from a versioned JSON asset.
void setYaw(float deg)
Sets the yaw.
bool isObstructed() const
True when obstructed.
void setEventSink(platform_event::PlatformEvent *sink)
Sets the event sink.
int getCollisionBodyId() const
Returns the collision body id.
float getMinimumRadius() const
Return the minimum orbit radius.
bool supports(const LogicalId &cue) const noexcept override
Accept every project-defined camera cue while explicitly enabled.
void setCollisionRadius(float radius)
Sets the collision radius.
void addView(const std::string &name, float ex, float ey, float ez, float tx, float ty, float tz)
Adds view.
Result< void > setCameraRoll(float degrees)
Set finite camera roll in degrees.
CameraController()
Camera controller.
void setTarget(float x, float y, float z)
Sets the target.
void stopSequence()
Stops sequence.
void setSmooth(float damping)
Sets the smooth.
bool addTimelineCut(float time, const std::string &rigName, float blendTime)
Adds timeline cut.
void setRadius(float r)
Sets the radius.
void setActionCuesEnabled(bool enabled)
Opt this controller into or out of action camera-cue dispatch.
std::string getActiveRig() const
Returns the active rig.
void stopTimeline()
Stops timeline.
float getRadius() const
Return the current orbit radius.
float getTimelineTime() const
Returns the timeline time.
bool setRigEnabled(const std::string &name, bool enabled)
Sets the rig enabled.
std::string serializeAsset() const
Serializes rigs and timeline data as a versioned JSON asset.
void clearTimeline()
Clears timeline.
void setCamera(graphics::Camera3D *cam)
Sets the camera.
bool addTimelineFloat(float time, const std::string &property, float value)
Adds a linearly interpolated camera property key.
void setComposition(float screenX, float screenY)
Screen-space composition offset, expressed as normalized view fractions.
float getSecondaryTargetY() const
Returns the secondary target y.
bool removeRig(const std::string &name)
Removes rig.
Result< void > setRadiusLimits(float minimum, float maximum)
Set inclusive orbit zoom limits atomically.
void playTimeline(bool loop)
Play timeline.
float getMaximumRadius() const
Return the maximum orbit radius.
graphics::Camera3D * getCamera() const
Returns the camera.
Result< void > trigger(const action::ActionCameraCueBinding &binding, const action::ActionNotifyContext &context) override
Convert one action cue into deterministic positional, rotational and FOV impulses.
void setSecondaryTarget(float x, float y, float z)
Store a world-space lock-on look target for mode "lockon".
std::string getMode() const
Returns the mode.
void setPitch(float deg)
Sets the pitch.
float getTargetZ() const
Returns the target z.
float getSecondaryTargetZ() const
Returns the secondary target z.
void seekTimeline(float time, bool fireEvents=false)
Seeks timeline.
void addInput(float yawDeltaDeg, float pitchDeltaDeg, float zoomDelta)
Applies device-independent yaw, pitch and zoom deltas.
float getFov() const
Returns the fov.
void playSequence(float stepTime)
Play sequence.
bool getActionCuesEnabled() const
Return whether this controller is currently registered for action cues.
int getPendingTimelineEventCount() const
Returns the pending timeline event count.
CameraFramingSnapshot captureFraming() const
Snapshot gameplay framing so a story director can restore it later. @cost Constant copy of scalar fra...
bool addRig(const std::string &name, const std::string &mode, int priority)
Adds rig.
void setCollisionIgnoredBody(int bodyId)
Excludes one Box3D body id, normally the followed player body.
void setCollisionEnabled(bool enabled)
Enables swept-sphere obstruction against boxes registered below.
bool isPlaying() const
True when playing.
void setPhotoModeAuthority(bool enabled)
Register or revoke this controller as the sole photo-mode camera authority.
bool isTimelinePlaying() const
True when timeline playing.
float getTargetX() const
Returns the target x.
std::string consumeTimelineEvent()
Consume timeline event.
void addFovImpulse(float degrees, float duration)
Adds fov impulse.
void addImpulse(float positionAmplitude, float rotationAmplitude, float duration, unsigned int seed=0)
Adds a damped positional/rotational camera impulse.
void setPositionSmooth(float damping)
Sets the position smooth.
Result< void > applyPhotoModeField(const PhotoModeAssignment &assignment) override
Apply one camera assignment atomically to this controller and its bound Camera3D.
std::string getTimelineEventData() const
Returns the timeline event data.
void setLookAhead(float x, float y, float z)
follow:额外的视线前移点(可让镜头看向玩家前方)。
Result< void > restoreFraming(const CameraFramingSnapshot &snapshot, float blendTime)
Restore a previously captured framing, optionally blending from the live pose. @cost One pose evaluat...
void setMode(const std::string &mode)
Sets the mode.
void clearImpulses()
Clears impulses.
void clearCollisionBoxes()
Clears collision boxes.
void setTargetNode(scene::SceneNodeRef *node)
Follow a stable scene-node handle. nullptr restores explicit coordinates.
void clearSecondaryTarget()
Forget the lock-on look target; lockon then falls back to offset/yaw follow.
void setMaxSpeed(float unitsPerSec)
Sets the max speed.
bool switchTo(const std::string &name, float blendTime)
Switch to.
void setOffset(float x, float y, float z)
follow:摄像机相对 target 的偏移(默认 (0, 2, 6))。
Result< void > setView(const std::string &name, float ex, float ey, float ez, float tx, float ty, float tz, float fov)
Insert or replace a named cinematic view including FOV. @cost Constant; amortised over the next blend...
void setFov(float degrees)
Sets the fov.
void pauseTimeline()
Pause timeline.
bool saveRigState(const std::string &name)
Stores the controller's current framing/lens parameters in a rig preset.
void setElevation(float deg)
Sets the elevation.
void setOrthoHeight(float height)
Vertical world span for mode "ortho" (Camera3D::setOrthographic).
float getOrthoHeight() const
Return the orthographic height used by mode "ortho".
bool setRigPriority(const std::string &name, int priority)
Sets the rig priority.
PhotoModeFieldAcceptance acceptsPhotoModeField(const PhotoModeAssignment &assignment) const noexcept override
Return whether this controller owns a photo-mode camera assignment.
bool activateRig(const std::string &name, float blendTime)
Activate rig.
void setOrbitSpeed(float degPerSec)
Sets the orbit speed.
~CameraController() override
Camera controller.
void setTargetSmooth(float damping)
Sets the target smooth.
void setDeadZone(float radius)
Dead-zone radius in world units around the tracked target.
void addCollisionBox(float minX, float minY, float minZ, float maxX, float maxY, float maxZ)
Adds collision box.
void setAzimuth(float deg)
Sets the azimuth.
void setDirectorEnabled(bool enabled)
Pause or resume priority-rig director selection (story cameras need this off).
float getTargetY() const
Returns the target y.
void setCollisionRecovery(float damping)
Sets the collision recovery.
bool addTimelineEvent(float time, const std::string &name, const std::string &data)
Adds timeline event.
摄像机模块命名空间(eve.Camera)。主要职责是把 CameraController 绑定进脚本。
EVENGINE_API_BACKENDS public API.
float getEyeX()
Camera eye position (world space).
float getNearClip()
Return the positive near clipping distance.
float getAperture()
Return physical-camera aperture.
void setDepthOfField(float focusDistance, float maxBlurPx, float focusRange=8.f)
Configure Gaussian depth-of-field on the final HDR resolve.
float getFocalLength()
Return physical-camera focal length in millimetres.
void setLayerCullDistance(int layer, float distance)
Set the camera cull distance for one render layer; zero disables the override.
void setPerspective()
Return to perspective projection, retaining the configured field of view.
void setUp(float x, float y, float z)
void setOrthographic(float height)
Enable a pure orthographic projection with the given vertical world-space span.
void setFov(float fovYDeg)
void setPhysicalLens(float aperture, float focalLength)
Set positive physical-camera aperture and focal length metadata.
void setExposure(float ev)
Set exposure compensation in photographic stops. Positive values brighten.
float getFarClip()
Return the far clipping distance.
void setAutoExposure(bool enabled, float minEV=-8.f, float maxEV=8.f)
Enable log-average automatic exposure and set its EV clamp range.
void setTarget(float x, float y, float z)
void clearDepthOfField()
Disable depth-of-field while retaining the current focus settings.
void setEye(float x, float y, float z)
float getTargetX()
Look-at target (world space).
void setClipPlanes(float nearZ, float farZ)
Set positive near/far clipping distances; far is kept beyond near.
static Document parse(const std::string &text, std::string *error=nullptr)
Parse.
Definition Json.cpp:623
EVENGINE_API_FOUNDATION public API.
Definition Json.h:39
EVENGINE_API_FOUNDATION public API.
void pushData(std::string name, std::string data="")
Script helper: pushes an event with an optional string payload.
Script handle to a scene node (hostName + nodeId). Deliberately holds strings rather than arena point...
void exposeCinemaDirectorBindings(ssq::Table &table)
Register CinemaDirector EveScript bindings on the camera module table.
void exposePcgFreeCameraBindings(ssq::Table &t)
Register Pcg free-camera bindings.
void exposePcgCarCameraSetupBindings(ssq::Table &t)
Register Pcg vehicle camera bindings.
I * query()
Queries .
Definition Capability.h:88
constexpr HexDirection next(HexDirection d) noexcept
The next direction clockwise (NW wraps to NE).
Definition HexMetrics.h:76
std::unordered_map< std::string, SkillDefinition > & table()
Definition Skill.cpp:73
int64_t integer(const RuntimeTensor &v, size_t i=0)
Integer.
PhotoModeFieldAcceptance
Capability implemented by the composition root that routes assignments to domain owners.
bool enabled
Closest hit returned by the optional camera-obstruction provider.
One reversible field assignment in a photo-mode transaction.
Owning validated camera impulse shared by action runtime and camera targets.
Context linking a routed event to its action execution.
Serializable gameplay camera framing for story push/pop restore.