source: src/UIElements/Views/Qt4/Qt3D/GLMoleculeObject_molecule.cpp@ d48a16

Action_Thermostats Add_AtomRandomPerturbation Add_FitFragmentPartialChargesAction Add_RotateAroundBondAction Add_SelectAtomByNameAction Added_ParseSaveFragmentResults AddingActions_SaveParseParticleParameters Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_ParticleName_to_Atom Adding_StructOpt_integration_tests AtomFragments Automaking_mpqc_open AutomationFragmentation_failures Candidate_v1.5.4 Candidate_v1.6.0 Candidate_v1.6.1 ChangeBugEmailaddress ChangingTestPorts ChemicalSpaceEvaluator CombiningParticlePotentialParsing Combining_Subpackages Debian_Package_split Debian_package_split_molecuildergui_only Disabling_MemDebug Docu_Python_wait EmpiricalPotential_contain_HomologyGraph EmpiricalPotential_contain_HomologyGraph_documentation Enable_parallel_make_install Enhance_userguide Enhanced_StructuralOptimization Enhanced_StructuralOptimization_continued Example_ManyWaysToTranslateAtom Exclude_Hydrogens_annealWithBondGraph FitPartialCharges_GlobalError Fix_BoundInBox_CenterInBox_MoleculeActions Fix_ChargeSampling_PBC Fix_ChronosMutex Fix_FitPartialCharges Fix_FitPotential_needs_atomicnumbers Fix_ForceAnnealing Fix_IndependentFragmentGrids Fix_ParseParticles Fix_ParseParticles_split_forward_backward_Actions Fix_PopActions Fix_QtFragmentList_sorted_selection Fix_Restrictedkeyset_FragmentMolecule Fix_StatusMsg Fix_StepWorldTime_single_argument Fix_Verbose_Codepatterns Fix_fitting_potentials Fixes ForceAnnealing_goodresults ForceAnnealing_oldresults ForceAnnealing_tocheck ForceAnnealing_with_BondGraph ForceAnnealing_with_BondGraph_continued ForceAnnealing_with_BondGraph_continued_betteresults ForceAnnealing_with_BondGraph_contraction-expansion FragmentAction_writes_AtomFragments FragmentMolecule_checks_bonddegrees GeometryObjects Gui_Fixes Gui_displays_atomic_force_velocity ImplicitCharges IndependentFragmentGrids IndependentFragmentGrids_IndividualZeroInstances IndependentFragmentGrids_IntegrationTest IndependentFragmentGrids_Sole_NN_Calculation JobMarket_RobustOnKillsSegFaults JobMarket_StableWorkerPool JobMarket_unresolvable_hostname_fix MoreRobust_FragmentAutomation ODR_violation_mpqc_open PartialCharges_OrthogonalSummation PdbParser_setsAtomName PythonUI_with_named_parameters QtGui_reactivate_TimeChanged_changes Recreated_GuiChecks Rewrite_FitPartialCharges RotateToPrincipalAxisSystem_UndoRedo SaturateAtoms_findBestMatching SaturateAtoms_singleDegree StoppableMakroAction Subpackage_CodePatterns Subpackage_JobMarket Subpackage_LinearAlgebra Subpackage_levmar Subpackage_mpqc_open Subpackage_vmg Switchable_LogView ThirdParty_MPQC_rebuilt_buildsystem TrajectoryDependenant_MaxOrder TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps TremoloParser_setsAtomName Ubuntu_1604_changes stable
Last change on this file since d48a16 was 96f14a, checked in by Frederik Heber <heber@…>, 9 years ago

Modified all GLMoleculeObjects and GLWorldScene to the new QtObservedBond.

  • GLWorldScene transmits bondInserted/bondRemoved similarly to those for the atoms to the molecule if aLready present and otherwise into the MissedStateMap.
  • Property mode set to 100644
File size: 17.0 KB
Line 
1/*
2 * Project: MoleCuilder
3 * Description: creates and alters molecular systems
4 * Copyright (C) 2010-2012 University of Bonn. All rights reserved.
5 * Copyright (C) 2013 Frederik Heber. All rights reserved.
6 *
7 *
8 * This file is part of MoleCuilder.
9 *
10 * MoleCuilder is free software: you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation, either version 2 of the License, or
13 * (at your option) any later version.
14 *
15 * MoleCuilder is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License
21 * along with MoleCuilder. If not, see <http://www.gnu.org/licenses/>.
22 */
23
24/*
25 * GLMoleculeObject_molecule.cpp
26 *
27 * Created on: Mar 30, 2012
28 * Author: ankele
29 */
30
31
32// include config.h
33#ifdef HAVE_CONFIG_H
34#include <config.h>
35#endif
36
37#include "GLMoleculeObject_molecule.hpp"
38
39#include <Qt3D/qglscenenode.h>
40#include <Qt3D/qglbuilder.h>
41
42#include "UIElements/Views/Qt4/Qt3D/GLMoleculeObject_atom.hpp"
43
44#include "CodePatterns/MemDebug.hpp"
45
46#include <boost/assign.hpp>
47
48#include "CodePatterns/Assert.hpp"
49#include "CodePatterns/IteratorAdaptors.hpp"
50#include "CodePatterns/Log.hpp"
51
52#include "LinearAlgebra/Vector.hpp"
53#include "LinkedCell/PointCloudAdaptor.hpp"
54#include "LinkedCell/linkedcell.hpp"
55#include "Tesselation/tesselation.hpp"
56#include "Tesselation/BoundaryLineSet.hpp"
57#include "Tesselation/BoundaryTriangleSet.hpp"
58#include "Tesselation/CandidateForTesselation.hpp"
59#include "UIElements/Qt4/InstanceBoard/QtObservedInstanceBoard.hpp"
60#include "Atom/TesselPoint.hpp"
61#include "World.hpp"
62
63using namespace boost::assign;
64
65static Observable::channels_t getAllAtomicChangesChannels()
66{
67 Observable::channels_t channels;
68 channels += molecule::AtomInserted, molecule::AtomRemoved, molecule::AtomMoved;
69 return channels;
70}
71
72const Observable::channels_t GLMoleculeObject_molecule::HullChannels(getAllAtomicChangesChannels());
73
74static QGLSceneNode *createMoleculeMesh(const QGeometryData &_geo)
75{
76 // Build a mesh from the geometry.
77 QGLBuilder builder;
78 builder.addTriangles(_geo);
79 QGLSceneNode *mesh = builder.finalizedSceneNode();
80 return mesh;
81}
82
83GLMoleculeObject_molecule::GLMoleculeObject_molecule(
84 QObject *parent,
85 QtObservedInstanceBoard &_board,
86 QtObservedMolecule::ptr &_ObservedMolecule) :
87 GLMoleculeObject((QGLSceneNode *)NULL, parent),
88 owner(NULL),
89 hoverAtomId(-1),
90 board(_board),
91 ObservedMolecule(_ObservedMolecule)
92{
93 init();
94}
95
96GLMoleculeObject_molecule::GLMoleculeObject_molecule(
97 QGLSceneNode *mesh[],
98 QObject *parent,
99 QtObservedInstanceBoard &_board,
100 QtObservedMolecule::ptr &_ObservedMolecule) :
101 GLMoleculeObject(mesh, parent),
102 owner(NULL),
103 hoverAtomId(-1),
104 board(_board),
105 ObservedMolecule(_ObservedMolecule)
106{
107 init();
108}
109
110void GLMoleculeObject_molecule::init()
111{
112 setObjectId(ObservedMolecule->getMolIndex());
113 setMaterial(getMaterial(1));
114
115 m_selected = ObservedMolecule->getMolSelected();
116
117 // initially, atoms and bonds should be visible
118 m_visible = false;
119
120 connect (this, SIGNAL(hoverChanged(GLMoleculeObject *)), this, SLOT(hoverChangedSignalled(GLMoleculeObject *)));
121 connect (this, SIGNAL(hoverChanged(GLMoleculeObject *)), this, SIGNAL(changed()));
122 connect (ObservedMolecule.get(), SIGNAL(tesselationhullChanged()), this, SLOT(resetTesselationHull()));
123 connect (ObservedMolecule.get(), SIGNAL(boundingboxChanged()), this, SLOT(resetBoundingBox()));
124 connect (ObservedMolecule.get(), SIGNAL(indexChanged(const moleculeId_t, const moleculeId_t)),
125 this, SLOT(resetIndex(const moleculeId_t, const moleculeId_t)));
126 /// these are channeled through GLWorldScene instead to ensure synchronicity
127// connect (ObservedMolecule.get(), SIGNAL(atomInserted(QtObservedAtom::ptr)),
128// this, SLOT(atomInserted(QtObservedAtom::ptr)) );
129// connect (ObservedMolecule.get(), SIGNAL(atomRemoved(const atomId_t)),
130// this, SLOT(atomRemoved(const atomId_t)) );
131 connect (ObservedMolecule.get(), SIGNAL(selectedChanged()), this, SLOT(resetSelected()));
132
133 connect( this, SIGNAL(clicked()), this, SLOT(wasClicked()));
134}
135
136GLMoleculeObject_molecule::~GLMoleculeObject_molecule()
137{}
138
139QGeometryData GLMoleculeObject_molecule::updateTesselationHull() const
140{
141 QGeometryData geo;
142
143 const molecule * const molref =
144 QtObservedMolecule::getMolecule(ObservedMolecule->getMolIndex());
145 if (molref == NULL) {
146 ELOG(1, "Could not createMoleculeMesh, molecule with id "
147 << ObservedMolecule->getMolIndex() << " already gone.");
148 return geo;
149 }
150 double minradius = 2.; // TODO: set to maximum bond length value
151 LOG(3, "DEBUG: Molecule fits into sphere of radius " << minradius);
152 // check minimum bond radius in molecule
153 double minlength = std::numeric_limits<double>::max();
154 for (molecule::const_iterator iter = molref->begin();
155 iter != molref->end(); ++iter) {
156 const BondList &ListOfBonds = (*iter)->getListOfBonds();
157 for (BondList::const_iterator bonditer = ListOfBonds.begin();
158 bonditer != ListOfBonds.end(); ++bonditer) {
159 const double bond_distance = (*bonditer)->GetDistance();
160 minlength = std::min(bond_distance, minlength);
161 }
162 }
163 minradius = std::max( std::max(minradius, minlength), 1.);
164
165 // we need at least three points for tesselation
166 if (AtomsinSceneMap.size() >= 3) {
167 // Tesselate the points.
168 Tesselation T;
169 PointCloudAdaptor<molecule> cloud(
170 const_cast<molecule *>(molref),
171 ObservedMolecule->getMolName());
172 T(cloud, minradius);
173
174 // Fill the points into a Qt geometry.
175 LinkedCell_deprecated LinkedList(cloud, minradius);
176 std::map<int, int> indices;
177 std::map<int, Vector> normals;
178 int index = 0;
179 for (PointMap::const_iterator piter = T.PointsOnBoundary.begin();
180 piter != T.PointsOnBoundary.end(); ++piter) {
181 const Vector &point = piter->second->getPosition();
182 // add data to the primitive
183 geo.appendVertex(QVector3D(point[0], point[1], point[2]));
184 Vector normalvector;
185 for (LineMap::const_iterator lineiter = piter->second->lines.begin();
186 lineiter != piter->second->lines.end(); ++lineiter)
187 for (TriangleMap::const_iterator triangleiter = lineiter->second->triangles.begin();
188 triangleiter != lineiter->second->triangles.end(); ++triangleiter)
189 normalvector +=
190 triangleiter->second->NormalVector;
191 normalvector.Normalize();
192 geo.appendNormal(QVector3D(normalvector[0], normalvector[1], normalvector[2]));
193 geo.appendColor(QColor(1, 1, 1, 1));
194 geo.appendTexCoord(QVector2D(0, 0));
195 indices.insert( std::make_pair( piter->second->getNr(), index++));
196 }
197
198 // Fill the tesselated triangles into the geometry.
199 for (TriangleMap::const_iterator runner = T.TrianglesOnBoundary.begin();
200 runner != T.TrianglesOnBoundary.end(); runner++) {
201 int v[3];
202 for (size_t i=0; i<3; ++i)
203 v[i] = runner->second->endpoints[i]->getNr();
204
205 // Sort the vertices so the triangle is clockwise (relative to the normal vector).
206 Vector cross = T.PointsOnBoundary[v[1]]->getPosition() - T.PointsOnBoundary[v[0]]->getPosition();
207 cross.VectorProduct(T.PointsOnBoundary[v[2]]->getPosition() - T.PointsOnBoundary[v[0]]->getPosition());
208 if (cross.ScalarProduct(runner->second->NormalVector) > 0)
209 geo.appendIndices(indices[v[0]], indices[v[1]], indices[v[2]]);
210 else
211 geo.appendIndices(indices[v[0]], indices[v[2]], indices[v[1]]);
212 }
213 }
214
215 return geo;
216}
217
218void GLMoleculeObject_molecule::resetTesselationHull()
219{
220 if (owner != NULL) {
221 TesselationHull = updateTesselationHull();
222 updateMesh(createMoleculeMesh(TesselationHull));
223 }
224}
225
226void GLMoleculeObject_molecule::resetBoundingBox()
227{
228 molecule::BoundingBoxInfo info = ObservedMolecule->getBoundingBox();
229 setPosition(QVector3D(info.position[0], info.position[1], info.position[2]));
230 setScale(info.radius + 0.3); // getBoundingSphere() only sees atoms as points, so make the box a bit bigger
231}
232
233void GLMoleculeObject_molecule::resetIndex(const moleculeId_t, const moleculeId_t)
234{
235 const atomId_t newId = ObservedMolecule->getMolIndex();
236 const size_t oldId = objectId();
237 ASSERT( newId != oldId,
238 "GLMoleculeObject_molecule::resetIndex() - index "+toString(newId)+" did not change.");
239 LOG(4, "INFO: GLMoleculeObject_molecule: new index is "+toString(newId)+".");
240 setObjectId(newId);
241}
242
243void GLMoleculeObject_molecule::resetSelected()
244{
245 const bool new_selected = ObservedMolecule->getMolSelected();
246 m_selected = new_selected;
247
248 emit changed();
249}
250
251void GLMoleculeObject_molecule::initialize(QGLView *view, QGLPainter *painter)
252{
253 // Initialize all of the mesh objects that we have as children.
254 if (m_visible) {
255 GLMoleculeObject::initialize(view, painter);
256 } else {
257 foreach (QObject *obj, children()) {
258 GLMoleculeObject *meshobj = qobject_cast<GLMoleculeObject *>(obj);
259 if (meshobj)
260 meshobj->initialize(view, painter);
261 }
262 }
263}
264
265void GLMoleculeObject_molecule::draw(QGLPainter *painter, const QVector4D &cameraPlane)
266{
267 // draw either molecule's mesh or all atoms and bonds
268 if (m_visible) {
269 resetTesselationHull();
270
271 painter->modelViewMatrix().push();
272
273 // Apply the material and effect to the painter.
274 QGLMaterial *material;
275 if (m_hovering)
276 material = m_hoverMaterial;
277 else if (m_selected)
278 material = m_selectionMaterial;
279 else
280 material = m_material;
281
282 ASSERT(material, "GLMoleculeObject::draw: chosen material is NULL");
283
284 painter->setColor(material->diffuseColor());
285 painter->setFaceMaterial(QGL::AllFaces, material);
286 if (m_effect)
287 painter->setUserEffect(m_effect);
288 else
289 painter->setStandardEffect(QGL::LitMaterial);
290
291 // Mark the object for object picking purposes.
292 int prevObjectId = painter->objectPickId();
293 if (m_objectId != -1)
294 painter->setObjectPickId(m_objectId);
295
296 m_mesh[0]->draw(painter);
297
298 // Turn off the user effect, if present.
299 if (m_effect)
300 painter->setStandardEffect(QGL::LitMaterial);
301
302 // Revert to the previous object identifier.
303 painter->setObjectPickId(prevObjectId);
304
305 // Restore the modelview matrix.
306 painter->modelViewMatrix().pop();
307
308 // GLMoleculeObject::draw(painter, cameraPlane);
309 } else {
310 // Draw all of the mesh objects that we have as children.
311 foreach (QObject *obj, children()) {
312 GLMoleculeObject *meshobj = qobject_cast<GLMoleculeObject *>(obj);
313 if (meshobj)
314 meshobj->draw(painter, cameraPlane);
315 }
316
317 // update bounding box prior to selection
318 resetBoundingBox();
319
320 painter->modelViewMatrix().push();
321 painter->modelViewMatrix().translate(m_position);
322 if (m_rotationAngle != 0.0f)
323 painter->modelViewMatrix().rotate(m_rotationAngle, m_rotationVector);
324 if ((m_scaleX != 1.0f) || (m_scaleY != 1.0f) || (m_scaleZ != 1.0f))
325 painter->modelViewMatrix().scale(m_scaleX, m_scaleY, m_scaleZ);
326
327 // Draw a box around the mesh, if selected.
328 if (m_selected)
329 drawSelectionBox(painter);
330
331 // Restore the modelview matrix.
332 painter->modelViewMatrix().pop();
333 }
334}
335
336/** Adds an atom of this molecule to the scene.
337 *
338 * @param _atom atom to add
339 */
340void GLMoleculeObject_molecule::atomInserted(QtObservedAtom::ptr _atom)
341{
342 const ObservedValue_Index_t atomid = _atom->getIndex();
343 LOG(3, "INFO: GLMoleculeObject_molecule: Received signal atomInserted for atom "
344 << _atom->getAtomIndex());
345
346 if (_atom) {
347 GLMoleculeObject_atom *atomObject =
348 new GLMoleculeObject_atom(
349 GLMoleculeObject::meshSphere,
350 this,
351 _atom);
352 ASSERT( atomObject != NULL,
353 "GLMoleculeObject_molecule::atomInserted - could not create atom object for "
354 +toString(_atom->getAtomIndex()));
355 AtomNodeMap::iterator iter = AtomsinSceneMap.find(atomid);
356 ASSERT(iter == AtomsinSceneMap.end(),
357 "GLMoleculeObject_molecule::atomInserted - same atom with id "
358 +toString(_atom->getAtomIndex())+" added again.");
359 AtomsinSceneMap.insert( make_pair(atomid, atomObject) );
360
361 qRegisterMetaType<atomId_t>("atomId_t");
362 qRegisterMetaType<GLMoleculeObject_bond::SideOfBond>("GLMoleculeObject_bond::SideOfBond");
363 connect (atomObject, SIGNAL(clicked(atomId_t)), this, SIGNAL(atomClicked(atomId_t)));
364 connect (atomObject, SIGNAL(changed()), this, SIGNAL(changed()));
365 connect (atomObject, SIGNAL(hoverChanged(GLMoleculeObject *)), this, SIGNAL(changed()));
366 connect (atomObject, SIGNAL(hoverChanged(GLMoleculeObject *)), this, SLOT(hoverChangedSignalled(GLMoleculeObject *)));
367
368 if (m_objectId == -1)
369 setObjectId(_atom->getAtomIndex());
370
371 emit changed();
372 emit changeOccured();
373 }
374}
375
376/** Removes an atom of this molecule from the scene.
377 *
378 * We just the id as the atom might have already been destroyed.
379 *
380 * @param _id id of atom to remove
381 */
382void GLMoleculeObject_molecule::atomRemoved(ObservedValue_Index_t _id)
383{
384 LOG(3, "INFO: GLMoleculeObject_molecule: Received signal atomRemoved for atom "+toString(_id)+".");
385 // bonds are removed by signal coming from ~bond
386
387 // remove atoms
388 AtomNodeMap::iterator iter = AtomsinSceneMap.find(_id);
389 ASSERT(iter != AtomsinSceneMap.end(),
390 "GLMoleculeObject_molecule::atomRemoved() - atom "+toString(_id)+" not on display.");
391 GLMoleculeObject_atom *atomObject = iter->second;
392 AtomsinSceneMap.erase(iter);
393 atomObject->disconnect();
394 delete atomObject;
395
396 emit changed();
397 emit changeOccured();
398
399 if (AtomsinSceneMap.empty())
400 emit moleculeEmptied(ObservedMolecule);
401}
402
403void GLMoleculeObject_molecule::hoverChangedSignalled(GLMoleculeObject *ob)
404{
405 // Find the atom, ob corresponds to.
406 hoverAtomId = -1;
407 GLMoleculeObject_atom *atomObject = dynamic_cast<GLMoleculeObject_atom *>(ob);
408 if (atomObject){
409 for (AtomNodeMap::iterator iter = AtomsinSceneMap.begin();iter != AtomsinSceneMap.end(); ++ iter){
410 if (iter->second == atomObject)
411 hoverAtomId = iter->second->objectId();
412 }
413
414 // Propagate signal.
415 emit hoverChanged(hoverAtomId);
416 } else {
417 // Find the atom, ob corresponds to.
418 GLMoleculeObject_molecule *moleculeObject = dynamic_cast<GLMoleculeObject_molecule *>(ob);
419 if (moleculeObject == this){
420 // Propagate signal.
421 emit hoverChanged(ObservedMolecule->getMolIndex(), 0);
422 }
423 }
424}
425
426/** Adds a bond to the scene.
427 *
428 * @param _bond bond to add
429 */
430void GLMoleculeObject_molecule::bondInserted(
431 QtObservedBond::ptr _bond)
432{
433 static const std::vector< GLMoleculeObject_bond::SideOfBond > bondsides =
434 boost::assign::list_of<GLMoleculeObject_bond::SideOfBond>
435 (GLMoleculeObject_bond::left)
436 (GLMoleculeObject_bond::right);
437 LOG(3, "INFO: GLWorldScene::bondInserted() - Adding bonds " << _bond->getBondIndex());
438 //LOG(4, "INFO: Currently present bonds " << BondsinSceneMap << ".");
439
440 const ObservedValue_Index_t bondid = _bond->getIndex();
441 const std::pair<BondNodeMap::iterator, BondNodeMap::iterator> iters =
442 BondsinSceneMap.equal_range(bondid);
443 if (iters.first == iters.second) {
444 for (size_t i=0;i<2;++i) {
445 GLMoleculeObject_bond * bondObject =
446 new GLMoleculeObject_bond(GLMoleculeObject::meshCylinder, this, _bond, bondsides[i]);
447 connect (bondObject, SIGNAL(changed()), this, SIGNAL(changed()));
448 BondsinSceneMap.insert( std::make_pair(bondid, bondObject) );
449 }
450 } else {
451 for (BondNodeMap::iterator iter = iters.first; iter != iters.second; ++iter) {
452 iter->second->resetPosition();
453 iter->second->resetWidth();
454 }
455 }
456 emit changed();
457 emit changeOccured();
458}
459
460/** Removes a bond from the scene.
461 *
462 * @param _bond bond to remove
463 */
464void GLMoleculeObject_molecule::bondRemoved(ObservedValue_Index_t _id)
465{
466 LOG(3, "INFO: GLWorldScene::bondRemoved() - Removing bond to id " << _id);
467 {
468 // left bond
469 const std::pair<BondNodeMap::iterator, BondNodeMap::iterator> iters =
470 BondsinSceneMap.equal_range(_id);
471 for (BondNodeMap::iterator iter = iters.first; iter != iters.second; ++iter) {
472 GLMoleculeObject_bond *bondObject = iter->second;
473 bondObject->disconnect();
474 delete bondObject; // is done by signal from bond itself
475 //LOG(4, "INFO: Still present bonds " << BondsinSceneMap << ".");
476 }
477 BondsinSceneMap.erase(_id);
478 }
479
480 emit changed();
481 emit changeOccured();
482}
483
484void GLMoleculeObject_molecule::setVisible(bool value)
485{
486 // first update the mesh if we are going to be visible now
487 if (value)
488 updateTesselationHull();
489 // then emit onward
490 GLMoleculeObject::setVisible(value);
491
492 emit changed();
493 emit changeOccured();
494}
495
496std::ostream &operator<<(std::ostream &ost, const GLMoleculeObject_molecule::BondIds &t)
497{
498 ost << t.first << "," << t.second;
499 return ost;
500}
501
502void GLMoleculeObject_molecule::wasClicked()
503{
504 LOG(4, "INFO: GLMoleculeObject_molecule: atom "
505 << ObservedMolecule->getMolIndex() << " has been clicked");
506 emit moleculeClicked(ObservedMolecule->getMolIndex());
507}
Note: See TracBrowser for help on using the repository browser.