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

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

FIX: GLMoleculeObject_molecule still contained hack to get upper bound on molecule's bounding box.

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