Import Geant4 10.7.0 source tree

This commit is contained in:
Gabriele Cosmo
2020-12-04 12:30:43 +01:00
parent 67ba86d073
commit dab42d2018
3770 changed files with 226369 additions and 286486 deletions
+103
View File
@@ -0,0 +1,103 @@
//
// ********************************************************************
// * License and Disclaimer *
// * *
// * The Geant4 software is copyright of the Copyright Holders of *
// * the Geant4 Collaboration. It is provided under the terms and *
// * conditions of the Geant4 Software License, included in the file *
// * LICENSE and available at http://cern.ch/geant4/license . These *
// * include a list of copyright holders. *
// * *
// * Neither the authors of this software system, nor their employing *
// * institutes,nor the agencies providing financial support for this *
// * work make any representation or warranty, express or implied, *
// * regarding this software system or assume any liability for its *
// * use. Please see the license in the file LICENSE and URL above *
// * for the full disclaimer and the limitation of liability. *
// * *
// * This code implementation is the result of the scientific and *
// * technical work of the GEANT4 collaboration. *
// * By using, copying, modifying or distributing the software (or *
// * any work based on the software) you agree to acknowledge its *
// * use in resulting scientific publications, and indicate your *
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
// John Allison 17th June 2019
#if defined (G4VIS_BUILD_QT3D_DRIVER) || defined (G4VIS_USE_QT3D)
#include "G4Qt3D.hh"
#include "G4Qt3DSceneHandler.hh"
#include "G4Qt3DViewer.hh"
#include "G4UIQt.hh"
#include "G4UImanager.hh"
#include "G4UIbatch.hh"
G4Qt3D::G4Qt3D():
G4VGraphicsSystem
("Qt3D",
"Qt3D",
"Qt3D graphics driver",
G4VGraphicsSystem::threeDInteractive) {}
G4Qt3D::~G4Qt3D() {}
G4VSceneHandler* G4Qt3D::CreateSceneHandler(const G4String& name) {
G4VSceneHandler* pScene = new G4Qt3DSceneHandler(*this, name);
return pScene;
}
G4VViewer* G4Qt3D::CreateViewer(G4VSceneHandler& scene,
const G4String& name) {
G4VViewer* pView =
new G4Qt3DViewer((G4Qt3DSceneHandler&) scene, name);
if (pView) {
if (pView->GetViewId() < 0) {
G4cerr <<
"G4Qt3D::CreateViewer: ERROR flagged by negative"
" view id in G4Qt3DViewer creation."
"\n Destroying view and returning null pointer."
<< G4endl;
delete pView;
pView = 0;
}
}
if (!pView) {
G4cerr <<
"G4Qt3D::CreateViewer: ERROR: null pointer on new G4Qt3DViewer."
<< G4endl;
}
return pView;
}
G4bool G4Qt3D::IsUISessionCompatible () const
{
G4bool isCompatible = false;
G4UImanager* ui = G4UImanager::GetUIpointer();
G4UIsession* session = ui->GetSession();
// If session is a batch session, it may be:
// a) this is a batch job (the user has not instantiated any UI session);
// b) we are currently processing a UI command, in which case the UI
// manager creates a temporary batch session and to find out if there is
// a genuine UI session that the user has instantiated we must drill
// down through previous sessions to a possible non-batch session.
while (G4UIbatch* batch = dynamic_cast<G4UIbatch*>(session)) {
session = batch->GetPreviousSession();
}
// Qt windows are only appropriate in a Qt session.
if (session) {
// If non-zero, this is the originating non-batch session
// The user has instantiated a UI session...
if (dynamic_cast<G4UIQt*>(session)) {
// ...and it's a G4UIQt session, which is OK.
isCompatible = true;
}
}
return isCompatible;
}
#endif // #if defined (G4VIS_BUILD_QT3D_DRIVER) || defined (G4VIS_USE_QT3D)
@@ -0,0 +1,997 @@
//
// ********************************************************************
// * License and Disclaimer *
// * *
// * The Geant4 software is copyright of the Copyright Holders of *
// * the Geant4 Collaboration. It is provided under the terms and *
// * conditions of the Geant4 Software License, included in the file *
// * LICENSE and available at http://cern.ch/geant4/license . These *
// * include a list of copyright holders. *
// * *
// * Neither the authors of this software system, nor their employing *
// * institutes,nor the agencies providing financial support for this *
// * work make any representation or warranty, express or implied, *
// * regarding this software system or assume any liability for its *
// * use. Please see the license in the file LICENSE and URL above *
// * for the full disclaimer and the limitation of liability. *
// * *
// * This code implementation is the result of the scientific and *
// * technical work of the GEANT4 collaboration. *
// * By using, copying, modifying or distributing the software (or *
// * any work based on the software) you agree to acknowledge its *
// * use in resulting scientific publications, and indicate your *
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
// John Allison 17th June 2019
#if defined (G4VIS_BUILD_QT3D_DRIVER) || defined (G4VIS_USE_QT3D)
#include "G4Qt3DSceneHandler.hh"
#include "G4PhysicalVolumeModel.hh"
#include "G4LogicalVolumeModel.hh"
#include "G4VPhysicalVolume.hh"
#include "G4LogicalVolume.hh"
#include "G4TransportationManager.hh"
#include "G4Box.hh"
#include "G4Polyline.hh"
#include "G4Polymarker.hh"
#include "G4Text.hh"
#include "G4Circle.hh"
#include "G4Square.hh"
#include "G4Polyhedron.hh"
#include "G4Scene.hh"
#include "G4Threading.hh"
#include "G4Qt3DViewer.hh"
#include "G4Qt3DUtils.hh"
#include "G4Qt3DQEntity.hh"
#include <Qt3DCore>
#include <Qt3DExtras>
#include <Qt3DRender>
#include <utility>
// Qt3D seems to offer a choice of type - float or double. It would be nice
// to use double since it offers the prospect of higher precision, hopefully
// avoiding some issues that we see at high zoom. But it currently gives the
// following warning: "findBoundingVolumeComputeData: Position attribute not
// suited for bounding volume computation", so for now we use float.
#define PRECISION float
#define BASETYPE Qt3DRender::QAttribute::Float
G4int G4Qt3DSceneHandler::fSceneIdCount = 0;
G4Qt3DSceneHandler::G4Qt3DSceneHandler
(G4VGraphicsSystem& system, const G4String& name)
: G4VSceneHandler(system, fSceneIdCount++, name)
{
#ifdef G4QT3DDEBUG
G4cout << "G4Qt3DSceneHandler::G4Qt3DSceneHandler called" << G4endl;
#endif
fpQt3DScene = new Qt3DCore::QEntity;
fpQt3DScene->setObjectName("G4Qt3DSceneRoot");
EstablishG4Qt3DQEntities();
}
G4Qt3DSceneHandler::~G4Qt3DSceneHandler()
{
// Doesn't like this - it gives BAD_ACCESS in delete_entity_recursively.
// Curiously the delete traceback shows three calls to this recursively:
/*#1 0x0000000100411906 in (anonymous namespace)::delete_entity_recursively(Qt3DCore::QNode*) at /Users/johna/Geant4/geant4-dev/source/visualization/Qt3D/src/G4Qt3DSceneHandler.cc:60
#2 0x0000000100411840 in G4Qt3DSceneHandler::~G4Qt3DSceneHandler() at /Users/johna/Geant4/geant4-dev/source/visualization/Qt3D/src/G4Qt3DSceneHandler.cc:169
#3 0x0000000100411fc5 in G4Qt3DSceneHandler::~G4Qt3DSceneHandler() at /Users/johna/Geant4/geant4-dev/source/visualization/Qt3D/src/G4Qt3DSceneHandler.cc:168
#4 0x0000000100411fe9 in G4Qt3DSceneHandler::~G4Qt3DSceneHandler() at /Users/johna/Geant4/geant4-dev/source/visualization/Qt3D/src/G4Qt3DSceneHandler.cc:168
#5 0x0000000101032510 in G4VisManager::~G4VisManager() at /Users/johna/Geant4/geant4-dev/source/visualization/management/src/G4VisManager.cc:214
#6 0x0000000100013885 in G4VisExecutive::~G4VisExecutive() at /Users/johna/Geant4/geant4-dev/source/visualization/management/include/G4VisExecutive.hh:119
#7 0x00000001000119a5 in G4VisExecutive::~G4VisExecutive() at /Users/johna/Geant4/geant4-dev/source/visualization/management/include/G4VisExecutive.hh:119
#8 0x00000001000119c9 in G4VisExecutive::~G4VisExecutive() at /Users/johna/Geant4/geant4-dev/source/visualization/management/include/G4VisExecutive.hh:119
#9 0x00000001000117dd in main at /Users/johna/Geant4/geant4-dev/examples/basic/B1/exampleB1.cc:108
*/
//if (fpQt3DScene) delete_entity_recursively(fpQt3DScene);
}
void G4Qt3DSceneHandler::EstablishG4Qt3DQEntities()
{
fpTransientObjects = new G4Qt3DQEntity(fpQt3DScene); // Hangs from root
fpTransientObjects ->setObjectName("G4Qt3DTORoot");
fpPersistentObjects = new G4Qt3DQEntity(fpQt3DScene); // Hangs from root
fpPersistentObjects ->setObjectName("G4Qt3DPORoot");
// Physical volume objects for each world hang from POs
G4TransportationManager* transportationManager
= G4TransportationManager::GetTransportationManager ();
size_t nWorlds = transportationManager->GetNoWorlds();
std::vector<G4VPhysicalVolume*>::iterator iterWorld
= transportationManager->GetWorldsIterator();
fpPhysicalVolumeObjects.resize(nWorlds);
for (size_t i = 0; i < nWorlds; ++i, ++iterWorld) {
G4VPhysicalVolume* world = (*iterWorld);
auto entity = new G4Qt3DQEntity(fpPersistentObjects);
entity->setObjectName("G4Qt3DPORoot_"+QString(world->GetName()));
entity->SetPVNodeID(G4PhysicalVolumeModel::G4PhysicalVolumeNodeID(world));
fpPhysicalVolumeObjects[i] = entity;
}
}
G4Qt3DQEntity* G4Qt3DSceneHandler::CreateNewNode()
{ // Create a G4Qt3DQEntity node suitable for next solid or primitive
// Avoid Qt errors in MT mode - see G4Qt3DViewer::SwitchToMasterThread
#ifdef G4MULTITHREADED
if (!G4Threading::IsMasterThread()) return nullptr;
#endif
G4Qt3DQEntity* newNode = nullptr;
if (fReadyForTransients) { // All transients hang from this node
newNode = new G4Qt3DQEntity(fpTransientObjects);
newNode->setObjectName(fpModel->GetGlobalTag().c_str());
return newNode;
}
G4PhysicalVolumeModel* pPVModel =
dynamic_cast<G4PhysicalVolumeModel*>(fpModel);
if (!pPVModel) { // Persistent objects (e.g., axes)
newNode = new G4Qt3DQEntity(fpPersistentObjects);
newNode->setObjectName(fpModel->GetGlobalTag().c_str());
return newNode;
}
// So this is a G4PhysicalVolumeModel
typedef G4PhysicalVolumeModel::G4PhysicalVolumeNodeID PVNodeID;
typedef std::vector<PVNodeID> PVPath;
// const PVPath& drawnPVPath = pPVModel->GetDrawnPVPath();
const PVPath& fullPVPath = pPVModel->GetFullPVPath();
//G4int currentDepth = pPVModel->GetCurrentDepth();
//G4VPhysicalVolume* pCurrentPV = pPVModel->GetCurrentPV();
//G4LogicalVolume* pCurrentLV = pPVModel->GetCurrentLV();
//G4Material* pCurrentMaterial = pPVModel->GetCurrentMaterial();
// Note: pCurrentMaterial may be zero (parallel world).
#ifdef G4QTDEBUG
G4cout << "A: " << fullPVPath << G4endl; // DEBUG
#endif
// Find appropriate root
const size_t nWorlds = fpPhysicalVolumeObjects.size();
size_t iWorld = 0;
for (; iWorld < nWorlds; ++iWorld) {
if (fullPVPath[0].GetPhysicalVolume() ==
fpPhysicalVolumeObjects[iWorld]->GetPVNodeID().GetPhysicalVolume()) break;
}
if (iWorld == nWorlds) {
G4Exception("G4Qt3DSceneHandler::CreateNewNode", "qt3D-0000", FatalException,
"World mis-match - not possible(!?)");
}
// (Re-)establish pv path of root entity
G4Qt3DQEntity* world = fpPhysicalVolumeObjects[iWorld];
world->SetPVNodeID(fullPVPath[0]);
// Create nodes as required
G4Qt3DQEntity* node = world;
newNode = node;
const size_t depth = fullPVPath.size();
size_t iDepth = 1;
while (iDepth < depth) {
const auto& children = node->children();
const G4int nChildren = children.size(); // int size() (Qt covention?)
G4int iChild = 0;
G4Qt3DQEntity* child = nullptr;
for (; iChild < nChildren; ++iChild) {
child = static_cast<G4Qt3DQEntity*>(children[iChild]);
if (child->GetPVNodeID() == fullPVPath[iDepth]) break;
}
if (iChild != nChildren) { // Existing node found
node = child; // Must be the ancestor of new node (subsequent iteration)
} else {
// Add a new node as child of node
newNode = new G4Qt3DQEntity(node);
newNode->SetPVNodeID(fullPVPath[iDepth]);
std::ostringstream oss;
oss << newNode->GetPVNodeID().GetPhysicalVolume()->GetName()
<< ':' << newNode->GetPVNodeID().GetCopyNo();
newNode->setObjectName(oss.str().c_str());
node = newNode;
}
++iDepth;
}
return node;
}
void G4Qt3DSceneHandler::PreAddSolid
(const G4Transform3D& objectTransformation,
const G4VisAttributes& visAttribs)
{
G4VSceneHandler::PreAddSolid(objectTransformation, visAttribs);
}
void G4Qt3DSceneHandler::PostAddSolid()
{
G4VSceneHandler::PostAddSolid();
}
void G4Qt3DSceneHandler::BeginPrimitives2D(const G4Transform3D& objectTransformation)
{
// The x,y coordinates of the primitives passed to AddPrimitive are
// intrepreted as screen coordinates, -1 < x,y < 1. The
// z-coordinate is ignored.
// IMPORTANT: invoke this from your polymorphic versions, e.g.:
// void MyXXXSceneHandler::BeginPrimitives2D
// (const G4Transform3D& objectTransformation) {
static G4bool first = true;
if (first) {
first = false;
G4Exception("G4Qt3DSceneHandler::BeginPrimitives2D", "qt3D-0001",
JustWarning,
"2D drawing not yet implemented");
}
G4VSceneHandler::BeginPrimitives2D (objectTransformation);
// ...
}
void G4Qt3DSceneHandler::EndPrimitives2D ()
{
// IMPORTANT: invoke this from your polymorphic versions, e.g.:
// void MyXXXSceneHandler::EndPrimitives2D () {
// ...
G4VSceneHandler::EndPrimitives2D ();
}
void G4Qt3DSceneHandler::BeginPrimitives
(const G4Transform3D& objectTransformation)
{
G4VSceneHandler::BeginPrimitives(objectTransformation);
}
void G4Qt3DSceneHandler::EndPrimitives ()
{
G4VSceneHandler::EndPrimitives ();
}
void G4Qt3DSceneHandler::AddPrimitive(const G4Polyline& polyline)
{
#ifdef G4QT3DDEBUG
G4cout <<
"G4Qt3DSceneHandler::AddPrimitive(const G4Polyline& polyline) called.\n"
<< polyline
<< G4endl;
#endif
auto currentNode = CreateNewNode();
if (!currentNode) return; // Node not available
if (polyline.size() == 0) return;
fpVisAttribs = fpViewer->GetApplicableVisAttributes(polyline.GetVisAttributes());
auto transform = G4Qt3DUtils::CreateQTransformFrom(fObjectTransformation);
transform->setObjectName("transform");
auto polylineEntity = new Qt3DCore::QEntity(currentNode);
polylineEntity->addComponent(transform);
const auto vertexByteSize = 3*sizeof(PRECISION);
const size_t nLines = polyline.size() - 1;
QByteArray polylineByteArray;
const auto polylineBufferByteSize = 2*nLines*vertexByteSize;
polylineByteArray.resize(polylineBufferByteSize);
auto polylineBufferArray = reinterpret_cast<PRECISION*>(polylineByteArray.data());
G4int iLine = 0;
for (size_t i = 0; i < nLines; ++i) {
polylineBufferArray[iLine++] = polyline[i].x();
polylineBufferArray[iLine++] = polyline[i].y();
polylineBufferArray[iLine++] = polyline[i].z();
polylineBufferArray[iLine++] = polyline[i+1].x();
polylineBufferArray[iLine++] = polyline[i+1].y();
polylineBufferArray[iLine++] = polyline[i+1].z();
}
auto polylineGeometry = new Qt3DRender::QGeometry();
polylineGeometry->setObjectName("polylineGeometry");
auto polylineBuffer = new Qt3DRender::QBuffer(polylineGeometry);
polylineBuffer->setObjectName("Polyline buffer");
polylineBuffer->setData(polylineByteArray);
auto polylineAtt = new Qt3DRender::QAttribute;
polylineAtt->setObjectName("Position attribute");
polylineAtt->setName(Qt3DRender::QAttribute::defaultPositionAttributeName());
polylineAtt->setBuffer(polylineBuffer);
polylineAtt->setAttributeType(Qt3DRender::QAttribute::VertexAttribute);
polylineAtt->setVertexBaseType(BASETYPE);
polylineAtt->setVertexSize(3);
polylineAtt->setCount(nLines);
polylineAtt->setByteOffset(0);
polylineAtt->setByteStride(vertexByteSize);
const auto& colour = fpVisAttribs->GetColour();
polylineGeometry->addAttribute(polylineAtt);
auto material = new Qt3DExtras::QDiffuseSpecularMaterial();
material->setObjectName("materialForPolyline");
material->setAmbient(G4Qt3DUtils::ConvertToQColor(colour));
material->setShininess(0.);
material->setSpecular(0.);
polylineEntity->addComponent(material);
auto renderer = new Qt3DRender::QGeometryRenderer;
renderer->setObjectName("polyhedronWireframeRenderer");
renderer->setGeometry(polylineGeometry);
renderer->setVertexCount(2*nLines);
renderer->setPrimitiveType(Qt3DRender::QGeometryRenderer::Lines);
polylineEntity->addComponent(renderer);
}
void G4Qt3DSceneHandler::AddPrimitive (const G4Polymarker& polymarker)
{
auto currentNode = CreateNewNode();
if (!currentNode) return; // Node not available
if (polymarker.size() == 0) return;
fpVisAttribs = fpViewer->GetApplicableVisAttributes(polymarker.GetVisAttributes());
switch (polymarker.GetMarkerType()) {
default:
case G4Polymarker::dots:
{
const size_t nDots = polymarker.size();
auto transform = G4Qt3DUtils::CreateQTransformFrom(fObjectTransformation);
transform->setObjectName("transform");
auto polymarkerEntity = new Qt3DCore::QEntity(currentNode);
polymarkerEntity->addComponent(transform);
const auto vertexByteSize = 3*sizeof(PRECISION);
QByteArray polymarkerByteArray;
const auto polymarkerBufferByteSize = nDots*vertexByteSize;
polymarkerByteArray.resize(polymarkerBufferByteSize);
auto polymarkerBufferArray = reinterpret_cast<PRECISION*>(polymarkerByteArray.data());
G4int iMarker = 0;
for (size_t i = 0; i < polymarker.size(); ++i) {
polymarkerBufferArray[iMarker++] = polymarker[i].x();
polymarkerBufferArray[iMarker++] = polymarker[i].y();
polymarkerBufferArray[iMarker++] = polymarker[i].z();
}
auto polymarkerGeometry = new Qt3DRender::QGeometry();
polymarkerGeometry->setObjectName("polymarkerGeometry");
auto polymarkerBuffer = new Qt3DRender::QBuffer(polymarkerGeometry);
polymarkerBuffer->setObjectName("Polymarker buffer");
polymarkerBuffer->setData(polymarkerByteArray);
auto polymarkerAtt = new Qt3DRender::QAttribute;
polymarkerAtt->setObjectName("Position attribute");
polymarkerAtt->setName(Qt3DRender::QAttribute::defaultPositionAttributeName());
polymarkerAtt->setBuffer(polymarkerBuffer);
polymarkerAtt->setAttributeType(Qt3DRender::QAttribute::VertexAttribute);
polymarkerAtt->setVertexBaseType(BASETYPE);
polymarkerAtt->setVertexSize(3);
polymarkerAtt->setCount(nDots);
polymarkerAtt->setByteOffset(0);
polymarkerAtt->setByteStride(vertexByteSize);
const auto& colour = fpVisAttribs->GetColour();
polymarkerGeometry->addAttribute(polymarkerAtt);
auto material = new Qt3DExtras::QDiffuseSpecularMaterial();
material->setObjectName("materialForPolymarker");
material->setAmbient(G4Qt3DUtils::ConvertToQColor(colour));
material->setShininess(0.);
material->setSpecular(0.);
polymarkerEntity->addComponent(material);
auto renderer = new Qt3DRender::QGeometryRenderer;
renderer->setObjectName("polymarkerWireframeRenderer");
renderer->setGeometry(polymarkerGeometry);
renderer->setVertexCount(nDots);
renderer->setPrimitiveType(Qt3DRender::QGeometryRenderer::Points);
polymarkerEntity->addComponent(renderer);
}
break;
case G4Polymarker::circles:
{
G4Circle circle (polymarker); // Default circle
const auto& colour = fpVisAttribs->GetColour();
auto material = new Qt3DExtras::QDiffuseSpecularMaterial();
material->setObjectName("materialForCircle");
material->setAmbient(G4Qt3DUtils::ConvertToQColor(colour));
if (colour.GetAlpha() < 1.) material->setAlphaBlendingEnabled(true);
auto sphereMesh = new Qt3DExtras::QSphereMesh;
sphereMesh->setObjectName("sphereMesh");
G4double radius;
if (circle.GetSizeType() == G4VMarker::world ) {
radius =circle.GetWorldRadius();
} else { // Screen-size or none
// Not figured out how to do screen-size, so use scene extent
const G4double scale = 200.; // Roughly pixles per scene
radius = circle.GetScreenRadius()*fpScene->GetExtent().GetExtentRadius()/scale;
}
sphereMesh->setRadius(radius);
for (size_t iPoint = 0; iPoint < polymarker.size (); iPoint++) {
auto position = fObjectTransformation*G4Translate3D(polymarker[iPoint]);
auto transform = G4Qt3DUtils::CreateQTransformFrom(position);
auto currentEntity = new Qt3DCore::QEntity(currentNode);
currentEntity->addComponent(material);
currentEntity->addComponent(transform);
currentEntity->addComponent(sphereMesh);
}
}
break;
case G4Polymarker::squares:
{
G4Square square (polymarker); // Default square
const auto& colour = fpVisAttribs->GetColour();
auto material = new Qt3DExtras::QDiffuseSpecularMaterial();
material->setObjectName("materialForSquare");
material->setAmbient(G4Qt3DUtils::ConvertToQColor(colour));
if (colour.GetAlpha() < 1.) material->setAlphaBlendingEnabled(true);
auto boxMesh = new Qt3DExtras::QCuboidMesh();
boxMesh->setObjectName("boxMesh");
G4double side;
if (square.GetSizeType() == G4VMarker::world ) {
side = square.GetWorldDiameter();
} else { // Screen-size or none
// Not figured out how to do screen-size, so use scene extent
const G4double scale = 200.; // Roughly pixles per scene
side = square.GetScreenDiameter()*fpScene->GetExtent().GetExtentRadius()/scale;
}
boxMesh->setXExtent(side);
boxMesh->setYExtent(side);
boxMesh->setZExtent(side);
for (size_t iPoint = 0; iPoint < polymarker.size (); iPoint++) {
auto position = fObjectTransformation*G4Translate3D(polymarker[iPoint]);
auto transform = G4Qt3DUtils::CreateQTransformFrom(position);
auto currentEntity = new Qt3DCore::QEntity(currentNode);
currentEntity->addComponent(material);
currentEntity->addComponent(transform);
currentEntity->addComponent(boxMesh);
}
}
break;
}
}
void G4Qt3DSceneHandler::AddPrimitive(const G4Text& text) {
#ifdef G4QT3DDEBUG
G4cout <<
"G4Qt3DSceneHandler::AddPrimitive(const G4Text& text) called.\n"
<< text
<< G4endl;
#endif
static G4bool first = true;
if (first) {
first = false;
G4Exception("G4Qt3DSceneHandler::AddPrimitive(const G4Text& text)",
"qt3D-0002", JustWarning,
"Text drawing not yet implemented");
}
return;
auto currentNode = CreateNewNode();
if (!currentNode) return; // Node not available
fpVisAttribs = fpViewer->GetApplicableVisAttributes(text.GetVisAttributes());
auto position = fObjectTransformation*G4Translate3D(text.GetPosition());
auto transform = G4Qt3DUtils::CreateQTransformFrom(position);
transform->setScale(10);
// This simply does not work
// auto qtext = new Qt3DExtras::QText2DEntity(currentNode);
// qtext->setText(text.GetText().c_str());
// qtext->setHeight(100);
// qtext->setWidth(1000);
// qtext->setColor(Qt::green);
// qtext->setFont(QFont("Courier New", 10));
//
// qtext->addComponent(transform);
// qtext->addComponent(material);
// This produces text in 3D facing +z - not what we want
const auto& colour = GetTextColour(text);
auto material = new Qt3DExtras::QDiffuseSpecularMaterial();
material->setObjectName("materialForText");
material->setAmbient(G4Qt3DUtils::ConvertToQColor(colour));
if (colour.GetAlpha() < 1.) material->setAlphaBlendingEnabled(true);
auto textMesh = new Qt3DExtras::QExtrudedTextMesh();
textMesh->setText(text.GetText().c_str());
textMesh->setFont(QFont("Courier New", 10));
textMesh->setDepth(.01f);
currentNode->addComponent(material);
currentNode->addComponent(transform);
currentNode->addComponent(textMesh);
}
void G4Qt3DSceneHandler::AddPrimitive(const G4Circle& circle)
{
#ifdef G4QT3DDEBUG
G4cout <<
"G4Qt3DSceneHandler::AddPrimitive(const G4Circle& circle) called.\n"
<< circle
<< G4endl;
#endif
#ifdef G4QT3DDEBUG
MarkerSizeType sizeType;
G4double size = GetMarkerSize (circle, sizeType);
switch (sizeType) {
default:
case screen:
// Draw in screen coordinates.
G4cout << "screen";
break;
case world:
// Draw in world coordinates.
G4cout << "world";
break;
}
G4cout << " size: " << size << G4endl;
#endif
auto currentNode = CreateNewNode();
if (!currentNode) return; // Node not available
fpVisAttribs = fpViewer->GetApplicableVisAttributes(circle.GetVisAttributes());
auto position = fObjectTransformation*G4Translate3D(circle.GetPosition());
auto transform = G4Qt3DUtils::CreateQTransformFrom(position);
const auto& colour = fpVisAttribs->GetColour();
auto material = new Qt3DExtras::QDiffuseSpecularMaterial();
material->setObjectName("materialForCircle");
material->setAmbient(G4Qt3DUtils::ConvertToQColor(colour));
if (colour.GetAlpha() < 1.) material->setAlphaBlendingEnabled(true);
auto sphereMesh = new Qt3DExtras::QSphereMesh;
sphereMesh->setObjectName("sphereMesh");
G4double radius;
if (circle.GetSizeType() == G4VMarker::world ) {
radius =circle.GetWorldRadius();
} else { // Screen-size or none
// Not figured out how to do screen-size, so use scene extent
const G4double scale = 200.; // Roughly pixles per scene
radius = circle.GetScreenRadius()*fpScene->GetExtent().GetExtentRadius()/scale;
}
sphereMesh->setRadius(radius);
auto currentEntity = new Qt3DCore::QEntity(currentNode);
currentEntity->addComponent(material);
currentEntity->addComponent(transform);
currentEntity->addComponent(sphereMesh);
}
void G4Qt3DSceneHandler::AddPrimitive(const G4Square& square)
{
#ifdef G4QT3DDEBUG
G4cout <<
"G4Qt3DSceneHandler::AddPrimitive(const G4Square& square) called.\n"
<< square
<< G4endl;
#endif
#ifdef G4QT3DDEBUG
MarkerSizeType sizeType;
G4double size = GetMarkerSize (square, sizeType);
switch (sizeType) {
default:
case screen:
// Draw in screen coordinates.
G4cout << "screen";
break;
case world:
// Draw in world coordinates.
G4cout << "world";
break;
}
G4cout << " size: " << size << G4endl;
#endif
auto currentNode = CreateNewNode();
if (!currentNode) return; // Node not available
fpVisAttribs = fpViewer->GetApplicableVisAttributes(square.GetVisAttributes());
auto position = fObjectTransformation*G4Translate3D(square.GetPosition());
auto transform = G4Qt3DUtils::CreateQTransformFrom(position);
const auto& colour = fpVisAttribs->GetColour();
auto material = new Qt3DExtras::QDiffuseSpecularMaterial();
material->setObjectName("materialForSquare");
material->setAmbient(G4Qt3DUtils::ConvertToQColor(colour));
if (colour.GetAlpha() < 1.) material->setAlphaBlendingEnabled(true);
auto boxMesh = new Qt3DExtras::QCuboidMesh();
boxMesh->setObjectName("boxMesh");
G4double side;
if (square.GetSizeType() == G4VMarker::world ) {
side = square.GetWorldDiameter();
} else { // Screen-size or none
// Not figured out how to do screen-size, so use scene extent
const G4double scale = 200.; // Roughly pixles per scene
side = square.GetScreenDiameter()*fpScene->GetExtent().GetExtentRadius()/scale;
}
boxMesh->setXExtent(side);
boxMesh->setYExtent(side);
boxMesh->setZExtent(side);
auto currentEntity = new Qt3DCore::QEntity(currentNode);
currentEntity->addComponent(material);
currentEntity->addComponent(transform);
currentEntity->addComponent(boxMesh);
}
void G4Qt3DSceneHandler::AddPrimitive(const G4Polyhedron& polyhedron)
{
auto currentNode = CreateNewNode();
if (!currentNode) return; // Node not available
if (polyhedron.GetNoFacets() == 0) return;
fpVisAttribs = fpViewer->GetApplicableVisAttributes(polyhedron.GetVisAttributes());
// Roll out vertices and normals for the faces. Note that this means vertices
// are duplicated. For example a box has 8 vertices, but to define 6 faces
// you need 12 triangles and 36 vertices. If it was just a matter of vertices
// we could restrict the number to 8 and use the indices to define the
// triangles, but we also have to consider the normals. A vertex can be have
// more than one normal, depending on which face it is being used to define.
// So we roll out all the vertices and normals for each triangle.
std::vector<G4Point3D> vertices;
std::vector<G4Normal3D> normals;
// Also roll out edges (as lines) for wireframe. Avoid duplicate lines,
// including those that differ only in the order of vertices.
typedef std::pair<G4Point3D,G4Point3D> Line;
std::vector<Line> lines;
auto insertIfNew = [&lines](const Line& newLine) {
for (const auto& line: lines) {
if ((newLine.first==line.first && newLine.second==line.second) ||
(newLine.first==line.second && newLine.second==line.first))
return;
}
lines.push_back(newLine);
};
G4bool notLastFace;
do {
G4int nEdges;
G4Point3D vertex [4];
G4int edgeFlag[4];
G4Normal3D normal [4];
notLastFace = polyhedron.GetNextFacet(nEdges, vertex, edgeFlag, normal);
vertices.push_back(vertex[0]);
vertices.push_back(vertex[1]);
vertices.push_back(vertex[2]);
normals.push_back(normal[0]);
normals.push_back(normal[1]);
normals.push_back(normal[2]);
insertIfNew(Line(vertex[0],vertex[1]));
insertIfNew(Line(vertex[1],vertex[2]));
if (nEdges == 3) {
// Face is a triangle
// One more line for wireframe, triangles for surfaces are complete
insertIfNew(Line(vertex[2],vertex[0]));
} else if (nEdges == 4) {
// Face is a quadrilateral
// Create another triangle for surfaces, add two more lines for wireframe
vertices.push_back(vertex[2]);
vertices.push_back(vertex[3]);
vertices.push_back(vertex[0]);
normals.push_back(normal[2]);
normals.push_back(normal[3]);
normals.push_back(normal[0]);
insertIfNew(Line(vertex[2],vertex[3]));
insertIfNew(Line(vertex[3],vertex[0]));
} else {
G4cerr << "ERROR: polyhedron face with more than 4 edges" << G4endl;
return;
}
} while (notLastFace);
const auto nVerts = vertices.size();
const auto nLines = lines.size();
// Now put stuff into Qt objects
auto transform = G4Qt3DUtils::CreateQTransformFrom(fObjectTransformation);
transform->setObjectName("transform");
Qt3DCore::QEntity* wireframeEntity = nullptr;
Qt3DCore::QEntity* surfaceEntity = nullptr;
static G4int errorCount = 0;
G4ViewParameters::DrawingStyle drawing_style = GetDrawingStyle (fpVisAttribs);
switch (drawing_style) {
case G4ViewParameters::wireframe:
wireframeEntity = new Qt3DCore::QEntity(currentNode);
wireframeEntity->addComponent(transform);
break;
case G4ViewParameters::hlr:
wireframeEntity = new Qt3DCore::QEntity(currentNode);
wireframeEntity->addComponent(transform);
surfaceEntity = new Qt3DCore::QEntity(currentNode);
surfaceEntity->addComponent(transform);
break;
case G4ViewParameters::hsr:
surfaceEntity = new Qt3DCore::QEntity(currentNode);
surfaceEntity->addComponent(transform);
break;
case G4ViewParameters::hlhsr:
wireframeEntity = new Qt3DCore::QEntity(currentNode);
wireframeEntity->addComponent(transform);
surfaceEntity = new Qt3DCore::QEntity(currentNode);
surfaceEntity->addComponent(transform);
break;
case G4ViewParameters::cloud:
// Shouldn't happen in this function (it's a polyhedron!)
if (errorCount == 0) {
++errorCount;
G4cerr << "WARNING: Qt3D: cloud drawing not implemented" << G4endl;
}
return;
break;
}
const auto vertexByteSize = 3*sizeof(PRECISION);
Qt3DRender::QGeometry* vertexGeometry = nullptr;
Qt3DRender::QGeometry* lineGeometry = nullptr;
Qt3DRender::QAttribute* positionAtt = nullptr;
Qt3DRender::QAttribute* normalAtt = nullptr;
Qt3DRender::QAttribute* lineAtt = nullptr;
Qt3DRender::QBuffer* vertexBuffer = nullptr;
if (drawing_style == G4ViewParameters::hlr ||
drawing_style == G4ViewParameters::hsr ||
drawing_style == G4ViewParameters::hlhsr) {
// Put vertices, normals into QByteArray
// Accomodates both vertices and normals - hence 2*
QByteArray vertexByteArray;
const auto vertexBufferByteSize = 2*nVerts*vertexByteSize;
vertexByteArray.resize(vertexBufferByteSize);
auto vertexBufferArray = reinterpret_cast<PRECISION*>(vertexByteArray.data());
G4int i1 = 0;
for (size_t i = 0; i < nVerts; i++) {
vertexBufferArray[i1++] = vertices[i].x();
vertexBufferArray[i1++] = vertices[i].y();
vertexBufferArray[i1++] = vertices[i].z();
vertexBufferArray[i1++] = normals[i].x();
vertexBufferArray[i1++] = normals[i].y();
vertexBufferArray[i1++] = normals[i].z();
}
// Vertex buffer (vertices and normals)
vertexGeometry = new Qt3DRender::QGeometry();
vertexGeometry->setObjectName("vertexGeometry");
vertexBuffer = new Qt3DRender::QBuffer(vertexGeometry);
vertexBuffer->setObjectName("Vertex buffer");
vertexBuffer->setData(vertexByteArray);
// Position attribute
positionAtt = new Qt3DRender::QAttribute;
positionAtt->setObjectName("Position attribute");
positionAtt->setName(Qt3DRender::QAttribute::defaultPositionAttributeName());
positionAtt->setBuffer(vertexBuffer);
positionAtt->setAttributeType(Qt3DRender::QAttribute::VertexAttribute);
positionAtt->setVertexBaseType(BASETYPE);
positionAtt->setVertexSize(3);
positionAtt->setCount(nVerts);
positionAtt->setByteOffset(0);
positionAtt->setByteStride(2*vertexByteSize);
// Normal attribute
normalAtt = new Qt3DRender::QAttribute;
normalAtt->setObjectName("Normal attribute");
normalAtt->setName(Qt3DRender::QAttribute::defaultNormalAttributeName());
normalAtt->setBuffer(vertexBuffer);
normalAtt->setAttributeType(Qt3DRender::QAttribute::VertexAttribute);
normalAtt->setVertexBaseType(BASETYPE);
normalAtt->setVertexSize(3);
normalAtt->setCount(nVerts);
normalAtt->setByteOffset(vertexByteSize);
normalAtt->setByteStride(2*vertexByteSize);
}
Qt3DRender::QBuffer* lineBuffer = nullptr;
if (drawing_style == G4ViewParameters::wireframe ||
drawing_style == G4ViewParameters::hlr ||
drawing_style == G4ViewParameters::hlhsr) {
// Put lines into a QByteArray
QByteArray lineByteArray;
const auto lineBufferByteSize = 2*nLines*vertexByteSize;
lineByteArray.resize(lineBufferByteSize);
auto lineBufferArray = reinterpret_cast<PRECISION*>(lineByteArray.data());
G4int i2 = 0;
for (const auto& line: lines) {
lineBufferArray[i2++] = line.first.x();
lineBufferArray[i2++] = line.first.y();
lineBufferArray[i2++] = line.first.z();
lineBufferArray[i2++] = line.second.x();
lineBufferArray[i2++] = line.second.y();
lineBufferArray[i2++] = line.second.z();
}
// Line loop buffer
lineGeometry = new Qt3DRender::QGeometry();
lineGeometry->setObjectName("lineGeometry");
lineBuffer = new Qt3DRender::QBuffer(lineGeometry);
lineBuffer->setObjectName("Line buffer");
lineBuffer->setData(lineByteArray);
// Line attribute
lineAtt = new Qt3DRender::QAttribute;
lineAtt->setObjectName("Position attribute");
lineAtt->setName(Qt3DRender::QAttribute::defaultPositionAttributeName());
lineAtt->setBuffer(lineBuffer);
lineAtt->setAttributeType(Qt3DRender::QAttribute::VertexAttribute);
lineAtt->setVertexBaseType(BASETYPE);
lineAtt->setVertexSize(3);
lineAtt->setCount(nLines);
lineAtt->setByteOffset(0);
lineAtt->setByteStride(vertexByteSize);
}
// Create material and renderer(s)...
const auto& colour = fpVisAttribs->GetColour();
Qt3DExtras::QDiffuseSpecularMaterial* material;
Qt3DRender::QGeometryRenderer* renderer;
switch (drawing_style) {
case G4ViewParameters::wireframe:
lineGeometry->addAttribute(lineAtt);
material = new Qt3DExtras::QDiffuseSpecularMaterial();
material->setObjectName("materialForWireframe");
material->setAmbient(G4Qt3DUtils::ConvertToQColor(colour));
material->setShininess(0.);
material->setSpecular(0.);
wireframeEntity->addComponent(material);
renderer = new Qt3DRender::QGeometryRenderer;
renderer->setObjectName("polyhedronWireframeRenderer");
renderer->setGeometry(lineGeometry);
renderer->setVertexCount(2*nLines);
renderer->setPrimitiveType(Qt3DRender::QGeometryRenderer::Lines);
wireframeEntity->addComponent(renderer);
break;
case G4ViewParameters::hlr:
// Surfaces with background colour to hide the edges
vertexGeometry->addAttribute(positionAtt);
vertexGeometry->addAttribute(normalAtt);
material = new Qt3DExtras::QDiffuseSpecularMaterial();
material->setObjectName("materialForHiddenLines");
material->setAmbient(Qt::white); // White for now (should be from fVP)
material->setShininess(0.);
material->setSpecular(0.);
surfaceEntity->addComponent(material);
renderer = new Qt3DRender::QGeometryRenderer;
renderer->setObjectName("polyhedronSurfaceRenderer");
renderer->setGeometry(vertexGeometry);
renderer->setVertexCount(nVerts);
renderer->setPrimitiveType(Qt3DRender::QGeometryRenderer::Triangles);
surfaceEntity->addComponent(renderer);
// Edges
lineGeometry->addAttribute(lineAtt);
material = new Qt3DExtras::QDiffuseSpecularMaterial();
material->setObjectName("materialForWireFrame");
material->setAmbient(G4Qt3DUtils::ConvertToQColor(colour));
material->setShininess(0.);
material->setSpecular(0.);
wireframeEntity->addComponent(material);
renderer = new Qt3DRender::QGeometryRenderer;
renderer->setObjectName("polyhedronWireframeRenderer");
renderer->setGeometry(lineGeometry);
renderer->setVertexCount(2*nLines);
renderer->setPrimitiveType(Qt3DRender::QGeometryRenderer::Lines);
wireframeEntity->addComponent(renderer);
break;
case G4ViewParameters::hsr:
vertexGeometry->addAttribute(positionAtt);
vertexGeometry->addAttribute(normalAtt);
material = new Qt3DExtras::QDiffuseSpecularMaterial();
material->setObjectName("materialForSurface");
material->setAmbient(G4Qt3DUtils::ConvertToQColor(colour));
if (colour.GetAlpha() < 1.) material->setAlphaBlendingEnabled(true);
surfaceEntity->addComponent(material);
renderer = new Qt3DRender::QGeometryRenderer;
renderer->setObjectName("polyhedronSurfaceRenderer");
renderer->setGeometry(vertexGeometry);
renderer->setVertexCount(nVerts);
renderer->setPrimitiveType(Qt3DRender::QGeometryRenderer::Triangles);
surfaceEntity->addComponent(renderer);
break;
case G4ViewParameters::hlhsr:
// Surfaces
vertexGeometry->addAttribute(positionAtt);
vertexGeometry->addAttribute(normalAtt);
material = new Qt3DExtras::QDiffuseSpecularMaterial();
material->setObjectName("materialForSurface");
material->setAmbient(G4Qt3DUtils::ConvertToQColor(colour));
if (colour.GetAlpha() < 1.) material->setAlphaBlendingEnabled(true);
surfaceEntity->addComponent(material);
renderer = new Qt3DRender::QGeometryRenderer;
renderer->setObjectName("polyhedronSurfaceRenderer");
renderer->setGeometry(vertexGeometry);
renderer->setVertexCount(nVerts);
renderer->setPrimitiveType(Qt3DRender::QGeometryRenderer::Triangles);
surfaceEntity->addComponent(renderer);
// Edges
lineGeometry->addAttribute(lineAtt);
material = new Qt3DExtras::QDiffuseSpecularMaterial();
material->setObjectName("materialForWireframe");
material->setAmbient(G4Qt3DUtils::ConvertToQColor(colour));
material->setShininess(0.);
material->setSpecular(0.);
wireframeEntity->addComponent(material);
renderer = new Qt3DRender::QGeometryRenderer;
renderer->setObjectName("polyhedronSurfaceRenderer");
renderer->setGeometry(lineGeometry);
renderer->setVertexCount(2*nLines);
renderer->setPrimitiveType(Qt3DRender::QGeometryRenderer::Lines);
wireframeEntity->addComponent(renderer);
break;
case G4ViewParameters::cloud:
// Case trapped at start of function, so no need to implement
break;
}
}
void G4Qt3DSceneHandler::ClearStore ()
{
G4Qt3DUtils::delete_components_and_children_of_entity_recursively(fpQt3DScene);
EstablishG4Qt3DQEntities();
}
void G4Qt3DSceneHandler::ClearTransientStore ()
{
G4Qt3DUtils::delete_components_and_children_of_entity_recursively(fpTransientObjects);
}
#endif // #if defined (G4VIS_BUILD_QT3D_DRIVER) || defined (G4VIS_USE_QT3D)
@@ -0,0 +1,182 @@
//
// ********************************************************************
// * License and Disclaimer *
// * *
// * The Geant4 software is copyright of the Copyright Holders of *
// * the Geant4 Collaboration. It is provided under the terms and *
// * conditions of the Geant4 Software License, included in the file *
// * LICENSE and available at http://cern.ch/geant4/license . These *
// * include a list of copyright holders. *
// * *
// * Neither the authors of this software system, nor their employing *
// * institutes,nor the agencies providing financial support for this *
// * work make any representation or warranty, express or implied, *
// * regarding this software system or assume any liability for its *
// * use. Please see the license in the file LICENSE and URL above *
// * for the full disclaimer and the limitation of liability. *
// * *
// * This code implementation is the result of the scientific and *
// * technical work of the GEANT4 collaboration. *
// * By using, copying, modifying or distributing the software (or *
// * any work based on the software) you agree to acknowledge its *
// * use in resulting scientific publications, and indicate your *
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
// John Allison, 18th July 2020
#if defined (G4VIS_BUILD_QT3D_DRIVER) || defined (G4VIS_USE_QT3D)
#include "G4Qt3DUtils.hh"
#include "G4Qt3DQEntity.hh"
#include "G4PhysicalVolumeModel.hh"
Qt3DCore::QTransform* G4Qt3DUtils::CreateQTransformFrom(const G4Transform3D& g)
{
auto* q = new Qt3DCore::QTransform;
q->setMatrix
(QMatrix4x4
(g.xx(),g.xy(),g.xz(),g.dx(),
g.yx(),g.yy(),g.yz(),g.dy(),
g.zx(),g.zy(),g.zz(),g.dz(),
0,0,0,1));
q->setObjectName("transform");
return q;
}
QColor G4Qt3DUtils::ConvertToQColor(const G4Colour& c) {
QColor qColor;
qColor.setRgbF(c.GetRed(),c.GetGreen(),c.GetBlue(),c.GetAlpha());
return qColor;
}
QVector3D G4Qt3DUtils::ConvertToQVector3D(const G4ThreeVector& v) {
return QVector3D(v.x(),v.y(),v.z());
}
// https://stackoverflow.com/questions/45759274/how-can-i-delete-all-nodes-recursively-in-the-root-entity-of-qt3dwindow
void G4Qt3DUtils::delete_entity_recursively(Qt3DCore::QNode *node){
#ifdef G4QT3DDEBUG
G4Qt3DUtils::LogFile << "node " << node->objectName().toStdString() << std::endl;
#endif
Qt3DCore::QEntity* entity = dynamic_cast<Qt3DCore::QEntity*>(node);
if(entity == nullptr){
G4String name = node->objectName().toStdString();
if (name == "") name = "X";
#ifdef G4QT3DDEBUG
G4Qt3DUtils::LogFile << (void*)node << ": "
<< "Deleting non-entity node " << name << std::endl;
#endif
delete node;
node = nullptr;
return;
}
for (auto component: entity->components()) {
G4String name = component->objectName().toStdString();
if (name == "") name = "X";
#ifdef G4QT3DDEBUG
G4Qt3DUtils::LogFile << (void*)node << ": " << "Deleting component " << name
<< " of " << entity->objectName().toStdString() << std::endl;
#endif
entity->removeComponent(component);
delete component;
component = nullptr;
}
for (auto child_node: entity->childNodes()) {
G4String name = child_node->objectName().toStdString();
if (name == "") name = "X";
#ifdef G4QT3DDEBUG
G4Qt3DUtils::LogFile << (void*)child_node << ": " << "Child node " << name
<< " of " << entity->objectName().toStdString() << std::endl;
#endif
delete_entity_recursively(child_node);
}
G4String name = entity->objectName().toStdString();
if (name == "") name = "X";
#ifdef G4QT3DDEBUG
G4Qt3DUtils::LogFile << (void*)entity << ": " << "Deleting entity " << name << std::endl;
#endif
delete entity;
entity = nullptr;
}
void G4Qt3DUtils::delete_components_and_children_of_entity_recursively(Qt3DCore::QNode *node){
Qt3DCore::QEntity* entity = dynamic_cast<Qt3DCore::QEntity*>(node);
if(entity == nullptr){
G4String name = node->objectName().toStdString();
if (name == "") name = "X";
#ifdef G4QT3DDEBUG
G4Qt3DUtils::LogFile << (void*)node << ": " << "Found non-entity node " << name << std::endl;
#endif
return;
}
for (auto component: entity->components()){
G4String name = component->objectName().toStdString();
if (name == "") name = "X";
#ifdef G4QT3DDEBUG
G4Qt3DUtils::LogFile << (void*)entity << ": " << "Deleting component " << name
<< " of " << entity->objectName().toStdString() << std::endl;
#endif
entity->removeComponent(component);
delete(component);
component = nullptr;
}
auto child_nodes = entity->childNodes();
for (auto child_node: child_nodes) {
G4String name = child_node->objectName().toStdString();
if (name == "") name = "X";
#ifdef G4QT3DDEBUG
G4Qt3DUtils::LogFile << (void*)child_node << ": " << "Child node " << name
<< " of " << entity->objectName().toStdString() << std::endl;
#endif
delete_entity_recursively(child_node);
}
G4String name = entity->objectName().toStdString();
if (name == "") name = "X";
#ifdef G4QT3DDEBUG
G4Qt3DUtils::LogFile << (void*)entity << ": " << "Clearing child nodes of " << name << std::endl;
#endif
child_nodes.clear();
}
#ifdef G4QT3DDEBUG
std::ofstream G4Qt3DUtils::LogFile("LogFile.txt");
void G4Qt3DUtils::PrintQObjectTree
(const QObject* node,
const G4String& where)
{
auto& logFile = G4Qt3DUtils::LogFile;
if (where.length()) logFile << "\n===== QObjectTree at " << where << std::endl;
static G4int iDep = -1;
++iDep;
const auto* g4node = dynamic_cast<const G4Qt3DQEntity*>(node);
G4String nodeName = node->objectName().toStdString();
if (nodeName == "") nodeName = "X";
for (G4int i = 0; i < iDep; ++i) logFile << " ";
logFile << (void*)node << ": "
<< "Node at depth " << iDep << ": " << nodeName << ": ";
if (g4node) {
logFile << g4node->GetPVNodeID() << std::endl;
} else {
logFile << typeid(node).name() << std::endl;
}
if (g4node) {
for (const auto& component: g4node->components()) {
G4String name = component->objectName().toStdString();
if (name == "") name = "X";
for (G4int i = 0; i < iDep; ++i) logFile << " ";
logFile << (void*)component << ": "<< "Component at depth " << iDep << " "
<< name << " of " << nodeName << std::endl;
}
}
for (const auto& child: node->children()) {
PrintQObjectTree(child);
}
--iDep;
if (where.length()) logFile << "===== End: QObjectTree at " << where << std::endl;
return;
}
#endif
#endif // #if defined (G4VIS_BUILD_QT3D_DRIVER) || defined (G4VIS_USE_QT3D)
@@ -0,0 +1,361 @@
//
// ********************************************************************
// * License and Disclaimer *
// * *
// * The Geant4 software is copyright of the Copyright Holders of *
// * the Geant4 Collaboration. It is provided under the terms and *
// * conditions of the Geant4 Software License, included in the file *
// * LICENSE and available at http://cern.ch/geant4/license . These *
// * include a list of copyright holders. *
// * *
// * Neither the authors of this software system, nor their employing *
// * institutes,nor the agencies providing financial support for this *
// * work make any representation or warranty, express or implied, *
// * regarding this software system or assume any liability for its *
// * use. Please see the license in the file LICENSE and URL above *
// * for the full disclaimer and the limitation of liability. *
// * *
// * This code implementation is the result of the scientific and *
// * technical work of the GEANT4 collaboration. *
// * By using, copying, modifying or distributing the software (or *
// * any work based on the software) you agree to acknowledge its *
// * use in resulting scientific publications, and indicate your *
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
// John Allison 17th June 2019
#if defined (G4VIS_BUILD_QT3D_DRIVER) || defined (G4VIS_USE_QT3D)
#include "G4Qt3DViewer.hh"
#include "G4Qt3DSceneHandler.hh"
#include "G4Qt3DUtils.hh"
#include "G4Scene.hh"
#include "G4UImanager.hh"
#include "G4UIQt.hh"
#include "G4SystemOfUnits.hh"
G4Qt3DViewer::G4Qt3DViewer
(G4Qt3DSceneHandler& sceneHandler, const G4String& name)
: G4VViewer(sceneHandler, sceneHandler.IncrementViewCount(), name)
, fQt3DSceneHandler(sceneHandler)
, fKeyPressed(false)
, fMousePressed(false)
, fMousePressedX(0.)
, fMousePressedY(0.)
{
setObjectName(fName.c_str());
fVP.SetAutoRefresh(true);
fDefaultVP.SetAutoRefresh(true);
// Background is white (not figured out how to change it) so...
fVP.SetDefaultColour(G4Colour::Black());
fDefaultVP.SetDefaultColour(G4Colour::Black());
auto UI = G4UImanager::GetUIpointer();
auto uiQt = dynamic_cast<G4UIQt*>(UI->GetG4UIWindow());
if (!uiQt) {
fViewId = -1; // This flags an error.
G4cerr << "G4Qt3DViewer::G4Qt3DViewer requires G4UIQt"
<< G4endl;
return;
}
fUIWidget = QWidget::createWindowContainer(this);
uiQt->AddTabWidget(fUIWidget,QString(fName));
setRootEntity(fQt3DSceneHandler.fpQt3DScene);
}
G4Qt3DViewer::~G4Qt3DViewer()
{}
void G4Qt3DViewer::SetView()
{
// Get radius of scene, etc.
// Note that this procedure properly takes into account zoom, dolly and pan.
const G4Point3D targetPoint
= fSceneHandler.GetScene()->GetStandardTargetPoint()
+ fVP.GetCurrentTargetPoint ();
G4double radius = fSceneHandler.GetScene()->GetExtent().GetExtentRadius();
if(radius<=0.) radius = 1.;
const G4double cameraDistance = fVP.GetCameraDistance (radius);
const G4Point3D cameraPosition =
targetPoint + cameraDistance * fVP.GetViewpointDirection().unit();
const GLdouble pnear = fVP.GetNearDistance (cameraDistance, radius);
const GLdouble pfar = fVP.GetFarDistance (cameraDistance, pnear, radius);
const GLdouble right = fVP.GetFrontHalfHeight (pnear, radius);
const GLdouble left = -right;
const GLdouble top = fVP.GetFrontHalfHeight (pnear, radius);
const GLdouble bottom = -top;
camera()->setObjectName((fName + " camera").c_str());
camera()->setViewCenter(G4Qt3DUtils::ConvertToQVector3D(targetPoint));
camera()->setPosition(G4Qt3DUtils::ConvertToQVector3D(cameraPosition));
camera()->setUpVector(G4Qt3DUtils::ConvertToQVector3D(fVP.GetUpVector()));
// auto lightEntity = new Qt3DCore::QEntity(fQt3DSceneHandler.fpQt3DScene);
// auto directionalLight = new Qt3DRender::QDirectionalLight(lightEntity);
//// directionalLight->setColor("white");
//// directionalLight->setIntensity(1.);
// directionalLight->setWorldDirection(G4Qt3DUtils::ConvertToQVector3D(fVP.GetActualLightpointDirection()));
// lightEntity->addComponent(directionalLight);
const auto& size = fUIWidget->size();
G4double w = size.width();
G4double h = size.height();
#ifdef G4QT3DDEBUG
// Curiously w,h are wrong first time - 640,480 instead of (my Mac) 991,452.
G4cout << "W,H: " << w << ',' << h << G4endl;
#endif
const G4double aspectRatio = w/h;
if (fVP.GetFieldHalfAngle() == 0.) {
camera()->lens()->setOrthographicProjection
(left*aspectRatio,right*aspectRatio,bottom,top,pnear,pfar);
} else {
camera()->lens()->setPerspectiveProjection
(2.*fVP.GetFieldHalfAngle()/deg,aspectRatio,pnear,pfar);
}
}
void G4Qt3DViewer::ClearView()
{}
void G4Qt3DViewer::DrawView()
{
// First, a view should decide when to re-visit the G4 kernel.
// Sometimes it might not be necessary, e.g., if the scene is stored
// in a graphical database (e.g., OpenGL's display lists) and only
// the viewing angle has changed. But graphics systems without a
// graphical database will always need to visit the G4 kernel.
// The fNeedKernelVisit flag might have been set by the user in
// /vis/viewer/rebuild, but if not, make decision and set flag only
// if necessary...
if (!fNeedKernelVisit) KernelVisitDecision();
G4bool kernelVisitWasNeeded = fNeedKernelVisit; // Keep (ProcessView resets).
fLastVP = fVP;
ProcessView (); // Clears store and processes scene only if necessary.
if (kernelVisitWasNeeded) {
// We might need to do something if the kernel was visited.
} else {
}
// ...before finally...
FinishView (); // Flush streams and/or swap buffers.
}
void G4Qt3DViewer::ShowView()
{
show();
}
void G4Qt3DViewer::FinishView()
{
show();
}
void G4Qt3DViewer::SwitchToVisSubThread()
{
// fUIWidget->moveToThread(QThread::currentThread());
// moveToThread(QThread::currentThread());
// fQt3DSceneHandler.fpQt3DScene->moveToThread(QThread::currentThread());
// fQt3DSceneHandler.fpTransientObjects->moveToThread(QThread::currentThread());
#ifdef G4QT3DDEBUG
// G4cout
// << "G4Qt3DViewer::SwitchToVisSubThread: (void*)fQt3DSceneHandler.fpQt3DScene: "
// << (void*)fQt3DSceneHandler.fpQt3DScene
// << G4endl;
#endif
}
void G4Qt3DViewer::SwitchToMasterThread()
{
// fUIWidget->moveToThread(QThread::currentThread());
// moveToThread(QThread::currentThread());
// fQt3DSceneHandler.fpQt3DScene->moveToThread(QThread::currentThread());
// fQt3DSceneHandler.fpTransientObjects->moveToThread(QThread::currentThread());
#ifdef G4QT3DDEBUG
// G4cout
// << "G4Qt3DViewer::SwitchToMasterThread: (void*)fQt3DSceneHandler.fpQt3DScene: "
// << (void*)fQt3DSceneHandler.fpQt3DScene
// << G4endl;
#endif
#ifdef G4MULTITHREADED
if (G4Threading::IsMultithreadedApplication()) {
// I have not figured out how to draw during a run. In fact, even attempting
// to fill nodes gives the error "Cannot create children for a parent that
// is in a different thread." So instead draw events from kept events.
//
// Setting fNeedKernelVisit=true causes scene deletion and a complete rebuild,
// including trajectories, hits, etc. from kept events.
//
// Clearly this is a limitation because even if you run 1000 events you only
// get those kept (default 100), and even worse, if end-if-event-action is
// "refresh", you only get one event (the last I think).
//
// Also, strictly, there is no need to rebuid run-duration models (detector),
// but a complete rebuild is the easiest way (already imeplemented).
fNeedKernelVisit = true;
DrawView(); // Draw trajectories, etc., from kept events
}
#endif
}
void G4Qt3DViewer::KernelVisitDecision () {
// If there's a significant difference with the last view parameters
// of either the scene handler or this viewer, trigger a rebuild.
if (CompareForKernelVisit(fLastVP)) {
NeedKernelVisit (); // Sets fNeedKernelVisit.
}
}
G4bool G4Qt3DViewer::CompareForKernelVisit(G4ViewParameters& lastVP)
{
// Typical comparison. Taken from OpenGL.
if (
(lastVP.GetDrawingStyle () != fVP.GetDrawingStyle ()) ||
(lastVP.GetNumberOfCloudPoints() != fVP.GetNumberOfCloudPoints()) ||
(lastVP.IsAuxEdgeVisible () != fVP.IsAuxEdgeVisible ()) ||
(lastVP.IsCulling () != fVP.IsCulling ()) ||
(lastVP.IsCullingInvisible () != fVP.IsCullingInvisible ()) ||
(lastVP.IsDensityCulling () != fVP.IsDensityCulling ()) ||
(lastVP.IsCullingCovered () != fVP.IsCullingCovered ()) ||
(lastVP.GetCBDAlgorithmNumber() !=
fVP.GetCBDAlgorithmNumber()) ||
(lastVP.IsSection () != fVP.IsSection ()) ||
(lastVP.IsCutaway () != fVP.IsCutaway ()) ||
(lastVP.IsExplode () != fVP.IsExplode ()) ||
(lastVP.GetNoOfSides () != fVP.GetNoOfSides ()) ||
(lastVP.GetGlobalMarkerScale() != fVP.GetGlobalMarkerScale()) ||
(lastVP.GetGlobalLineWidthScale() != fVP.GetGlobalLineWidthScale()) ||
(lastVP.IsMarkerNotHidden () != fVP.IsMarkerNotHidden ()) ||
(lastVP.GetDefaultVisAttributes()->GetColour() !=
fVP.GetDefaultVisAttributes()->GetColour()) ||
(lastVP.GetDefaultTextVisAttributes()->GetColour() !=
fVP.GetDefaultTextVisAttributes()->GetColour()) ||
(lastVP.GetBackgroundColour ()!= fVP.GetBackgroundColour ())||
(lastVP.IsPicking () != fVP.IsPicking ()) ||
(lastVP.GetVisAttributesModifiers() !=
fVP.GetVisAttributesModifiers())
) {
return true;
}
if (lastVP.IsDensityCulling () &&
(lastVP.GetVisibleDensity () != fVP.GetVisibleDensity ()))
return true;
if (lastVP.GetCBDAlgorithmNumber() > 0) {
if (lastVP.GetCBDParameters().size() != fVP.GetCBDParameters().size()) return true;
else if (lastVP.GetCBDParameters() != fVP.GetCBDParameters()) return true;
}
if (lastVP.IsExplode () &&
(lastVP.GetExplodeFactor () != fVP.GetExplodeFactor ()))
return true;
return false;
}
void G4Qt3DViewer::keyPressEvent(QKeyEvent* ev)
{
fKeyPressed = true;
fKey = ev->key();
}
void G4Qt3DViewer::keyReleaseEvent(QKeyEvent* /*ev*/)
{
fKeyPressed = false;
}
void G4Qt3DViewer::mouseDoubleClickEvent(QMouseEvent* /*ev*/) {}
void G4Qt3DViewer::mouseMoveEvent(QMouseEvent* ev)
{
// I think we only want these if a mouse button is pressed.
// But they come even when not pressed (on my MacBook Pro trackpad).
// Documentation says:
/* Mouse move events will occur only when a mouse button is pressed down,
unless mouse tracking has been enabled with QWidget::setMouseTracking().*/
// But this is a window not a widget.
// As a workaround we maintain a flag changed by mousePress/ReleaseEvent.
G4double x = ev->x();
G4double y = ev->y();
G4double dx = x-fMousePressedX;
G4double dy = y-fMousePressedY;
fMousePressedX = x;
fMousePressedY = y;
if (fMousePressed) {
if (fKeyPressed && fKey == Qt::Key_Shift) { // Translation (pan)
const G4double sceneRadius = fQt3DSceneHandler.fpScene->GetExtent().GetExtentRadius();
const G4double scale = 300; // Roughly pixels per window, empirically chosen
const G4double dxScene = dx*sceneRadius/scale;
const G4double dyScene = dy*sceneRadius/scale;
fVP.IncrementPan(-dxScene,dyScene);
} else { // Rotation
// Simple ad-hoc algorithms
const G4Vector3D& x_prime = fVP.GetViewpointDirection().cross(fVP.GetUpVector());
const G4Vector3D& y_prime = x_prime.cross(fVP.GetViewpointDirection());
const G4double scale = 200; // Roughly pixels per window, empirically chosen
G4Vector3D newViewpointDirection = fVP.GetViewpointDirection();
newViewpointDirection += dx*x_prime/scale;
newViewpointDirection += dy*y_prime/scale;
fVP.SetViewpointDirection(newViewpointDirection.unit());
if (fVP.GetRotationStyle() == G4ViewParameters::freeRotation) {
G4Vector3D newUpVector = fVP.GetUpVector();
newUpVector += dx*x_prime/scale;
newUpVector += dy*y_prime/scale;
fVP.SetUpVector(newUpVector.unit());
}
}
}
SetView();
DrawView();
}
void G4Qt3DViewer::mousePressEvent(QMouseEvent* ev)
{
fMousePressed = true;
fMousePressedX = ev->x();
fMousePressedY = ev->y();
}
void G4Qt3DViewer::mouseReleaseEvent(QMouseEvent* /*ev*/)
{
fMousePressed = false;
}
void G4Qt3DViewer::wheelEvent(QWheelEvent* ev)
{
// Take note of up-down motion only
const G4double angleY = ev->angleDelta().y();
if (fVP.GetFieldHalfAngle() == 0.) { // Orthographic projection
const G4double scale = 500; // Empirically chosen
fVP.MultiplyZoomFactor(1.+angleY/scale);
} else { // Perspective projection
const G4double scale = fVP.GetFieldHalfAngle()/(10.*deg); // Empirical
fVP.SetDolly(fVP.GetDolly()+angleY/scale);
}
SetView();
DrawView();
}
#endif // #if defined (G4VIS_BUILD_QT3D_DRIVER) || defined (G4VIS_USE_QT3D)