source: src/UIElements/Views/Qt4/Qt3D/GLWorldView.cpp@ 9c259e

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

FIX: GLWorldScene/View capture all missed signals for each GLMoleculeObject_molecule.

  • Taking note of subscribed molecules to sign Off on GLWorldView's destruct.
  • GLWorldView::recieveNotification() is checking for whether molecule actually exists still.
  • Property mode set to 100644
File size: 29.4 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 * GLWorldView.cpp
26 *
27 * Created on: Aug 1, 2010
28 * Author: heber
29 */
30
31// include config.h
32#ifdef HAVE_CONFIG_H
33#include <config.h>
34#endif
35
36#include "GLWorldView.hpp"
37
38#include <Qt/qevent.h>
39#include <Qt/qaction.h>
40#include <QtGui/QMenu>
41#include <QtGui/QToolBar>
42#include <QtGui/QToolButton>
43#include <Qt/qtimer.h>
44#include <Qt/qsettings.h>
45#include <Qt3D/qglbuilder.h>
46#include <Qt3D/qglscenenode.h>
47#include <Qt3D/qglsphere.h>
48#include <Qt3D/qglcylinder.h>
49#include <Qt3D/qglcube.h>
50
51#include "GLWorldScene.hpp"
52
53#include "CodePatterns/MemDebug.hpp"
54
55#include "Atom/AtomObserver.hpp"
56#include "Atom/atom_observable.hpp"
57#include "Box.hpp"
58#include "CodePatterns/Log.hpp"
59#include "CodePatterns/Observer/Notification.hpp"
60#include "CodePatterns/Observer/ObserverLog.hpp"
61#include "Descriptors/MoleculeIdDescriptor.hpp"
62#include "molecule.hpp"
63#include "Shapes/ShapeRegistry.hpp"
64#include "World.hpp"
65#include "WorldTime.hpp"
66
67GLWorldView::GLWorldView(QWidget *parent)
68 : QGLView(parent), Observer("GLWorldView"), worldscene(NULL), changesPresent(false), needsRedraw(false)
69{
70 worldscene = new GLWorldScene(this);
71
72 setOption(QGLView::ObjectPicking, true);
73 setOption(QGLView::CameraNavigation, false);
74 setFocusPolicy(Qt::StrongFocus);
75 setCameraControlMode(Rotate);
76 defaultEyeSeparation = 4.0;
77
78 createDomainBox();
79 createDreiBein();
80 //changeMaterials(false);
81
82 qRegisterMetaType<atomId_t>("atomId_t");
83 qRegisterMetaType<moleculeId_t>("moleculeId_t");
84
85 connect(this, SIGNAL(ShapeAdded()), worldscene, SLOT(addShape()));
86 connect(this, SIGNAL(ShapeRemoved()), worldscene, SLOT(removeShape()));
87 connect(this, SIGNAL(TimeChanged()), worldscene, SIGNAL(updated()));
88 connect(worldscene, SIGNAL(changeOccured()), this, SLOT(changeSignalled()));
89 connect(worldscene, SIGNAL(changed()), this, SIGNAL(changed()));
90 connect(worldscene, SIGNAL(hoverChanged(const atomId_t)), this, SLOT(sceneHoverSignalled(const atomId_t)));
91 connect(worldscene, SIGNAL(hoverChanged(const moleculeId_t, int)), this, SLOT(sceneHoverSignalled(const moleculeId_t, int)));
92 connect(this, SIGNAL(worldSelectionChanged()), worldscene, SLOT(worldSelectionChanged()));
93 connect(this, SIGNAL(atomRemoved(const moleculeId_t, const atomId_t)), worldscene, SLOT(atomRemoved(const moleculeId_t, const atomId_t)), Qt::DirectConnection);
94 connect(this, SIGNAL(atomInserted(const moleculeId_t, const atomId_t)), worldscene, SLOT(atomInserted(const moleculeId_t, const atomId_t)), Qt::DirectConnection);
95 connect(this, SIGNAL(moleculeRemoved(const moleculeId_t)), worldscene, SLOT(moleculeRemoved(const moleculeId_t)), Qt::DirectConnection);
96 connect(this, SIGNAL(moleculeInserted(const moleculeId_t)), worldscene, SLOT(moleculeInserted(const moleculeId_t)), Qt::DirectConnection);
97 //connect(this, SIGNAL(changed()), this, SLOT(updateGL()));
98 connect(this, SIGNAL(changed()), this, SLOT(sceneChangeSignalled()));
99 connect(this, SIGNAL(moleculesVisibilityChanged(const moleculeId_t,bool)), worldscene, SLOT(moleculesVisibilityChanged(const moleculeId_t,bool)));
100
101 // sign on to changes in the world
102 World::getInstance().signOn(this);
103 World::getInstance().signOn(this, World::MoleculeInserted);
104 World::getInstance().signOn(this, World::MoleculeRemoved);
105 World::getInstance().signOn(this, World::SelectionChanged);
106 WorldTime::getInstance().signOn(this, WorldTime::TimeChanged);
107 AtomObserver::getInstance().signOn(this, AtomObservable::PositionChanged);
108
109 ShapeRegistry::getInstance().signOn(this);
110 ShapeRegistry::getInstance().signOn(this, ShapeRegistry::ShapeInserted);
111 ShapeRegistry::getInstance().signOn(this, ShapeRegistry::ShapeRemoved);
112 ShapeRegistry::getInstance().signOn(this, ShapeRegistry::SelectionChanged);
113
114 redrawTimer = new QTimer(this);
115}
116
117GLWorldView::~GLWorldView()
118{
119 // remove me from all observed molecules
120 for (ObservedMolecules_t::iterator iter = ObservedMolecules.begin();
121 !ObservedMolecules.empty();
122 iter = ObservedMolecules.begin())
123 signOffFromMolecule(*iter);
124
125 QSettings settings;
126 settings.beginGroup("WorldView");
127 settings.setValue("domainBoxEnabled", (meshDomainBox->options() & QGLSceneNode::HideNode) == 0);
128 settings.setValue("dreiBeinEnabled", (meshDreiBein->options() & QGLSceneNode::HideNode) == 0);
129 settings.endGroup();
130
131
132 World::getInstance().signOff(this);
133 World::getInstance().signOff(this, World::AtomInserted);
134 World::getInstance().signOff(this, World::AtomRemoved);
135 World::getInstance().signOff(this, World::MoleculeInserted);
136 World::getInstance().signOff(this, World::MoleculeRemoved);
137 World::getInstance().signOff(this, World::SelectionChanged);
138 WorldTime::getInstance().signOff(this, WorldTime::TimeChanged);
139 AtomObserver::getInstance().signOff(this, AtomObservable::PositionChanged);
140 ShapeRegistry::getInstance().signOff(this);
141 ShapeRegistry::getInstance().signOff(this, ShapeRegistry::ShapeInserted);
142 ShapeRegistry::getInstance().signOff(this, ShapeRegistry::ShapeRemoved);
143 ShapeRegistry::getInstance().signOff(this, ShapeRegistry::SelectionChanged);
144 delete worldscene;
145
146 delete(domainBoxMaterial);
147 for (int i=0;i<3;i++)
148 delete(dreiBeinMaterial[i]);
149}
150
151
152/**
153 * Add some widget specific actions to the toolbar:
154 * - camera rotation/translation mode
155 * - camera fit to domain
156 */
157void GLWorldView::addToolBarActions(QToolBar *toolbar)
158{
159 // camera control mode
160 toolbar->addSeparator();
161 QAction *transAction = new QAction(QIcon::fromTheme("forward"), tr("camera translation mode"), this);
162 connect(transAction, SIGNAL(triggered()), this, SLOT(setCameraControlModeTranslation()));
163 toolbar->addAction(transAction);
164 QAction *rotAction = new QAction(QIcon::fromTheme("object-rotate-left"), tr("camera rotation mode"), this);
165 connect(rotAction, SIGNAL(triggered()), this, SLOT(setCameraControlModeRotation()));
166 toolbar->addAction(rotAction);
167 QAction *fitAction = new QAction(QIcon::fromTheme("zoom-best-fit"), tr("camera fit to domain"), this);
168 connect(fitAction, SIGNAL(triggered()), this, SLOT(fitCameraToDomain()));
169 toolbar->addAction(fitAction);
170
171 // stereo mode
172 QToolButton *stereoButton = new QToolButton(toolbar);
173 QMenu *stereoMenu = new QMenu();
174 QAction *stereoDisableAction = new QAction(QIcon::fromTheme("zoom-best-fit"), tr("disable"), this);
175 connect(stereoDisableAction, SIGNAL(triggered()), this, SLOT(setCameraStereoModeDisable()));
176 stereoMenu->addAction(stereoDisableAction);
177 QAction *stereoHardwareAction = new QAction(QIcon::fromTheme("zoom-best-fit"), tr("hardware"), this);
178 connect(stereoHardwareAction, SIGNAL(triggered()), this, SLOT(setCameraStereoModeHardware()));
179 stereoMenu->addAction(stereoHardwareAction);
180 QAction *stereoLeftRightAction = new QAction(QIcon::fromTheme("zoom-best-fit"), tr("left right"), this);
181 connect(stereoLeftRightAction, SIGNAL(triggered()), this, SLOT(setCameraStereoModeLeftRight()));
182 stereoMenu->addAction(stereoLeftRightAction);
183 QAction *stereoRightLeftAction = new QAction(QIcon::fromTheme("zoom-best-fit"), tr("right left"), this);
184 connect(stereoRightLeftAction, SIGNAL(triggered()), this, SLOT(setCameraStereoModeRightLeft()));
185 stereoMenu->addAction(stereoRightLeftAction);
186 QAction *stereoTopBottomAction = new QAction(QIcon::fromTheme("zoom-best-fit"), tr("top bottom"), this);
187 connect(stereoTopBottomAction, SIGNAL(triggered()), this, SLOT(setCameraStereoModeTopBottom()));
188 stereoMenu->addAction(stereoTopBottomAction);
189 QAction *stereoBottomTopAction = new QAction(QIcon::fromTheme("zoom-best-fit"), tr("bottom top"), this);
190 connect(stereoBottomTopAction, SIGNAL(triggered()), this, SLOT(setCameraStereoModeBottomTop()));
191 stereoMenu->addAction(stereoBottomTopAction);
192 QAction *stereoAnaglyphAction = new QAction(QIcon::fromTheme("zoom-best-fit"), tr("anaglyph"), this);
193 connect(stereoAnaglyphAction, SIGNAL(triggered()), this, SLOT(setCameraStereoModeAnaglyph()));
194 stereoMenu->addAction(stereoAnaglyphAction);
195 stereoButton->setMenu(stereoMenu);
196 stereoButton->setIcon(QIcon(QPixmap(":/icon_view_stereo.png")));
197 stereoButton->setPopupMode(QToolButton::InstantPopup);
198 toolbar->addWidget(stereoButton);
199
200 // selection mode
201 toolbar->addSeparator();
202 QAction *selAtomAction = new QAction(QIcon(QPixmap(":/icon_select_atom.png")), tr("select atom by clicking"), this);
203 connect(selAtomAction, SIGNAL(triggered()), worldscene, SLOT(setSelectionModeAtom()));
204 toolbar->addAction(selAtomAction);
205 QAction *selMolAction = new QAction(QIcon(QPixmap(":/icon_select_molecule.png")), tr("select molecule by clicking"), this);
206 connect(selMolAction, SIGNAL(triggered()), worldscene, SLOT(setSelectionModeMolecule()));
207 toolbar->addAction(selMolAction);
208
209 // dreiBein/domain enabler
210 toolbar->addSeparator();
211 QAction *seldreiBein = new QAction(QIcon(QPixmap(":/icon_dreiBein.png")), tr("enable/disable dreiBein"), this);
212 connect(seldreiBein, SIGNAL(triggered()), this, SLOT(changeDreiBein()));
213 toolbar->addAction(seldreiBein);
214 QAction *seldomain = new QAction(QIcon(QPixmap(":/icon_domain.png")), tr("enable/disable domain box"), this);
215 connect(seldomain, SIGNAL(triggered()), this, SLOT(changeDomain()));
216 toolbar->addAction(seldomain);
217}
218
219void GLWorldView::createDomainBox()
220{
221 QSettings settings;
222 settings.beginGroup("WorldView");
223 QColor colorFrame = settings.value("domainBoxColorFrame", QColor(150,160,200,255)).value<QColor>();
224 QColor colorAmbient = settings.value("domainBoxColorAmbient", QColor(50,60,100,255)).value<QColor>();
225 QColor colorDiffuse = settings.value("domainBoxColorDiffuse", QColor(150,160,200,180)).value<QColor>();
226 settings.setValue("domainBoxColorFrame", colorFrame);
227 settings.setValue("domainBoxColorAmbient", colorAmbient);
228 settings.setValue("domainBoxColorDiffuse", colorDiffuse);
229 const bool status = settings.value("domainBoxEnabled").toBool();
230 settings.endGroup();
231
232 domainBoxMaterial = new QGLMaterial;
233 domainBoxMaterial->setAmbientColor(QColor(0,0,0,255));
234 domainBoxMaterial->setDiffuseColor(QColor(0,0,0,255));
235 domainBoxMaterial->setEmittedLight(colorFrame);
236
237
238 QGLMaterial *material = new QGLMaterial;
239 material->setAmbientColor(colorAmbient);
240 material->setDiffuseColor(colorDiffuse);
241
242 QGLBuilder builder;
243 builder << QGL::Faceted;
244 builder << QGLCube(-1.0); // "inverted" => inside faces are used as front.
245 meshDomainBox = builder.finalizedSceneNode();
246 QMatrix4x4 mat;
247 mat.translate(0.5f, 0.5f, 0.5f);
248 meshDomainBox->setLocalTransform(mat);
249 meshDomainBox->setMaterial(material);
250
251 setDomainStatus( status );
252}
253
254void GLWorldView::createDreiBein()
255{
256 QSettings settings;
257 settings.beginGroup("WorldView");
258 QColor colorX = settings.value("dreiBeinColorX", QColor(255,50,50,255)).value<QColor>();
259 QColor colorY = settings.value("dreiBeinColorY", QColor(50,255,50,255)).value<QColor>();
260 QColor colorZ = settings.value("dreiBeinColorZ", QColor(50,50,255,255)).value<QColor>();
261 settings.setValue("dreiBeinColorX", colorX);
262 settings.setValue("dreiBeinColorY", colorY);
263 settings.setValue("dreiBeinColorZ", colorZ);
264 const bool status = settings.value("dreiBeinEnabled").toBool();
265 settings.endGroup();
266
267 // Create 3 color for the 3 axes.
268 dreiBeinMaterial[0] = new QGLMaterial;
269 dreiBeinMaterial[0]->setColor(colorX);
270 dreiBeinMaterial[1] = new QGLMaterial;
271 dreiBeinMaterial[1]->setColor(colorY);
272 dreiBeinMaterial[2] = new QGLMaterial;
273 dreiBeinMaterial[2]->setColor(colorZ);
274
275 // Create the basic meshes (cylinder and cone).
276 QGLBuilder builderCyl;
277 builderCyl << QGLCylinder(.15,.15,1.6,16);
278 QGLSceneNode *cyl = builderCyl.finalizedSceneNode();
279
280 QGLBuilder builderCone;
281 builderCone << QGLCylinder(0,.4,0.4,16);
282 QGLSceneNode *cone = builderCone.finalizedSceneNode();
283 {
284 QMatrix4x4 mat;
285 mat.translate(0.0f, 0.0f, 1.0f);
286 cone->setLocalTransform(mat);
287 }
288
289 // Create a scene node from the 3 axes.
290 meshDreiBein = new QGLSceneNode(this);
291
292 // X-direction
293 QGLSceneNode *node = new QGLSceneNode(meshDreiBein);
294 node->setMaterial(dreiBeinMaterial[0]);
295 node->addNode(cyl);
296 node->setPosition(QVector3D(.8f, 0.f, 0.f));
297 node->addNode(cone);
298 {
299 QMatrix4x4 mat;
300 mat.rotate(90, 0.0f, 1.0f, 0.0f);
301 node->setLocalTransform(mat);
302 }
303
304 // Y-direction
305 node = new QGLSceneNode(meshDreiBein);
306 node->setMaterial(dreiBeinMaterial[1]);
307 node->addNode(cyl);
308 node->addNode(cone);
309 {
310 QMatrix4x4 mat;
311 mat.rotate(-90, 1.0f, 0.0f, 0.0f);
312 node->setLocalTransform(mat);
313 }
314 node->setPosition(QVector3D(0.f, .8f, 0.f));
315
316 // Z-direction
317 node = new QGLSceneNode(meshDreiBein);
318 node->setMaterial(dreiBeinMaterial[2]);
319 node->addNode(cyl);
320 node->addNode(cone);
321 node->setPosition(QVector3D(0.f, 0.f, .8f));
322
323 setdreiBeinStatus( status );
324}
325
326/**
327 * Update operation which can be invoked by the observable (which should be the
328 * change tracker here).
329 */
330void GLWorldView::update(Observable *publisher)
331{
332 emit changed();
333}
334
335void GLWorldView::signOnToMolecule(const molecule *_mol)
336{
337 ASSERT( _mol != NULL,
338 "GLWorldView::signOnToMolecule() - molecule ref is NULL.");
339 _mol->signOn(this, molecule::AtomInserted);
340 _mol->signOn(this, molecule::AtomRemoved);
341
342 ObservedMolecules.insert(const_cast<molecule *>(_mol));
343}
344
345void GLWorldView::signOffFromMolecule(const molecule *_mol)
346{
347 ObservedMolecules_t::const_iterator iter = ObservedMolecules.find(
348 const_cast<molecule *>(_mol));
349 ASSERT( iter != ObservedMolecules.end(),
350 "GLWorldView::signOffFromMolecule() - molecule "+toString(_mol)
351 +" gave subjectKilled we are not signed on.");
352// LOG(1, "INFO: Erasing " << mol << " from ObservedMolecules.");
353 ObservedMolecules.erase(iter);
354
355 ASSERT( _mol != NULL,
356 "GLWorldView::signOffFromMolecule() - molecule ref is NULL.");
357 _mol->signOff(this, molecule::AtomInserted);
358 _mol->signOff(this, molecule::AtomRemoved);
359}
360
361/**
362 * The observable can tell when it dies.
363 */
364void GLWorldView::subjectKilled(Observable *publisher)
365{
366 molecule * mol = static_cast<molecule *>(publisher);
367
368// std::copy(ObservedMolecules.begin(), ObservedMolecules.end(),
369// std::ostream_iterator<molecule *>(std::cout, "\n"));
370
371 if (mol != NULL) {
372
373 // sign off
374 signOffFromMolecule(mol);
375
376 // emit removed signal
377 const moleculeId_t _id = World::getInstance().lastChanged<molecule>()->getId();
378 emit moleculeRemoved(_id);
379 }
380}
381
382/** Listen to specific changes to the world.
383 *
384 * @param publisher ref to observable.
385 * @param notification type of notification
386 */
387void GLWorldView::recieveNotification(Observable *publisher, Notification_ptr notification)
388{
389 if (static_cast<World *>(publisher) == World::getPointer()) {
390 switch (notification->getChannelNo()) {
391 case World::SelectionChanged:
392 {
393 #ifdef LOG_OBSERVER
394 observerLog().addMessage() << "++ Observer " << observerLog().getName(static_cast<Observer *>(this)) << " received notification that selection has changed.";
395 #endif
396 emit worldSelectionChanged();
397 break;
398 }
399 case World::MoleculeInserted:
400 {
401 const moleculeId_t _id = World::getInstance().lastChanged<molecule>()->getId();
402 #ifdef LOG_OBSERVER
403 observerLog().addMessage() << "++ Observer " << observerLog().getName(static_cast<Observer *>(this)) << " received notification that molecule "+toString(_id)+" has been inserted.";
404 #endif
405 const molecule * const _molecule = const_cast<const World &>(World::getInstance()).
406 getMolecule(MoleculeById(_id));
407 if (_molecule != NULL) {
408 signOnToMolecule(_molecule);
409
410 emit moleculeInserted(_id);
411 }
412 break;
413 }
414 case World::MoleculeRemoved:
415 {
416 const moleculeId_t _id = World::getInstance().lastChanged<molecule>()->getId();
417 #ifdef LOG_OBSERVER
418 observerLog().addMessage() << "++ Observer " << observerLog().getName(static_cast<Observer *>(this)) << " received notification that molecule "+toString(_id)+" has been removed.";
419 #endif
420 // removed from ObservedMolecules via subjectKilled
421 emit moleculeRemoved(_id);
422 break;
423 }
424 default:
425 ASSERT(0, "GLWorldView::recieveNotification() - we cannot get here for World.");
426 break;
427 }
428 } else if (static_cast<WorldTime *>(publisher) == WorldTime::getPointer()) {
429 switch (notification->getChannelNo()) {
430 case WorldTime::TimeChanged:
431 {
432#ifdef LOG_OBSERVER
433 observerLog().addMessage() << "++ Observer " << observerLog().getName(static_cast<Observer *>(this)) << " received notification that WorldTime's time has changed.";
434#endif
435 emit changed();
436 emit TimeChanged();
437 break;
438 }
439 default:
440 ASSERT(0, "GLWorldView::recieveNotification() - we cannot get here for WorldTime.");
441 break;
442 }
443 } else if (dynamic_cast<molecule *>(publisher) != NULL) {
444 const molecule * mol = const_cast<const molecule * const>(dynamic_cast<molecule *>(publisher));
445 const atomId_t atomid = mol->lastChanged()->getId();
446 const moleculeId_t molid = mol->getId();
447 switch (notification->getChannelNo()) {
448 case molecule::AtomInserted:
449 {
450#ifdef LOG_OBSERVER
451 observerLog().addMessage() << "++ Observer " << observerLog().getName(static_cast<Observer *>(this))
452 << " received notification that atom "+toString(atomid)+" has been inserted into molecule "+toString(molid)+".";
453#endif
454 emit atomInserted(molid, atomid);
455 break;
456 }
457 case World::AtomRemoved:
458 {
459#ifdef LOG_OBSERVER
460 observerLog().addMessage() << "++ Observer " << observerLog().getName(static_cast<Observer *>(this))
461 << " received notification that atom "+toString(atomid)+" has been removed from molecule "+toString(molid)+".";
462#endif
463 emit atomRemoved(molid, atomid);
464 break;
465 }
466 default:
467 ASSERT(0, "GLWorldView::recieveNotification() - we cannot get here for molecule.");
468 break;
469 }
470 } else if (dynamic_cast<AtomObservable *>(publisher) != NULL) {
471 switch (notification->getChannelNo()) {
472 case AtomObservable::PositionChanged:
473 {
474 #ifdef LOG_OBSERVER
475 const atom *_atom = dynamic_cast<const atom *>(publisher);
476 observerLog().addMessage() << "++ Observer " << observerLog().getName(static_cast<Observer *>(this)) << " received notification that atom "+toString(_atom->getId())+" has changed its position.";
477 #endif
478 emit changed();
479 break;
480 }
481 default:
482 ASSERT(0, "GLWorldView::recieveNotification() - we cannot get here for AtomObservable.");
483 break;
484 }
485 } else if (static_cast<ShapeRegistry*>(publisher) == ShapeRegistry::getPointer()) {
486 switch (notification->getChannelNo()) {
487 case ShapeRegistry::ShapeInserted:
488 {
489 emit ShapeAdded();
490 break;
491 }
492 case ShapeRegistry::ShapeRemoved:
493 {
494 emit ShapeRemoved();
495 break;
496 }
497 case ShapeRegistry::SelectionChanged:
498 {
499 worldscene->updateSelectedShapes();
500 break;
501 }
502 default:
503 ASSERT(0, "GLWorldView::recieveNotification() - we cannot get here for ShapeRegistry.");
504 break;
505 }
506 } else
507 ASSERT(0, "GLWorldView::recieveNotification() - received notification from unknown source.");
508}
509
510void GLWorldView::checkChanges()
511{
512 updateGL();
513 needsRedraw = false;
514}
515
516void GLWorldView::changeDreiBein()
517{
518 // invert to new status
519 const bool status = ((meshDreiBein->options() & QGLSceneNode::HideNode) == 0);
520 setdreiBeinStatus(!status);
521 // realize
522 updateGL();
523 needsRedraw = true;
524}
525
526void GLWorldView::setdreiBeinStatus(const bool status)
527{
528 if (status)
529 meshDreiBein->setOptions( meshDreiBein->options() & (255-QGLSceneNode::HideNode) );
530 else
531 meshDreiBein->setOptions( meshDreiBein->options() | QGLSceneNode::HideNode );
532}
533
534void GLWorldView::changeDomain()
535{
536 // invert to new status
537 const bool status = ((meshDomainBox->options() & QGLSceneNode::HideNode) == 0);
538 setDomainStatus(!status);
539 // realize
540 updateGL();
541 needsRedraw = true;
542}
543
544void GLWorldView::setDomainStatus(const bool status)
545{
546 if (status)
547 meshDomainBox->setOptions( meshDomainBox->options() & (255-QGLSceneNode::HideNode) );
548 else
549 meshDomainBox->setOptions( meshDomainBox->options() | QGLSceneNode::HideNode );
550}
551
552void GLWorldView::sceneChangeSignalled()
553{
554 if (!needsRedraw){
555 redrawTimer->singleShot(0, this, SLOT(checkChanges()));
556 needsRedraw = true;
557 redrawTimer->start();
558 }
559}
560
561void GLWorldView::initializeGL(QGLPainter *painter)
562{
563 worldscene->initialize(this, painter);
564 changesPresent = false;
565}
566
567void GLWorldView::paintGL(QGLPainter *painter)
568{
569 if (changesPresent) {
570 initializeGL(painter);
571 changesPresent = false;
572 }
573
574 QVector3D cameraDir = camera()->center() - camera()->eye();
575 cameraDir.normalize();
576 QVector4D cameraPlane(cameraDir, QVector3D::dotProduct(cameraDir, camera()->eye()));
577 worldscene->draw(painter, cameraPlane);
578
579 drawDreiBein(painter);
580
581 // Domain box has to be last because of its transparency.
582 drawDomainBox(painter);
583}
584
585void GLWorldView::keyPressEvent(QKeyEvent *e)
586{
587 // Find the distance between the eye and focus point.
588 QVector3D d = camera()->eye() - camera()->center();
589// LOG(1, "Distance vector eye and center is "
590// << d.x() << "," << d.y() << "," << d.z());
591 // scale the move unit by the eye <-> domain center distance
592 const double key_move_unit = 0.04*(d.length()/50.);
593
594 if (e->key() == Qt::Key_Tab) {
595 // The Tab key turns the ShowPicking option on and off,
596 // which helps show what the pick buffer looks like.
597 setOption(QGLView::ShowPicking, ((options() & QGLView::ShowPicking) == 0));
598 updateGL();
599 } else if ((e->key() == Qt::Key_Minus) || (e->key() == Qt::Key_Plus)) {
600 // Scale the distance.
601 if (e->key() == Qt::Key_Minus)
602 d *= 1.2;
603 else if (e->key() == Qt::Key_Plus)
604 d /= 1.2;
605 // Set new eye position.
606 camera()->setEye(camera()->center() + d);
607 } else if ((e->key() == Qt::Key_Left) || (e->key() == Qt::Key_Right)) {
608 // Translate the camera.
609 const double d = (e->key() == Qt::Key_Left) ? -key_move_unit : key_move_unit;
610 camera()->translateCenter( d, 0., 0);
611 camera()->translateEye( d, 0., 0);
612 } else if ((e->key() == Qt::Key_Up) || (e->key() == Qt::Key_Down)) {
613 // Translate the camera.
614 const double d = (e->key() == Qt::Key_Up) ? -key_move_unit : key_move_unit;
615 camera()->translateCenter( 0., d, 0);
616 camera()->translateEye( 0., d, 0);
617 } else if ((e->key() == Qt::Key_PageUp) || (e->key() == Qt::Key_PageDown)) {
618 // Translate the camera.
619 const double d = (e->key() == Qt::Key_PageUp) ? -key_move_unit : key_move_unit;
620 camera()->translateCenter( 0., 0., d);
621 camera()->translateEye( 0., 0., d);
622 }
623 QGLView::keyPressEvent(e);
624}
625
626void GLWorldView::changeSignalled()
627{
628 changesPresent = true;
629}
630
631
632/**
633 * Set the current camera control mode.
634 */
635void GLWorldView::setCameraControlMode(GLWorldView::CameraControlModeType mode)
636{
637 cameraControlMode = mode;
638}
639
640void GLWorldView::setCameraControlModeRotation()
641{
642 setCameraControlMode(Rotate);
643}
644
645void GLWorldView::setCameraControlModeTranslation()
646{
647 setCameraControlMode(Translate);
648}
649
650/**
651 * Returns the current camera control mode.
652 * This needs to be invertable (rotation - translation), if the shift key is pressed.
653 */
654GLWorldView::CameraControlModeType GLWorldView::getCameraControlMode(bool inverted)
655{
656 if (inverted){
657 if (cameraControlMode == Rotate)
658 return Translate;
659 if (cameraControlMode == Translate)
660 return Rotate;
661 return Rotate;
662 }else
663 return cameraControlMode;
664}
665
666/**
667 * Set the camera so it can oversee the whole domain.
668 */
669void GLWorldView::fitCameraToDomain()
670{
671 // Move the camera focus point to the center of the domain box.
672 Vector v = World::getInstance().getDomain().translateIn(Vector(0.5, 0.5, 0.5));
673 camera()->setCenter(QVector3D(v[0], v[1], v[2]));
674
675 // Guess some eye distance.
676 double dist = v.Norm() * 3;
677 camera()->setEye(QVector3D(v[0], v[1], v[2] + dist));
678 camera()->setUpVector(QVector3D(0, 1, 0));
679}
680
681void GLWorldView::setCameraStereoModeDisable()
682{
683 setStereoType(QGLView::Hardware);
684 camera()->setEyeSeparation(0.0);
685 updateGL();
686}
687
688void GLWorldView::setCameraStereoModeHardware()
689{
690 setStereoType(QGLView::Hardware);
691 camera()->setEyeSeparation(defaultEyeSeparation);
692 updateGL();
693}
694
695void GLWorldView::setCameraStereoModeLeftRight()
696{
697 setStereoType(QGLView::LeftRight);
698 camera()->setEyeSeparation(defaultEyeSeparation);
699 updateGL();
700}
701
702void GLWorldView::setCameraStereoModeRightLeft()
703{
704 setStereoType(QGLView::RightLeft);
705 camera()->setEyeSeparation(defaultEyeSeparation);
706 updateGL();
707}
708
709void GLWorldView::setCameraStereoModeTopBottom()
710{
711 setStereoType(QGLView::TopBottom);
712 camera()->setEyeSeparation(defaultEyeSeparation);
713 updateGL();
714}
715
716void GLWorldView::setCameraStereoModeBottomTop()
717{
718 setStereoType(QGLView::BottomTop);
719 camera()->setEyeSeparation(defaultEyeSeparation);
720 updateGL();
721}
722
723void GLWorldView::setCameraStereoModeAnaglyph()
724{
725 setStereoType(QGLView::RedCyanAnaglyph);
726 camera()->setEyeSeparation(defaultEyeSeparation);
727 updateGL();
728}
729
730void GLWorldView::mousePressEvent(QMouseEvent *event)
731{
732 QGLView::mousePressEvent(event);
733
734 // Reset the saved mouse position.
735 lastMousePos = event->posF();
736}
737
738/**
739 * Handle a mouse move event.
740 * This is used to control the camera (rotation and translation) when the left button is being pressed.
741 */
742void GLWorldView::mouseMoveEvent(QMouseEvent *event)
743{
744 if (event->buttons() & Qt::LeftButton){
745 // Find the mouse distance since the last event.
746 QPointF d = event->posF() - lastMousePos;
747 lastMousePos = event->posF();
748
749 // Rotate or translate? (inverted by shift key)
750 CameraControlModeType mode = getCameraControlMode(event->modifiers() & Qt::ShiftModifier);
751
752 if (mode == Rotate){
753 // Rotate the camera.
754 d *= 0.3;
755 camera()->tiltPanRollCenter(- d.y(), - d.x(), 0);
756 }else if (mode == Translate){
757 // Translate the camera.
758 d *= 0.02;
759 camera()->translateCenter(- d.x(), d.y(), 0);
760 camera()->translateEye(- d.x(), d.y(), 0);
761 }
762 }else{
763 // Without this Qt would not test for hover events (i.e. mouse over an atom).
764 QGLView::mouseMoveEvent(event);
765 }
766}
767
768/**
769 * When the mouse wheel is used, zoom in or out.
770 */
771void GLWorldView::wheelEvent(QWheelEvent *event)
772{
773 // Find the distance between the eye and focus point.
774 QVector3D d = camera()->eye() - camera()->center();
775
776 // Scale the distance.
777 if (event->delta() < 0)
778 d *= 1.2;
779 else if (event->delta() > 0)
780 d /= 1.2;
781
782 // Set new eye position.
783 camera()->setEye(camera()->center() + d);
784}
785
786/**
787 * Draw a transparent cube representing the domain.
788 */
789void GLWorldView::drawDomainBox(QGLPainter *painter) const
790{
791 // Apply the domain matrix.
792 RealSpaceMatrix m = World::getInstance().getDomain().getM();
793 painter->modelViewMatrix().push();
794 painter->modelViewMatrix() *= QMatrix4x4(m.at(0,0), m.at(0,1), m.at(0,2), 0.0,
795 m.at(1,0), m.at(1,1), m.at(1,2), 0.0,
796 m.at(2,0), m.at(2,1), m.at(2,2), 0.0,
797 0.0, 0.0, 0.0, 1.0);
798
799 // Draw the transparent cube.
800 painter->setStandardEffect(QGL::LitMaterial);
801 glCullFace(GL_BACK);
802 glEnable(GL_CULL_FACE);
803 glEnable(GL_BLEND);
804 glDepthMask(0);
805 //glDisable(GL_DEPTH_TEST);
806 meshDomainBox->draw(painter);
807 //glEnable(GL_DEPTH_TEST);
808 glDepthMask(1);
809 glDisable(GL_BLEND);
810 glDisable(GL_CULL_FACE);
811
812 // Draw the outlines (if we have drawn the box itself)
813 if ((meshDomainBox->options() & QGLSceneNode::HideNode) == 0) {
814 painter->setFaceMaterial(QGL::AllFaces, domainBoxMaterial);
815 //glEnable(GL_LINE_SMOOTH);
816 QVector3DArray array;
817 array.append(0, 0, 0); array.append(1, 0, 0);
818 array.append(1, 0, 0); array.append(1, 1, 0);
819 array.append(1, 1, 0); array.append(0, 1, 0);
820 array.append(0, 1, 0); array.append(0, 0, 0);
821
822 array.append(0, 0, 1); array.append(1, 0, 1);
823 array.append(1, 0, 1); array.append(1, 1, 1);
824 array.append(1, 1, 1); array.append(0, 1, 1);
825 array.append(0, 1, 1); array.append(0, 0, 1);
826
827 array.append(0, 0, 0); array.append(0, 0, 1);
828 array.append(1, 0, 0); array.append(1, 0, 1);
829 array.append(0, 1, 0); array.append(0, 1, 1);
830 array.append(1, 1, 0); array.append(1, 1, 1);
831 painter->clearAttributes();
832 painter->setVertexAttribute(QGL::Position, array);
833 painter->draw(QGL::Lines, 24);
834 }
835
836 painter->modelViewMatrix().pop();
837}
838
839void GLWorldView::drawDreiBein(QGLPainter *painter)
840{
841 painter->modelViewMatrix().push();
842 painter->modelViewMatrix().translate(camera()->center());
843 painter->setStandardEffect(QGL::LitMaterial);
844 painter->setFaceMaterial(QGL::FrontFaces, NULL);
845 meshDreiBein->draw(painter);
846 painter->modelViewMatrix().pop();
847}
848
849void GLWorldView::sceneHoverSignalled(const atomId_t _id)
850{
851 emit hoverChanged(_id);
852}
853
854void GLWorldView::sceneHoverSignalled(const moleculeId_t _id, int _i)
855{
856 emit hoverChanged(_id, _i);
857}
Note: See TracBrowser for help on using the repository browser.