Debian Codegraph @

avogadro/qtplugins/resetview/resetview.cpp

raw
1 /******************************************************************************
2 This source file is part of the Avogadro project.
3 This source code is released under the 3-Clause BSD License, (see "LICENSE").
4 ******************************************************************************/
5
6 #include "resetview.h"
7
8 #include <avogadro/qtgui/molecule.h>
9 #include <avogadro/qtopengl/glwidget.h>
10 #include <avogadro/rendering/camera.h>
11
12 #include <QAction>
13 #include <QDebug>
14 #include <QOpenGLWidget>
15 #include <QTimer>
16
17 #include <algorithm>
18 #include <limits>
19
20 #define CAMERA_NEAR_DISTANCE 13.35f // Experimental number
21
22 namespace Avogadro::QtPlugins {
23
24 using Avogadro::QtGui::ExtensionPlugin;
25 using Core::Array;
26 using Eigen::Affine3f;
27 using Eigen::EigenSolver;
28 using Eigen::Matrix3d;
29 using Eigen::Matrix3f;
30 using Eigen::Quaternionf;
31 using Eigen::Vector3d;
32 using Rendering::Projection;
33 using std::numeric_limits;
34
35 const float ResetView::DELTA_TIME = 100.0f / 3.0f; // 33.3 ms ~ 30 fps
36 const int ResetView::TOTAL_FRAMES = 25; // ~1 sec
37
38 ResetView::ResetView(QObject* parent_)
39 : ExtensionPlugin(parent_), m_centerAction(new QAction(tr("Center"), this)),
40 m_viewToAxesAction(new QAction(tr("Align View to Axes"), this))
41 {
42 m_centerAction->setProperty("menu priority", 210);
43 m_viewToAxesAction->setProperty("menu priority", 200);
44
45 connect(m_centerAction, SIGNAL(triggered()), SLOT(centerView()));
46 connect(m_viewToAxesAction, SIGNAL(triggered()), SLOT(alignToAxes()));
47 }
48
49 ResetView::~ResetView() {}
50
51 void ResetView::registerCommands()
52 {
53 emit registerCommand("alignView", tr("Align view to axes."));
54 }
55
56 bool ResetView::handleCommand(const QString& command,
57 [[maybe_unused]] const QVariantMap& options)
58 {
59 if (m_molecule == nullptr || m_camera == nullptr)
60 return false; // Nothing to do
61
62 if (command == "alignView") {
63 animationCameraDefault(false);
64 return true;
65 }
66 return false;
67 }
68
69 QList<QAction*> ResetView::actions() const
70 {
71 QList<QAction*> result;
72 return result << m_centerAction << m_viewToAxesAction;
73 }
74
75 QStringList ResetView::menuPath(QAction*) const
76 {
77 return QStringList() << tr("&View");
78 }
79
80 void ResetView::setMolecule(QtGui::Molecule* mol)
81 {
82 m_molecule = mol;
83 }
84
85 void ResetView::setCamera(Rendering::Camera* camera)
86 {
87 m_camera = camera;
88 }
89
90 void ResetView::setActiveWidget(QWidget* widget)
91 {
92 if (widget != nullptr) {
93 m_glWidget = widget;
94 connect(this, SIGNAL(updateRequested()), m_glWidget, SLOT(requestUpdate()));
95 }
96 }
97
98 bool ResetView::defaultChecks()
99 {
100 if (m_molecule == nullptr || m_camera == nullptr)
101 return true;
102
103 // Check for 3D coordinates - it's useless to consider the camera otherwise
104 if (m_molecule->atomPositions3d().size() != m_molecule->atomCount())
105 return true;
106
107 // no need to animate when there are no atoms
108 if (m_molecule->atomCount() == 0) {
109 animationCameraDefault(false);
110 return true;
111 }
112 return false;
113 }
114
115 inline float getZDistance(const Affine3f& projection, float x,
116 Projection perspective)
117 {
118 if (perspective == Projection::Perspective) {
119 float fov = 2.0f * std::atan(1.0f / projection(1, 1));
120 // float aspect = projection(1,1) / projection(0,0);
121 // tan (fov/2) = (x/2) / z -> z = (x/2) / tan (fov/2)
122 return std::max(CAMERA_NEAR_DISTANCE, (x / 2.0f) / std::tan(fov / 2.0f));
123 } else {
124 return 3.0f * CAMERA_NEAR_DISTANCE;
125 }
126 }
127 inline void getBB(const Array<Vector3>& mols, Vector3& min, Vector3& max)
128 {
129 if (mols.size() > 0) {
130 min = mols[0];
131 max = mols[0];
132 for (size_t i = 1; i < mols.size(); ++i) {
133 min.x() = std::min(mols[i].x(), min.x());
134 max.x() = std::max(mols[i].x(), max.x());
135
136 min.y() = std::min(mols[i].y(), min.y());
137 max.y() = std::max(mols[i].y(), max.y());
138
139 min.z() = std::min(mols[i].z(), min.z());
140 max.z() = std::max(mols[i].z(), max.z());
141 }
142 } else {
143 min = max = Vector3(0, 0, 0);
144 }
145 } // namespace QtPlugins
146
147 void ResetView::animationCameraDefault(bool animate)
148 {
149 Matrix3f linearGoal;
150 linearGoal.row(0) = Vector3f::UnitX();
151 linearGoal.row(1) = Vector3f::UnitY();
152 linearGoal.row(2) = Vector3f::UnitZ();
153 // calculate the translation matrix
154 auto goal = Affine3f(linearGoal);
155
156 const Array<Vector3>& mols = m_molecule->atomPositions3d();
157 Vector3 min, max;
158 getBB(mols, min, max);
159 Vector3f mid = (max.cast<float>() + min.cast<float>()) / 2.0f;
160 float d = getZDistance(m_camera->projection(), max.x() - min.x(),
161 m_camera->projectionType());
162
163 Vector3f eye = -mid + (Vector3f::UnitZ() * -d);
164 goal.translate(eye);
165 animationCamera(goal, animate);
166 }
167
168 float ResetView::calculateOptimalOrthographicScale(
169 const Affine3f& viewTransform)
170 {
171 if (m_camera->projectionType() != Projection::Orthographic) {
172 return 1.0f;
173 }
174
175 const Array<Vector3>& mols = m_molecule->atomPositions3d();
176 Vector3 min, max;
177 getBB(mols, min, max);
178
179 // Transform bounding box corners to view space
180 float infinity = numeric_limits<float>::infinity();
181 Vector3f minView{ infinity, infinity, infinity };
182 Vector3f maxView{ -infinity, -infinity, -infinity };
183
184 Vector3f corners[8] = {
185 Vector3f(min.x(), min.y(), min.z()), Vector3f(max.x(), min.y(), min.z()),
186 Vector3f(min.x(), max.y(), min.z()), Vector3f(max.x(), max.y(), min.z()),
187 Vector3f(min.x(), min.y(), max.z()), Vector3f(max.x(), min.y(), max.z()),
188 Vector3f(min.x(), max.y(), max.z()), Vector3f(max.x(), max.y(), max.z())
189 };
190
191 for (const auto& corner : corners) {
192 Vector3f transformed = viewTransform * corner;
193 minView.x() = std::min(transformed.x(), minView.x());
194 maxView.x() = std::max(transformed.x(), maxView.x());
195 minView.y() = std::min(transformed.y(), minView.y());
196 maxView.y() = std::max(transformed.y(), maxView.y());
197 }
198
199 // Calculate scene extent in view space
200 float sceneWidth = maxView.x() - minView.x();
201 float sceneHeight = maxView.y() - minView.y();
202
203 // Base orthographic frustum has half-height of 5.0
204 float baseHalfHeight = 5.0f;
205 float aspectRatio = static_cast<float>(m_camera->width()) /
206 static_cast<float>(m_camera->height());
207 float baseHalfWidth = baseHalfHeight * aspectRatio;
208
209 // Calculate scale needed to fit with 10% padding
210 float scaleX = (sceneWidth / 2.0f) / baseHalfWidth * 1.1f;
211 float scaleY = (sceneHeight / 2.0f) / baseHalfHeight * 1.1f;
212
213 float optimalScale = std::max(scaleX, scaleY);
214
215 // Clamp to reasonable values
216 return std::clamp(optimalScale, 0.1f, 10.0f);
217 }
218
219 void ResetView::animationCamera(const Affine3f& goal, bool animate)
220 {
221 if (animate) {
222 Matrix3f rot_aux = goal.rotation();
223 Vector3f posGoal = goal.translation();
224 auto rotGoal = Quaternionf(rot_aux);
225
226 Affine3f start = m_camera->modelView();
227
228 rot_aux = start.rotation();
229 Vector3f posStart = start.translation();
230 auto rotStart = Quaternionf(rot_aux);
231
232 // Calculate optimal orthographic scales
233 float scaleStart = m_camera->orthographicScale();
234 float scaleGoal = calculateOptimalOrthographicScale(goal);
235
236 for (int frame = 0; frame <= ResetView::TOTAL_FRAMES; ++frame) {
237 Affine3f interpolation;
238 float alpha = frame / float(ResetView::TOTAL_FRAMES);
239 interpolation.fromPositionOrientationScale(
240 ((1.0f - alpha) * posStart) + (alpha * posGoal),
241 rotStart.slerp(alpha, rotGoal), Vector3f(1.0f, 1.0f, 1.0f));
242
243 // Interpolate orthographic scale
244 float interpolatedScale = (1.0f - alpha) * scaleStart + alpha * scaleGoal;
245
246 float time = frame * ResetView::DELTA_TIME;
247 QTimer::singleShot(
248 time, this, [this, interpolation, interpolatedScale]() {
249 m_camera->setModelView(interpolation);
250 if (m_camera->projectionType() == Projection::Orthographic) {
251 m_camera->setOrthographicScale(interpolatedScale);
252 }
253 emit updateRequested();
254 });
255 }
256
257 } else {
258 m_camera->setModelView(goal);
259
260 // Set optimal orthographic scale immediately
261 float optimalScale = calculateOptimalOrthographicScale(goal);
262 m_camera->setOrthographicScale(optimalScale);
263
264 emit updateRequested();
265 }
266 }
267
268 // Calculate the oriented bounding box to get the most significant
269 // axis base and the centroid
270 inline void getOBB(const Array<Vector3>& mols, Vector3d& centroid,
271 Vector3d& min, Vector3d& mid, Vector3d& max)
272 {
273 centroid = Vector3::Zero();
274
275 for (const auto& mol : mols)
276 centroid += mol;
277
278 centroid /= (double)mols.size();
279 Matrix3d covariance = Matrix3::Zero();
280
281 for (const auto& mol : mols) {
282 Vector3d adjusted = mol - centroid;
283 covariance += adjusted * adjusted.transpose();
284 }
285 covariance /= (double)mols.size();
286
287 auto solver = EigenSolver<Matrix3>(covariance);
288 Eigen::Matrix3d vectors = solver.eigenvectors().real();
289
290 max = vectors.row(0);
291 mid = vectors.row(1);
292 min = vectors.row(2);
293 }
294
295 void ResetView::centerView()
296 {
297 if (defaultChecks())
298 return;
299
300 const Array<Vector3>& mols = m_molecule->atomPositions3d();
301 Vector3d centroid, min, mid, max;
302 getOBB(mols, centroid, min, mid, max);
303
304 Matrix3f linearGoal;
305 linearGoal.col(0) = (max.normalized()).cast<float>(); // x
306 linearGoal.col(1) = (mid.normalized()).cast<float>(); // y
307 linearGoal.col(2) = (min.normalized()).cast<float>(); // z
308 // calculate the translation matrix
309 auto goal = Affine3f(linearGoal);
310
311 // eigen return the eigenvectors normalized, but we need a non-normalized
312 // so we project all the points to the axis and get the min/max
313 float infinity = numeric_limits<float>::infinity();
314 Vector3f minScreen{ infinity, infinity, infinity };
315 Vector3f maxScreen{ -infinity, -infinity, -infinity };
316 for (const auto& atom : mols) {
317 Vector3f aux = linearGoal * Vector3f(atom.x(), atom.y(), atom.z());
318 minScreen.x() = std::min(aux.x(), minScreen.x());
319 maxScreen.x() = std::max(aux.x(), maxScreen.x());
320
321 minScreen.y() = std::min(aux.y(), minScreen.y());
322 maxScreen.y() = std::max(aux.y(), maxScreen.y());
323
324 minScreen.z() = std::min(aux.z(), minScreen.z());
325 maxScreen.z() = std::max(aux.z(), maxScreen.z());
326 }
327 Vector3f midScreen = (maxScreen + minScreen) / 2.0f;
328 float d = getZDistance(m_camera->projection(), maxScreen.x() - minScreen.x(),
329 m_camera->projectionType());
330 midScreen.z() = 0;
331 Vector3f eye = -midScreen + (Vector3f::UnitZ() * -d);
332 goal.pretranslate(eye);
333
334 animationCamera(goal);
335 }
336
337 void ResetView::alignToAxes()
338 {
339 if (defaultChecks())
340 return;
341 animationCameraDefault();
342 }
343
344 } // namespace Avogadro::QtPlugins