source: src/UIElements/Views/Qt4/Qt3D/GLWorldScene.cpp@ 163110

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 163110 was ce4126, checked in by Frederik Heber <heber@…>, 11 years ago

FIX: Added update mechanism to GLWorldScene when WorldTime changes.

  • bonds were not updated when WorldTime changed, atoms only change because each was subscribed to WorldTime.
  • Now, just GLWorldView is subscribed to WorldTime::TimeChanged, emitting TimeChanged and activating GLWorldScene::updated() signal.
  • GLWorldScene has access to private reset..() functions of GLMoleculeObject_atom and GLMoleculeObject_bond.
  • added GLWorldScene::update(), enhancing (also modified) ::init() function. It does not use molecules anymore, but directly the World's atoms. These are iterated over, checked whether already present and updated or added. Similarly with bonds. update() is activated on signal updated().
  • Property mode set to 100644
File size: 16.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 * GLWorldScene.cpp
26 *
27 * This is based on the Qt3D example "teaservice", specifically parts of teaservice.cpp.
28 *
29 * Created on: Aug 17, 2011
30 * Author: heber
31 */
32
33// include config.h
34#ifdef HAVE_CONFIG_H
35#include <config.h>
36#endif
37
38#include "GLWorldScene.hpp"
39#include <Qt3D/qglview.h>
40#include <Qt3D/qglbuilder.h>
41#include <Qt3D/qglscenenode.h>
42#include <Qt3D/qglsphere.h>
43#include <Qt3D/qglcylinder.h>
44
45#include "GLMoleculeObject.hpp"
46#include "GLMoleculeObject_atom.hpp"
47#include "GLMoleculeObject_bond.hpp"
48#include "GLMoleculeObject_molecule.hpp"
49#include "GLMoleculeObject_shape.hpp"
50
51#include "CodePatterns/MemDebug.hpp"
52
53#include "CodePatterns/Log.hpp"
54
55#include "Actions/SelectionAction/Atoms/AtomByIdAction.hpp"
56#include "Actions/SelectionAction/Atoms/NotAtomByIdAction.hpp"
57#include "Actions/SelectionAction/Molecules/MoleculeByIdAction.hpp"
58#include "Actions/SelectionAction/Molecules/NotMoleculeByIdAction.hpp"
59#include "Atom/atom.hpp"
60#include "Bond/bond.hpp"
61#include "Descriptors/AtomIdDescriptor.hpp"
62#include "Helpers/helpers.hpp"
63#include "Shapes/ShapeRegistry.hpp"
64#include "molecule.hpp"
65#include "World.hpp"
66
67#include <iostream>
68
69using namespace MoleCuilder;
70
71std::ostream &operator<<(std::ostream &ost, const GLWorldScene::BondIds &t)
72{
73 ost << t.first << "," << t.second;
74 return ost;
75}
76
77GLWorldScene::GLWorldScene(QObject *parent)
78 : QObject(parent),
79 hoverAtom(NULL)
80{
81 int sphereDetails[] = {5, 3, 2, 0};
82 int cylinderDetails[] = {16, 8, 6, 3};
83 for (int i=0;i<GLMoleculeObject::DETAILTYPES_MAX;i++){
84 QGLBuilder emptyBuilder;
85 meshEmpty[i] = emptyBuilder.finalizedSceneNode();
86 QGLBuilder sphereBuilder;
87 sphereBuilder << QGLSphere(2.0, sphereDetails[i]);
88 meshSphere[i] = sphereBuilder.finalizedSceneNode();
89 meshSphere[i]->setOption(QGLSceneNode::CullBoundingBox, true);
90 QGLBuilder cylinderBuilder;
91 cylinderBuilder << QGLCylinder(.25,.25,1.0,cylinderDetails[i]);
92 meshCylinder[i] = cylinderBuilder.finalizedSceneNode();
93 meshCylinder[i]->setOption(QGLSceneNode::CullBoundingBox, true);
94 }
95
96 connect(this, SIGNAL(updated()), this, SLOT(update()));
97
98 setSelectionMode(SelectAtom);
99
100 init();
101}
102
103GLWorldScene::~GLWorldScene()
104{
105 // remove all elements
106 GLMoleculeObject::cleanMaterialMap();
107}
108
109/** Initialise the WorldScene with molecules and atoms from World.
110 *
111 */
112void GLWorldScene::init()
113{
114 const std::vector<atom*> &atoms = World::getInstance().getAllAtoms();
115
116 if (atoms.size() > 0) {
117 for (std::vector<atom*>::const_iterator atomiter = atoms.begin();
118 atomiter != atoms.end();
119 atomiter++) {
120 // create atom objects in scene
121 atomInserted((*atomiter)->getId());
122
123 // create bond objects in scene
124 const BondList &bondlist = (*atomiter)->getListOfBonds();
125 for (BondList::const_iterator bonditer = bondlist.begin();
126 bonditer != bondlist.end();
127 ++bonditer) {
128 const bond::ptr _bond = *bonditer;
129 const GLMoleculeObject_bond::SideOfBond side = (_bond->leftatom == *atomiter) ?
130 GLMoleculeObject_bond::left : GLMoleculeObject_bond::right;
131 bondInserted(_bond, side);
132 }
133 }
134 }
135}
136
137/** Update the WorldScene with molecules and atoms from World.
138 *
139 * This function should be called after e.g. WorldTime::TimeChanged was
140 * received or after another molecule has been loaded.
141 *
142 */
143void GLWorldScene::update()
144{
145 const std::vector<atom*> &atoms = World::getInstance().getAllAtoms();
146
147 if (atoms.size() > 0) {
148 for (std::vector<atom*>::const_iterator atomiter = atoms.begin();
149 atomiter != atoms.end();
150 atomiter++) {
151 // check whether atom already exists
152 const atomId_t atomid = (*atomiter)->getId();
153 const bool atom_present = AtomsinSceneMap.count(atomid);
154 if (!atom_present)
155 atomInserted((*atomiter)->getId());
156 else
157 AtomsinSceneMap[atomid]->resetPosition();
158
159
160 // create bond objects in scene
161 const BondList &bondlist = (*atomiter)->getListOfBonds();
162 for (BondList::const_iterator bonditer = bondlist.begin();
163 bonditer != bondlist.end();
164 ++bonditer) {
165 const bond::ptr _bond = *bonditer;
166 const GLMoleculeObject_bond::SideOfBond side = (_bond->leftatom == *atomiter) ?
167 GLMoleculeObject_bond::left : GLMoleculeObject_bond::right;
168 bool bond_present = false;
169 const BondIds ids = getBondIds(_bond,side);
170 if (atom_present) {
171 // check whether bond is not present already
172 bond_present = BondsinSceneMap.count(ids);
173 }
174 if (!bond_present)
175 bondInserted(_bond, side);
176 else {
177 BondsinSceneMap[ids]->resetPosition();
178 BondsinSceneMap[ids]->resetWidth();
179 }
180 }
181 }
182 }
183}
184
185/** Adds an atom to the scene.
186 *
187 * @param _atom atom to add
188 */
189void GLWorldScene::atomInserted(const atomicNumber_t _id)
190{
191 LOG(3, "INFO: GLWorldScene: Received signal atomInserted for atom "+toString(_id)+".");
192 GLMoleculeObject_atom *atomObject = new GLMoleculeObject_atom(meshSphere, this, _id);
193 AtomNodeMap::iterator iter = AtomsinSceneMap.find(_id);
194 ASSERT(iter == AtomsinSceneMap.end(),
195 "GLWorldScene::atomAdded() - same atom with id "+toString(_id)+" added again.");
196 AtomsinSceneMap.insert( make_pair(_id, atomObject) );
197
198 qRegisterMetaType<atomId_t>("atomId_t");
199 qRegisterMetaType<bond::ptr>("bond::ptr");
200 qRegisterMetaType<GLMoleculeObject_bond::SideOfBond>("GLMoleculeObject_bond::SideOfBond");
201 connect (atomObject, SIGNAL(clicked(atomId_t)), this, SLOT(atomClicked(atomId_t)));
202 connect (atomObject, SIGNAL(changed()), this, SIGNAL(changed()));
203 connect (atomObject, SIGNAL(hoverChanged(GLMoleculeObject *)), this, SIGNAL(changed()));
204 connect (atomObject, SIGNAL(hoverChanged(GLMoleculeObject *)), this, SLOT(hoverChangedSignalled(GLMoleculeObject *)));
205 connect (atomObject, SIGNAL(selectionChanged()), this, SIGNAL(changed()));
206 connect (atomObject, SIGNAL(BondsInserted(const bond::ptr , const GLMoleculeObject_bond::SideOfBond)), this, SLOT(bondInserted(const bond::ptr , const GLMoleculeObject_bond::SideOfBond)));
207 connect (atomObject, SIGNAL(indexChanged(GLMoleculeObject_atom*, int, int)), this, SLOT(changeAtomId(GLMoleculeObject_atom*, int, int)));
208 //bondsChanged(_atom);
209 emit changeOccured();
210}
211
212/** Removes an atom from the scene.
213 *
214 * We just the id as the atom might have already been destroyed.
215 *
216 * @param _id id of atom to remove
217 */
218void GLWorldScene::atomRemoved(const atomicNumber_t _id)
219{
220 LOG(3, "INFO: GLWorldScene: Received signal atomRemoved for atom "+toString(_id)+".");
221 // bonds are removed by signal coming from ~bond
222 // remove atoms
223 AtomNodeMap::iterator iter = AtomsinSceneMap.find(_id);
224 ASSERT(iter != AtomsinSceneMap.end(),
225 "GLWorldScene::atomRemoved() - atom "+toString(_id)+" not on display.");
226 GLMoleculeObject_atom *atomObject = iter->second;
227 atomObject->disconnect();
228 AtomsinSceneMap.erase(iter);
229 delete atomObject;
230 emit changeOccured();
231}
232
233/** ....
234 *
235 */
236void GLWorldScene::worldSelectionChanged()
237{
238 LOG(3, "INFO: GLWorldScene: Received signal selectionChanged.");
239
240 const std::vector<molecule*> &molecules = World::getInstance().getAllMolecules();
241
242 if (molecules.size() > 0) {
243 for (std::vector<molecule*>::const_iterator Runner = molecules.begin();
244 Runner != molecules.end();
245 Runner++) {
246
247 MoleculeNodeMap::iterator iter = MoleculesinSceneMap.find((*Runner)->getId());
248 bool isSelected = World::getInstance().isSelected(*Runner);
249
250 // molecule selected but not in scene?
251 if (isSelected && (iter == MoleculesinSceneMap.end())){
252 // -> create new mesh
253 GLMoleculeObject_molecule *molObject = new GLMoleculeObject_molecule(meshEmpty, this, *Runner);
254 MoleculesinSceneMap.insert( make_pair((*Runner)->getId(), molObject) );
255 connect (molObject, SIGNAL(changed()), this, SIGNAL(changed()));
256 connect (molObject, SIGNAL(selectionChanged()), this, SIGNAL(changed()));
257 connect (molObject, SIGNAL(selectionChanged()), this, SIGNAL(changed()));
258 emit changed();
259 emit changeOccured();
260 }
261
262 // molecule not selected but in scene?
263 if (!isSelected && (iter != MoleculesinSceneMap.end())){
264 // -> remove from scene
265 moleculeRemoved(*Runner);
266 }
267
268 }
269 }
270}
271
272/** Removes a molecule from the scene.
273 *
274 * @param _molecule molecule to remove
275 */
276void GLWorldScene::moleculeRemoved(const molecule *_molecule)
277{
278 LOG(3, "INFO: GLWorldScene: Received signal moleculeRemoved for molecule "+toString(_molecule->getId())+".");
279 MoleculeNodeMap::iterator iter = MoleculesinSceneMap.find(_molecule->getId());
280
281 // only remove if the molecule is in the scene
282 // (= is selected)
283 if (iter != MoleculesinSceneMap.end()){
284 GLMoleculeObject_molecule *molObject = iter->second;
285 molObject->disconnect();
286 MoleculesinSceneMap.erase(iter);
287 delete molObject;
288 emit changed();
289 emit changeOccured();
290 }
291}
292
293/** Helper function to get bond ids in the correct order for BondNodeMap.
294 *
295 * \return pair of ids in correct order.
296 */
297GLWorldScene::BondIds GLWorldScene::getBondIds(
298 const bond::ptr _bond,
299 const enum GLMoleculeObject_bond::SideOfBond _side) const
300{
301 BondIds ids;
302 switch (_side) {
303 case GLMoleculeObject_bond::left:
304 ids = std::make_pair(_bond->leftatom->getId(), _bond->rightatom->getId());
305 break;
306 case GLMoleculeObject_bond::right:
307 ids = std::make_pair(_bond->rightatom->getId(), _bond->leftatom->getId());
308 break;
309 }
310 return ids;
311}
312
313/** Adds a bond to the scene.
314 *
315 * @param _bond bond to add
316 * @param side which side of the bond (left or right)
317 */
318void GLWorldScene::bondInserted(const bond::ptr _bond, const enum GLMoleculeObject_bond::SideOfBond _side)
319{
320 LOG(3, "INFO: GLWorldScene::bondInserted() - Adding bond "+toString(*_bond)+".");
321 //LOG(4, "INFO: Currently present bonds " << BondsinSceneMap << ".");
322
323 const BondIds ids = getBondIds(_bond, _side);
324 BondNodeMap::iterator iter = BondsinSceneMap.find(ids);
325 if (iter == BondsinSceneMap.end()) {
326 GLMoleculeObject_bond * bondObject =
327 new GLMoleculeObject_bond(meshCylinder, this, _bond, _side);
328 connect (
329 bondObject, SIGNAL(BondRemoved(const atomId_t, const atomId_t)),
330 this, SLOT(bondRemoved(const atomId_t, const atomId_t)));
331 connect (bondObject, SIGNAL(changed()), this, SIGNAL(changed()));
332 BondsinSceneMap.insert( make_pair(ids, bondObject) );
333 // BondIdsinSceneMap.insert( Leftids );
334 } else {
335 iter->second->resetPosition();
336 iter->second->resetWidth();
337 }
338 emit changeOccured();
339}
340
341/** Removes a bond from the scene.
342 *
343 * @param _bond bond to remove
344 */
345void GLWorldScene::bondRemoved(const atomId_t leftnr, const atomId_t rightnr)
346{
347 LOG(3, "INFO: GLWorldScene::bondRemoved() - Removing bond between "+toString(leftnr)+" and "+toString(rightnr)+".");
348 {
349 // left bond
350 const BondIds Leftids( make_pair(leftnr, rightnr) );
351 BondNodeMap::iterator leftiter = BondsinSceneMap.find( Leftids );
352 ASSERT(leftiter != BondsinSceneMap.end(),
353 "GLWorldScene::bondRemoved() - bond "+toString(leftnr)+"-"
354 +toString(rightnr)+" not on display.");
355 GLMoleculeObject_bond *bondObject = leftiter->second;
356 BondsinSceneMap.erase(leftiter);
357 delete bondObject; // is done by signal from bond itself
358 //LOG(4, "INFO: Still present bonds " << BondsinSceneMap << ".");
359 }
360
361 emit changeOccured();
362}
363
364/** Adds a shape to the scene.
365 *
366 * uses ShapeRegistry::lastChanged()
367 *
368 */
369void GLWorldScene::addShape()
370{
371 Shape &shape = *ShapeRegistry::getInstance().lastChanged();
372 GLMoleculeObject_shape *shapeObject = new GLMoleculeObject_shape(shape, this);
373 ShapeNodeMap::iterator iter = ShapesinSceneMap.find(shape.getName());
374 ASSERT(iter == ShapesinSceneMap.end(),
375 "GLWorldScene::addShape() - same shape "+shape.getName()+" added again.");
376 ShapesinSceneMap.insert( make_pair(shape.getName(), shapeObject) );
377}
378
379void GLWorldScene::removeShape()
380{
381 Shape &shape = *ShapeRegistry::getInstance().lastChanged();
382 ShapeNodeMap::iterator iter = ShapesinSceneMap.find(shape.getName());
383 ASSERT(iter != ShapesinSceneMap.end(),
384 "GLWorldScene::removeShape() - shape "+shape.getName()+" not in scene.");
385 ShapesinSceneMap.erase(iter);
386 delete(iter->second);
387}
388
389void GLWorldScene::updateSelectedShapes()
390{
391 foreach (QObject *obj, children()) {
392 GLMoleculeObject_shape *shapeobj = qobject_cast<GLMoleculeObject_shape *>(obj);
393 if (shapeobj){
394 shapeobj->enable(ShapeRegistry::getInstance().isSelected(shapeobj->getShape()));
395 }
396 }
397}
398
399void GLWorldScene::initialize(QGLView *view, QGLPainter *painter) const
400{
401 // Initialize all of the mesh objects that we have as children.
402 foreach (QObject *obj, children()) {
403 GLMoleculeObject *meshobj = qobject_cast<GLMoleculeObject *>(obj);
404 if (meshobj)
405 meshobj->initialize(view, painter);
406 }
407}
408
409void GLWorldScene::draw(QGLPainter *painter, const QVector4D &cameraPlane) const
410{
411 // Draw all of the mesh objects that we have as children.
412 foreach (QObject *obj, children()) {
413 GLMoleculeObject *meshobj = qobject_cast<GLMoleculeObject *>(obj);
414 if (meshobj)
415 meshobj->draw(painter, cameraPlane);
416 }
417}
418
419void GLWorldScene::atomClicked(atomId_t no)
420{
421 LOG(3, "INFO: GLWorldScene - atom " << no << " has been clicked.");
422 const atom *Walker = World::getInstance().getAtom(AtomById(no));
423 if (selectionMode == SelectAtom){
424 if (!World::getInstance().isSelected(Walker))
425 SelectionAtomById(std::vector<atomId_t>(1,no));
426 else
427 SelectionNotAtomById(std::vector<atomId_t>(1,no));
428 }else if (selectionMode == SelectMolecule){
429 const molecule *mol = Walker->getMolecule();
430 ASSERT(mol, "Atom without molecule has been clicked.");
431 if (!World::getInstance().isSelected(mol))
432 SelectionMoleculeById(mol->getId());
433 else
434 SelectionNotMoleculeById(mol->getId());
435 }
436 emit clicked(no);
437}
438
439void GLWorldScene::setSelectionMode(SelectionModeType mode)
440{
441 selectionMode = mode;
442 // TODO send update to toolbar
443}
444
445void GLWorldScene::setSelectionModeAtom()
446{
447 setSelectionMode(SelectAtom);
448}
449
450void GLWorldScene::setSelectionModeMolecule()
451{
452 setSelectionMode(SelectMolecule);
453}
454
455void GLWorldScene::hoverChangedSignalled(GLMoleculeObject *ob)
456{
457 // Find the atom, ob corresponds to.
458 hoverAtom = NULL;
459 GLMoleculeObject_atom *atomObject = dynamic_cast<GLMoleculeObject_atom *>(ob);
460 if (atomObject){
461 for (AtomNodeMap::iterator iter = AtomsinSceneMap.begin();iter != AtomsinSceneMap.end(); ++ iter){
462 if (iter->second == atomObject)
463 hoverAtom = World::getInstance().getAtom(AtomById(iter->first));
464 }
465 }
466
467 // Propagate signal.
468 emit hoverChanged(hoverAtom);
469}
470
471void GLWorldScene::changeAtomId(GLMoleculeObject_atom *ob, int oldId, int newId)
472{
473 LOG(3, "INFO: GLWorldScene - change atom id " << oldId << " to " << newId << ".");
474 // Remove from map.
475 AtomNodeMap::iterator iter = AtomsinSceneMap.find(oldId);
476 ASSERT(iter != AtomsinSceneMap.end(),
477 "GLWorldScene::objectIdChangedSignalled() - atom with id "+toString(oldId)+" not on display.");
478 GLMoleculeObject_atom *atomObject = iter->second;
479 AtomsinSceneMap.erase(iter);
480
481 // Reinsert with new id.
482 AtomsinSceneMap.insert( make_pair(newId, atomObject) );
483}
484
Note: See TracBrowser for help on using the repository browser.