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

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 2f7988 was 2f7988, checked in by Frederik Heber <heber@…>, 9 years ago

Moved and renamed QtInstanceInformationBoard -> QtObservedInstanceBoard.

  • Property mode set to 100644
File size: 30.7 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 "CodePatterns/MemDebug.hpp"
43
44#include <boost/assign.hpp>
45
46#include "CodePatterns/Assert.hpp"
47#include "CodePatterns/IteratorAdaptors.hpp"
48#include "CodePatterns/Log.hpp"
49#include "CodePatterns/Observer/Notification.hpp"
50#include "CodePatterns/Observer/ObserverLog.hpp"
51
52#include "Atom/atom.hpp"
53#include "molecule.hpp"
54#include "Descriptors/AtomIdDescriptor.hpp"
55#include "Descriptors/MoleculeIdDescriptor.hpp"
56#include "Element/element.hpp"
57#include "LinearAlgebra/Vector.hpp"
58#include "LinkedCell/PointCloudAdaptor.hpp"
59#include "LinkedCell/linkedcell.hpp"
60#include "Tesselation/tesselation.hpp"
61#include "Tesselation/BoundaryLineSet.hpp"
62#include "Tesselation/BoundaryTriangleSet.hpp"
63#include "Tesselation/CandidateForTesselation.hpp"
64#include "UIElements/Qt4/InstanceBoard/QtObservedInstanceBoard.hpp"
65#include "Atom/TesselPoint.hpp"
66#include "World.hpp"
67
68#include "ObservedValue_wCallback.hpp"
69#include "ObservedValue_UpdateAtoms.hpp"
70
71using namespace boost::assign;
72
73#include "GLMoleculeObject_atom.hpp"
74
75static Observable::channels_t getAllAtomicChangesChannels()
76{
77 Observable::channels_t channels;
78 channels += molecule::AtomInserted, molecule::AtomRemoved, molecule::AtomMoved;
79 return channels;
80}
81
82static Observable::channels_t getAllAtomicObservedChannels()
83{
84 Observable::channels_t channels;
85 channels += molecule::AtomInserted, molecule::AtomRemoved, molecule::AtomMoved;
86 return channels;
87}
88
89// static instances
90const Observable::channels_t GLMoleculeObject_molecule::HullChannels(getAllAtomicChangesChannels());
91const Observable::channels_t GLMoleculeObject_molecule::BoundingBoxChannels(1, molecule::BoundingBoxChanged);
92const Observable::channels_t GLMoleculeObject_molecule::IndexChannels(1, molecule::IndexChanged);
93const Observable::channels_t GLMoleculeObject_molecule::NameChannels(1, molecule::MoleculeNameChanged);
94
95static QGLSceneNode *createMoleculeMesh(const QGeometryData &_geo)
96{
97 // Build a mesh from the geometry.
98 QGLBuilder builder;
99 builder.addTriangles(_geo);
100 QGLSceneNode *mesh = builder.finalizedSceneNode();
101 return mesh;
102}
103
104GLMoleculeObject_molecule::GLMoleculeObject_molecule(
105 QObject *parent,
106 const moleculeId_t _molid,
107 QtObservedInstanceBoard * _board,
108 std::vector<boost::any> _ObservedValues) :
109 GLMoleculeObject((QGLSceneNode *)NULL, parent),
110 Observer(std::string("GLMoleculeObject_molecule")+toString(_molid)),
111 owner(NULL),
112 molref(getMolecule(_molid)),
113 /* We must not use boost::cref(this) as "this" has not been properly constructed and seemingly
114 * boost::cref tries to do some magic to grasp the inheritance hierarchy which fails because
115 * the class has not been fully constructed yet. "This" itself seems to be working fine.
116 */
117 ObservedValues(_ObservedValues),
118 subjectKilledCount(0),
119 TesselationHullUpdater(
120 boost::bind(&GLMoleculeObject_molecule::updateTesselationHull, this)
121 ),
122 TesselationHull(
123 molref,
124 TesselationHullUpdater,
125 "MoleculeTesselationHull_"+toString(_molid),
126 HullChannels),
127 hoverAtomId(-1),
128 AllsignedOnChannels(getAllAtomicObservedChannels().size()),
129 signedOnChannels(0),
130 board(_board)
131{
132 init(_molid);
133}
134
135GLMoleculeObject_molecule::GLMoleculeObject_molecule(
136 QGLSceneNode *mesh[],
137 QObject *parent,
138 const moleculeId_t _molid,
139 QtObservedInstanceBoard * _board,
140 std::vector<boost::any> _ObservedValues) :
141 GLMoleculeObject(mesh, parent),
142 Observer(std::string("GLMoleculeObject_molecule")+toString(_molid)),
143 owner(NULL),
144 molref(getMolecule(_molid)),
145 /* We must not use boost::cref(this) as "this" has not been properly constructed and seemingly
146 * boost::cref tries to do some magic to grasp the inheritance hierarchy which fails because
147 * the class has not been fully constructed yet. "This" itself seems to be working fine.
148 */
149 ObservedValues(_ObservedValues),
150 subjectKilledCount(0),
151 TesselationHullUpdater(
152 boost::bind(&GLMoleculeObject_molecule::updateTesselationHull, this)
153 ),
154 TesselationHull(
155 molref,
156 TesselationHullUpdater,
157 "MoleculeTesselationHull_"+toString(_molid),
158 HullChannels),
159 hoverAtomId(-1),
160 AllsignedOnChannels(getAllAtomicObservedChannels().size()),
161 signedOnChannels(0),
162 board(_board)
163{
164 init(_molid);
165}
166
167void GLMoleculeObject_molecule::init(const moleculeId_t _molid)
168{
169 setObjectId(_molid);
170 setMaterial(getMaterial(1));
171
172 m_selected = const_cast<const World &>(World::getInstance()).isMoleculeSelected(_molid);
173
174 // initially, atoms and bonds should be visible
175 m_visible = false;
176
177 activateObserver();
178
179 connect (this, SIGNAL(hoverChanged(GLMoleculeObject *)), this, SLOT(hoverChangedSignalled(GLMoleculeObject *)));
180 connect (this, SIGNAL(hoverChanged(GLMoleculeObject *)), this, SIGNAL(changed()));
181 connect (this, SIGNAL(TesselationHullChanged()), this, SLOT(resetTesselationHull()), Qt::QueuedConnection);
182 connect (this, SIGNAL(BoundingBoxChanged()), this, SLOT(resetBoundingBox()), Qt::QueuedConnection);
183 connect (this, SIGNAL(IdChanged()), this, SLOT(resetIndex()), Qt::QueuedConnection);
184 connect (this, SIGNAL(AtomInserted(const atomId_t)), this, SLOT(atomInserted(const atomId_t)), Qt::QueuedConnection);
185 connect (this, SIGNAL(AtomRemoved(const atomId_t)), this, SLOT(atomRemoved(const atomId_t)), Qt::QueuedConnection);
186 if (board != NULL) {
187 connect(board, SIGNAL(atomInserted(const atomId_t)),
188 this, SLOT(atomInserted(const atomId_t)));
189 connect(board, SIGNAL(atomRemoved(const atomId_t)),
190 this, SLOT(atomRemoved(const atomId_t)));
191 }
192
193 connect( this, SIGNAL(clicked()), this, SLOT(wasClicked()));
194}
195
196GLMoleculeObject_molecule::~GLMoleculeObject_molecule()
197{
198 deactivateObserver();
199 board->returnMoleculeObservedValues(getMolIndex(), ObservedValues);
200}
201
202void GLMoleculeObject_molecule::deactivateObserver()
203{
204 if (owner != NULL) {
205 Observable::channels_t channels = getAllAtomicObservedChannels();
206 for (Observable::channels_t::const_iterator iter = channels.begin();
207 iter != channels.end(); ++iter)
208 owner->signOff(this, *iter);
209 owner = NULL;
210 signedOnChannels = 0;
211 }
212}
213
214void GLMoleculeObject_molecule::activateObserver()
215{
216 // sign on as observer (obtain non-const instance before)
217 const molecule * const _molecule = getMolecule(getMolIndex());
218 if (_molecule != NULL) {
219 Observable::channels_t channels = getAllAtomicObservedChannels();
220 owner = static_cast<const Observable *>(_molecule);
221 for (Observable::channels_t::const_iterator iter = channels.begin();
222 iter != channels.end(); ++iter)
223 owner->signOn(this, *iter);
224 } else {
225 ELOG(1, "GLMoleculeObject_molecule() - added null object for not present mol id " << getMolIndex());
226 }
227
228}
229
230void GLMoleculeObject_molecule::addAtomBonds(
231 const bond::ptr &_bond,
232 const GLMoleculeObject_bond::SideOfBond _side
233 )
234{
235 bool bond_present = false;
236 const BondIds ids = getBondIds(_bond, _side);
237 // check whether bond is not present already
238 bond_present = BondsinSceneMap.count(ids);
239 if (!bond_present)
240 bondInserted(ids.first, ids.second, _side);
241 else {
242 BondsinSceneMap[ids]->resetPosition();
243 BondsinSceneMap[ids]->resetWidth();
244 }
245}
246
247QGeometryData GLMoleculeObject_molecule::updateTesselationHull() const
248{
249 QGeometryData geo;
250
251 const molecule * const molref = getMolecule(getMolIndex());
252 if (molref == NULL) {
253 ELOG(1, "Could not createMoleculeMesh, molecule with id " << getMolIndex() << " already gone.");
254 return geo;
255 }
256 double minradius = 2.; // TODO: set to maximum bond length value
257 LOG(3, "DEBUG: Molecule fits into sphere of radius " << minradius);
258 // check minimum bond radius in molecule
259 double minlength = std::numeric_limits<double>::max();
260 for (molecule::const_iterator iter = molref->begin();
261 iter != molref->end(); ++iter) {
262 const BondList &ListOfBonds = (*iter)->getListOfBonds();
263 for (BondList::const_iterator bonditer = ListOfBonds.begin();
264 bonditer != ListOfBonds.end(); ++bonditer) {
265 const double bond_distance = (*bonditer)->GetDistance();
266 minlength = std::min(bond_distance, minlength);
267 }
268 }
269 minradius = std::max( std::max(minradius, minlength), 1.);
270
271 // we need at least three points for tesselation
272 if (getPresentAtoms().size() >= 3) {
273 // Tesselate the points.
274 Tesselation T;
275 PointCloudAdaptor<molecule> cloud(const_cast<molecule *>(molref), getMolName());
276 T(cloud, minradius);
277
278 // Fill the points into a Qt geometry.
279 LinkedCell_deprecated LinkedList(cloud, minradius);
280 std::map<int, int> indices;
281 std::map<int, Vector> normals;
282 int index = 0;
283 for (PointMap::const_iterator piter = T.PointsOnBoundary.begin();
284 piter != T.PointsOnBoundary.end(); ++piter) {
285 const Vector &point = piter->second->getPosition();
286 // add data to the primitive
287 geo.appendVertex(QVector3D(point[0], point[1], point[2]));
288 Vector normalvector;
289 for (LineMap::const_iterator lineiter = piter->second->lines.begin();
290 lineiter != piter->second->lines.end(); ++lineiter)
291 for (TriangleMap::const_iterator triangleiter = lineiter->second->triangles.begin();
292 triangleiter != lineiter->second->triangles.end(); ++triangleiter)
293 normalvector +=
294 triangleiter->second->NormalVector;
295 normalvector.Normalize();
296 geo.appendNormal(QVector3D(normalvector[0], normalvector[1], normalvector[2]));
297 geo.appendColor(QColor(1, 1, 1, 1));
298 geo.appendTexCoord(QVector2D(0, 0));
299 indices.insert( std::make_pair( piter->second->getNr(), index++));
300 }
301
302 // Fill the tesselated triangles into the geometry.
303 for (TriangleMap::const_iterator runner = T.TrianglesOnBoundary.begin();
304 runner != T.TrianglesOnBoundary.end(); runner++) {
305 int v[3];
306 for (size_t i=0; i<3; ++i)
307 v[i] = runner->second->endpoints[i]->getNr();
308
309 // Sort the vertices so the triangle is clockwise (relative to the normal vector).
310 Vector cross = T.PointsOnBoundary[v[1]]->getPosition() - T.PointsOnBoundary[v[0]]->getPosition();
311 cross.VectorProduct(T.PointsOnBoundary[v[2]]->getPosition() - T.PointsOnBoundary[v[0]]->getPosition());
312 if (cross.ScalarProduct(runner->second->NormalVector) > 0)
313 geo.appendIndices(indices[v[0]], indices[v[1]], indices[v[2]]);
314 else
315 geo.appendIndices(indices[v[0]], indices[v[2]], indices[v[1]]);
316 }
317 }
318
319 return geo;
320}
321
322molecule::BoundingBoxInfo GLMoleculeObject_molecule::initBoundingBox()
323{
324 molecule::BoundingBoxInfo info;
325 info.position = zeroVec;
326 info.radius = 0.;
327 return info;
328}
329
330molecule::BoundingBoxInfo GLMoleculeObject_molecule::updateBoundingBox(
331 const boost::function<const moleculeId_t ()> &_getMolIndex)
332{
333 const molecule * const mol = getMolecule(_getMolIndex());
334 return mol->getBoundingBox();
335}
336
337moleculeId_t GLMoleculeObject_molecule::updateIndex()
338{
339 return const_cast<const World &>(World::getInstance()).lastChangedMolId();
340}
341
342std::string GLMoleculeObject_molecule::updateName(
343 const boost::function<const moleculeId_t ()> &_getMolIndex)
344{
345 const molecule * const mol = getMolecule(_getMolIndex());
346 return mol->getName();
347}
348
349void GLMoleculeObject_molecule::resetTesselationHull()
350{
351 // only when Observable still lives so far, we may check on Cacheable::isValid
352 if ((owner != NULL) && (!TesselationHull.isValid()))
353 updateMesh(createMoleculeMesh(*TesselationHull));
354}
355
356void GLMoleculeObject_molecule::resetBoundingBox()
357{
358 molecule::BoundingBoxInfo info = getBoundingBox();
359 setPosition(QVector3D(info.position[0], info.position[1], info.position[2]));
360 setScale(info.radius + 0.3); // getBoundingSphere() only sees atoms as points, so make the box a bit bigger
361}
362
363void GLMoleculeObject_molecule::resetIndex()
364{
365 const atomId_t newId = getMolIndex();
366 const size_t oldId = objectId();
367 ASSERT( newId != oldId,
368 "GLMoleculeObject_molecule::resetIndex() - index "+toString(newId)+" did not change.");
369 LOG(4, "INFO: GLMoleculeObject_molecule: new index is "+toString(newId)+".");
370 setObjectId(newId);
371
372 emit indexChanged(this, oldId, newId);
373}
374
375void GLMoleculeObject_molecule::resetName()
376{
377}
378
379void GLMoleculeObject_molecule::AtomSelected(const atomId_t _id)
380{
381 AtomNodeMap::iterator iter = AtomsinSceneMap.find(_id);
382 if (iter != AtomsinSceneMap.end())
383 QMetaObject::invokeMethod(iter->second, // pointer to a QObject
384 "Selected", // member name (no parameters here)
385 Qt::QueuedConnection); // connection type
386 else
387 ELOG(2, "GLMoleculeObject_molecule::AtomSelected() - atom "
388 << _id << " unknown to GLMoleculeObject_molecule.");
389}
390
391void GLMoleculeObject_molecule::AtomUnselected(const atomId_t _id)
392{
393 AtomNodeMap::iterator iter = AtomsinSceneMap.find(_id);
394 if (iter != AtomsinSceneMap.end())
395 QMetaObject::invokeMethod(iter->second, // pointer to a QObject
396 "Unselected", // member name (no parameters here)
397 Qt::QueuedConnection); // connection type
398 else ELOG(2, "GLMoleculeObject_molecule::AtomUnselected() - atom "
399 << _id << " unknown to GLMoleculeObject_molecule.");
400}
401
402void GLMoleculeObject_molecule::Selected()
403{
404 ASSERT( !m_selected,
405 "GLMoleculeObject_molecule::Selected() - 3D rep of molecule is already selected.");
406 m_selected = true;
407
408 emit changed();
409}
410
411void GLMoleculeObject_molecule::Unselected()
412{
413 ASSERT( m_selected,
414 "GLMoleculeObject_molecule::Unselected() - 3D rep of molecule is already unselected.");
415 m_selected = false;
416
417 emit changed();
418}
419
420void GLMoleculeObject_molecule::update(Observable *publisher)
421{
422 ASSERT(0,
423 "GLMoleculeObject_molecule::update() - general update from unexpected source.");
424}
425
426void GLMoleculeObject_molecule::subjectKilled(Observable *publisher)
427{
428 ++signedOnChannels;
429
430 if (signedOnChannels == AllsignedOnChannels) {
431 // remove owner: no more signOff needed
432 owner = NULL;
433
434 board->moleculecountsubjectKilled(getMolIndex());
435 }
436}
437
438void GLMoleculeObject_molecule::recieveNotification(Observable *publisher, Notification_ptr notification)
439{
440 const molecule * const _molecule = getMolecule(getMolIndex());
441 // when molecule is NULL we will soon get destroyed anyway
442 if (_molecule == NULL)
443 return;
444 if (publisher == dynamic_cast<const Observable*>(_molecule)){
445 // notification from atom
446#ifdef LOG_OBSERVER
447 observerLog().addMessage() << "++ Update of Observer "<< observerLog().getName(static_cast<Observer *>(this))
448 << " received notification from molecule " << getMolIndex() << " for channel "
449 << notification->getChannelNo() << ".";
450#endif
451 switch (notification->getChannelNo()) {
452 case molecule::AtomInserted:
453 case molecule::AtomRemoved:
454 case molecule::AtomMoved:
455 {
456 #ifdef LOG_OBSERVER
457 observerLog().addMessage() << "++ Observer " << observerLog().getName(static_cast<Observer *>(this)) << " received notification that atom "+toString(_id)+" has been inserted.";
458 #endif
459 emit TesselationHullChanged();
460 emit BoundingBoxChanged();
461 break;
462 }
463 case molecule::IndexChanged:
464 {
465 #ifdef LOG_OBSERVER
466 const atomId_t _id = _molecule->lastChangedAtomId();
467 observerLog().addMessage() << "++ Observer " << observerLog().getName(static_cast<Observer *>(this)) << " received notification that atom "+toString(_id)+"'s index has changed.";
468 #endif
469 emit IdChanged();
470 break;
471 }
472 default:
473 break;
474 }
475 }
476}
477
478void GLMoleculeObject_molecule::initialize(QGLView *view, QGLPainter *painter)
479{
480 // Initialize all of the mesh objects that we have as children.
481 if (m_visible) {
482 GLMoleculeObject::initialize(view, painter);
483 } else {
484 foreach (QObject *obj, children()) {
485 GLMoleculeObject *meshobj = qobject_cast<GLMoleculeObject *>(obj);
486 if (meshobj)
487 meshobj->initialize(view, painter);
488 }
489 }
490}
491
492void GLMoleculeObject_molecule::draw(QGLPainter *painter, const QVector4D &cameraPlane)
493{
494 // draw either molecule's mesh or all atoms and bonds
495 if (m_visible) {
496 resetTesselationHull();
497
498 painter->modelViewMatrix().push();
499
500 // Apply the material and effect to the painter.
501 QGLMaterial *material;
502 if (m_hovering)
503 material = m_hoverMaterial;
504 else if (m_selected)
505 material = m_selectionMaterial;
506 else
507 material = m_material;
508
509 ASSERT(material, "GLMoleculeObject::draw: chosen material is NULL");
510
511 painter->setColor(material->diffuseColor());
512 painter->setFaceMaterial(QGL::AllFaces, material);
513 if (m_effect)
514 painter->setUserEffect(m_effect);
515 else
516 painter->setStandardEffect(QGL::LitMaterial);
517
518 // Mark the object for object picking purposes.
519 int prevObjectId = painter->objectPickId();
520 if (m_objectId != -1)
521 painter->setObjectPickId(m_objectId);
522
523 m_mesh[0]->draw(painter);
524
525 // Turn off the user effect, if present.
526 if (m_effect)
527 painter->setStandardEffect(QGL::LitMaterial);
528
529 // Revert to the previous object identifier.
530 painter->setObjectPickId(prevObjectId);
531
532 // Restore the modelview matrix.
533 painter->modelViewMatrix().pop();
534
535 // GLMoleculeObject::draw(painter, cameraPlane);
536 } else {
537 // Draw all of the mesh objects that we have as children.
538 foreach (QObject *obj, children()) {
539 GLMoleculeObject *meshobj = qobject_cast<GLMoleculeObject *>(obj);
540 if (meshobj)
541 meshobj->draw(painter, cameraPlane);
542 }
543
544 // update bounding box prior to selection
545 resetBoundingBox();
546
547 painter->modelViewMatrix().push();
548 painter->modelViewMatrix().translate(m_position);
549 if (m_rotationAngle != 0.0f)
550 painter->modelViewMatrix().rotate(m_rotationAngle, m_rotationVector);
551 if ((m_scaleX != 1.0f) || (m_scaleY != 1.0f) || (m_scaleZ != 1.0f))
552 painter->modelViewMatrix().scale(m_scaleX, m_scaleY, m_scaleZ);
553
554 // Draw a box around the mesh, if selected.
555 if (m_selected)
556 drawSelectionBox(painter);
557
558 // Restore the modelview matrix.
559 painter->modelViewMatrix().pop();
560 }
561}
562
563/** Adds an atom of this molecule to the scene.
564 *
565 * @param _atom atom to add
566 */
567void GLMoleculeObject_molecule::atomInserted(const atomId_t _id)
568{
569 LOG(3, "INFO: GLMoleculeObject_molecule: Received signal atomInserted for atom "+toString(_id)+".");
570
571 GLMoleculeObject_atom *atomObject =
572 new GLMoleculeObject_atom(
573 GLMoleculeObject::meshSphere,
574 this,
575 _id,
576 board,
577 board->getAtomObservedValues(_id));
578 ASSERT( atomObject != NULL,
579 "GLMoleculeObject_molecule::atomInserted - could not create atom object for "+toString(_id));
580 AtomNodeMap::iterator iter = AtomsinSceneMap.find(_id);
581 ASSERT(iter == AtomsinSceneMap.end(),
582 "GLMoleculeObject_molecule::atomInserted - same atom with id "+toString(_id)+" added again.");
583 AtomsinSceneMap.insert( make_pair(_id, atomObject) );
584
585 qRegisterMetaType<atomId_t>("atomId_t");
586 qRegisterMetaType<bond::ptr>("bond::ptr");
587 qRegisterMetaType<GLMoleculeObject_bond::SideOfBond>("GLMoleculeObject_bond::SideOfBond");
588 connect (atomObject, SIGNAL(clicked(atomId_t)), this, SIGNAL(atomClicked(atomId_t)));
589 connect (atomObject, SIGNAL(changed()), this, SIGNAL(changed()));
590 connect (atomObject, SIGNAL(hoverChanged(GLMoleculeObject *)), this, SIGNAL(changed()));
591 connect (atomObject, SIGNAL(hoverChanged(GLMoleculeObject *)), this, SLOT(hoverChangedSignalled(GLMoleculeObject *)));
592// connect (atomObject, SIGNAL(bondsChanged()), this, SLOT(bondInserted(const atomId_t, const atomId_t, const GLMoleculeObject_bond::SideOfBond)));
593 connect (atomObject, SIGNAL(BondsAdded(const atomId_t, const atomId_t, const GLMoleculeObject_bond::SideOfBond)), this, SLOT(bondInserted(const atomId_t, const atomId_t, const GLMoleculeObject_bond::SideOfBond)));
594 connect (atomObject, SIGNAL(BondsRemoved(const atomId_t, const atomId_t)), this, SLOT(bondRemoved(const atomId_t, const atomId_t)));
595 connect (atomObject, SIGNAL(indexChanged(GLMoleculeObject_atom*, const atomId_t, const atomId_t)), this, SLOT(changeAtomId(GLMoleculeObject_atom*, const atomId_t, const atomId_t)));
596
597 if (m_objectId == -1)
598 setObjectId(_id);
599
600 emit changed();
601 emit changeOccured();
602}
603
604/** Removes an atom of this molecule from the scene.
605 *
606 * We just the id as the atom might have already been destroyed.
607 *
608 * @param _id id of atom to remove
609 */
610void GLMoleculeObject_molecule::atomRemoved(const atomId_t _id)
611{
612 LOG(3, "INFO: GLMoleculeObject_molecule: Received signal atomRemoved for atom "+toString(_id)+".");
613 // bonds are removed by signal coming from ~bond
614
615 if ((unsigned int)m_objectId == _id)
616 setObjectId(-1);
617
618 // remove atoms
619 AtomNodeMap::iterator iter = AtomsinSceneMap.find(_id);
620 ASSERT(iter != AtomsinSceneMap.end(),
621 "GLMoleculeObject_molecule::atomRemoved() - atom "+toString(_id)+" not on display.");
622 GLMoleculeObject_atom *atomObject = iter->second;
623 AtomsinSceneMap.erase(iter);
624 atomObject->disconnect();
625 delete atomObject;
626
627 emit changed();
628 emit changeOccured();
629}
630
631void GLMoleculeObject_molecule::hoverChangedSignalled(GLMoleculeObject *ob)
632{
633 // Find the atom, ob corresponds to.
634 hoverAtomId = -1;
635 GLMoleculeObject_atom *atomObject = dynamic_cast<GLMoleculeObject_atom *>(ob);
636 if (atomObject){
637 for (AtomNodeMap::iterator iter = AtomsinSceneMap.begin();iter != AtomsinSceneMap.end(); ++ iter){
638 if (iter->second == atomObject)
639 hoverAtomId = iter->first;
640 }
641
642 // Propagate signal.
643 emit hoverChanged(hoverAtomId);
644 } else {
645 // Find the atom, ob corresponds to.
646 GLMoleculeObject_molecule *moleculeObject = dynamic_cast<GLMoleculeObject_molecule *>(ob);
647 if (moleculeObject == this){
648 // Propagate signal.
649 emit hoverChanged(getMolIndex(), 0);
650 }
651 }
652}
653
654
655/** Helper function to get bond ids in the correct order for BondNodeMap.
656 *
657 * \return pair of ids in correct order.
658 */
659GLMoleculeObject_molecule::BondIds GLMoleculeObject_molecule::getBondIds(
660 const bond::ptr _bond,
661 const enum GLMoleculeObject_bond::SideOfBond _side)
662{
663 BondIds ids;
664 switch (_side) {
665 case GLMoleculeObject_bond::left:
666 ids = std::make_pair(_bond->leftatom->getId(), _bond->rightatom->getId());
667 break;
668 case GLMoleculeObject_bond::right:
669 ids = std::make_pair(_bond->rightatom->getId(), _bond->leftatom->getId());
670 break;
671 }
672 return ids;
673}
674
675/** Adds a bond to the scene.
676 *
677 * @param _bond bond to add
678 * @param side which side of the bond (left or right)
679 */
680void GLMoleculeObject_molecule::bondInserted(
681 const atomId_t _left, const atomId_t _right,
682 const enum GLMoleculeObject_bond::SideOfBond _side)
683{
684 LOG(3, "INFO: GLWorldScene::bondInserted() - Adding bond "+toString(_left)
685 +toString(_right)+".");
686 //LOG(4, "INFO: Currently present bonds " << BondsinSceneMap << ".");
687
688 const BondIds ids( std::make_pair(_left, _right) );
689 BondNodeMap::iterator iter = BondsinSceneMap.find(ids);
690 if (iter == BondsinSceneMap.end()) {
691 GLMoleculeObject_bond * bondObject =
692 new GLMoleculeObject_bond(GLMoleculeObject::meshCylinder, this, ids, _side);
693 connect (
694 bondObject, SIGNAL(BondRemoved(const atomId_t, const atomId_t)),
695 this, SLOT(bondRemoved(const atomId_t, const atomId_t)));
696 connect (bondObject, SIGNAL(changed()), this, SIGNAL(changed()));
697 BondsinSceneMap.insert( make_pair(ids, bondObject) );
698 // BondIdsinSceneMap.insert( Leftids );
699 } else {
700 iter->second->resetPosition();
701 iter->second->resetWidth();
702 }
703 emit changed();
704 emit changeOccured();
705}
706
707/** Removes a bond from the scene.
708 *
709 * @param _bond bond to remove
710 */
711void GLMoleculeObject_molecule::bondRemoved(const atomId_t leftnr, const atomId_t rightnr)
712{
713 LOG(3, "INFO: GLWorldScene::bondRemoved() - Removing bond between "+toString(leftnr)+" and "+toString(rightnr)+".");
714 {
715 // left bond
716 const BondIds Leftids( make_pair(leftnr, rightnr) );
717 BondNodeMap::iterator leftiter = BondsinSceneMap.find( Leftids );
718 ASSERT(leftiter != BondsinSceneMap.end(),
719 "GLWorldScene::bondRemoved() - bond "+toString(leftnr)+"-"
720 +toString(rightnr)+" not on display.");
721 GLMoleculeObject_bond *bondObject = leftiter->second;
722 bondObject->disconnect();
723 BondsinSceneMap.erase(leftiter);
724 delete bondObject; // is done by signal from bond itself
725 //LOG(4, "INFO: Still present bonds " << BondsinSceneMap << ".");
726 }
727
728 emit changed();
729 emit changeOccured();
730}
731
732void GLMoleculeObject_molecule::setVisible(bool value)
733{
734 // first update the mesh if we are going to be visible now
735 if (value)
736 updateTesselationHull();
737 // then emit onward
738 GLMoleculeObject::setVisible(value);
739
740 emit changed();
741 emit changeOccured();
742}
743
744std::ostream &operator<<(std::ostream &ost, const GLMoleculeObject_molecule::BondIds &t)
745{
746 ost << t.first << "," << t.second;
747 return ost;
748}
749
750void GLMoleculeObject_molecule::wasClicked()
751{
752 LOG(4, "INFO: GLMoleculeObject_molecule: atom " << getMolIndex() << " has been clicked");
753 emit moleculeClicked(getMolIndex());
754}
755
756void GLMoleculeObject_molecule::changeAtomId(
757 GLMoleculeObject_atom *ob,
758 const atomId_t oldId,
759 const atomId_t newId)
760{
761 LOG(3, "INFO: GLMoleculeObject_molecule - change atom id " << oldId << " to " << newId << ".");
762
763 // Remove from map.
764 AtomNodeMap::iterator iter = AtomsinSceneMap.find(oldId);
765 ASSERT(iter != AtomsinSceneMap.end(),
766 "GLMoleculeObject_molecule::changeAtomId() - atom with old id "+toString(oldId)+" not on display.");
767 ASSERT(iter->second == ob,
768 "GLMoleculeObject_molecule::changeAtomId() - atom with id "
769 +toString(oldId)+" does not match with object in AtomsinSceneMap.");
770 AtomsinSceneMap.erase(iter);
771
772 // Reinsert with new id.
773 {
774 AtomNodeMap::iterator iter = AtomsinSceneMap.find(newId);
775 ASSERT(iter == AtomsinSceneMap.end(),
776 "GLMoleculeObject_molecule::changeAtomId() - atom with new id "+toString(newId)+" already known.");
777 }
778 AtomsinSceneMap.insert( make_pair(newId, ob) );
779}
780
781const molecule * const GLMoleculeObject_molecule::getMolecule(const moleculeId_t _id)
782{
783 const molecule * const mol = const_cast<const World &>(World::getInstance()).
784 getMolecule(MoleculeById(_id));
785 return mol;
786}
787
788void GLMoleculeObject_molecule::initObservedValues(
789 std::vector<boost::any> &_ObservedValues,
790 const moleculeId_t _molid,
791 const molecule * const _molref,
792 const boost::function<void(const moleculeId_t)> &_subjectKilled)
793{
794 /* This is an old note from when the code was still part of cstor's initializer body.
795 * TODO: Probably does not apply anymore but has not yet been tested.
796 *
797 * We must not use boost::cref(this) as "this" has not been properly constructed and seemingly
798 * boost::cref tries to do some magic to grasp the inheritance hierarchy which fails because
799 * the class has not been fully constructed yet. "This" itself seems to be working fine.
800 */
801
802 ASSERT( _ObservedValues.size() == MAX_ObservedTypes,
803 "GLMoleculeObject_molecule::initObservedValues() - given ObservedValues has not correct size.");
804
805 // fill ObservedValues: index first
806 const boost::function<moleculeId_t ()> MolIndexUpdater(
807 boost::bind(&GLMoleculeObject_molecule::updateIndex));
808
809 ObservedValue_wCallback<moleculeId_t> * const IndexObservable =
810 new ObservedValue_wCallback<moleculeId_t>(
811 _molref,
812 MolIndexUpdater,
813 "MoleculeIndex_"+toString(_molid),
814 _molid,
815 IndexChannels,
816 _subjectKilled);
817 _ObservedValues[MolIndex] = IndexObservable;
818
819 const boost::function<const moleculeId_t ()> MolIndexGetter =
820 boost::bind(&ObservedValue_wCallback<moleculeId_t>::get,
821 IndexObservable);
822
823 // fill ObservedValues: then all the other that need index
824 const boost::function<std::string ()> MolNameUpdater(
825 boost::bind(&GLMoleculeObject_molecule::updateName, MolIndexGetter));
826 const boost::function<molecule::BoundingBoxInfo ()> BoundingBoxUpdater(
827 boost::bind(&GLMoleculeObject_molecule::updateBoundingBox, MolIndexGetter));
828
829 _ObservedValues[MolName] = new ObservedValue_wCallback<std::string, moleculeId_t>(
830 _molref,
831 MolNameUpdater,
832 "MoleculeName_"+toString(_molid),
833 MolNameUpdater(),
834 NameChannels,
835 _subjectKilled,
836 MolIndexGetter);
837 _ObservedValues[BoundingBox] = new ObservedValue_wCallback<molecule::BoundingBoxInfo, moleculeId_t>(
838 _molref,
839 BoundingBoxUpdater,
840 "MoleculeBoundingBox_"+toString(_molid),
841 initBoundingBox(),
842 BoundingBoxChannels,
843 _subjectKilled,
844 MolIndexGetter);
845}
846
847void GLMoleculeObject_molecule::destroyObservedValues(
848 std::vector<boost::any> &_ObservedValues)
849{
850 delete boost::any_cast<ObservedValue_wCallback<moleculeId_t> *>(_ObservedValues[MolIndex]);
851 delete boost::any_cast<ObservedValue_wCallback<std::string, moleculeId_t> *>(_ObservedValues[MolName]);
852 delete boost::any_cast<ObservedValue_wCallback<molecule::BoundingBoxInfo, moleculeId_t> *>(_ObservedValues[BoundingBox]);
853 _ObservedValues.clear();
854}
855
856moleculeId_t GLMoleculeObject_molecule::getMolIndex() const
857{
858 return boost::any_cast<ObservedValue_wCallback<moleculeId_t> *>(ObservedValues[MolIndex])->get();
859}
860
861std::string GLMoleculeObject_molecule::getMolName() const
862{
863 return boost::any_cast<ObservedValue_wCallback<std::string, moleculeId_t> *>(ObservedValues[MolName])->get();
864}
865
866molecule::BoundingBoxInfo GLMoleculeObject_molecule::getBoundingBox() const
867{
868 return boost::any_cast<ObservedValue_wCallback<molecule::BoundingBoxInfo, moleculeId_t> *>(ObservedValues[BoundingBox])->get();
869}
870
871GLMoleculeObject_molecule::atoms_t GLMoleculeObject_molecule::getPresentAtoms() const
872{
873 atoms_t returnAtomIds;
874 returnAtomIds.insert(
875 MapKeyConstIterator<AtomNodeMap::const_iterator>(const_cast<const AtomNodeMap &>(AtomsinSceneMap).begin()),
876 MapKeyConstIterator<AtomNodeMap::const_iterator>(const_cast<const AtomNodeMap &>(AtomsinSceneMap).end()));
877 return returnAtomIds;
878}
Note: See TracBrowser for help on using the repository browser.