From cd3548a8b283b140ed366d8d54c4b216f3380b91 Mon Sep 17 00:00:00 2001 From: Markus Frank <markus.frank@cern.ch> Date: Thu, 14 Nov 2013 15:55:39 +0000 Subject: [PATCH] Please read the notes in doc/release.notes --- DDCore/include/DD4hep/DetFactoryHelper.h | 42 +- DDCore/include/DD4hep/Detector.h | 369 +-- DDCore/include/DD4hep/Factories.h | 93 +- DDCore/include/DD4hep/FieldTypes.h | 28 +- DDCore/include/DD4hep/Fields.h | 168 +- DDCore/include/DD4hep/GeoHandler.h | 68 +- DDCore/include/DD4hep/Handle.h | 268 +- DDCore/include/DD4hep/IDDescriptor.h | 68 +- DDCore/include/DD4hep/InstanceCount.h | 90 +- DDCore/include/DD4hep/LCDD.h | 158 +- DDCore/include/DD4hep/Objects.h | 339 ++- DDCore/include/DD4hep/Plugins.h | 8 +- DDCore/include/DD4hep/Primitives.h | 65 +- DDCore/include/DD4hep/Printout.h | 68 +- DDCore/include/DD4hep/Readout.h | 120 +- DDCore/include/DD4hep/Segmentations.h | 208 +- DDCore/include/DD4hep/Shapes.h | 506 ++-- DDCore/include/DD4hep/TGeoUnits.h | 620 ++-- DDCore/include/DD4hep/VolumeManager.h | 250 +- DDCore/include/DD4hep/Volumes.h | 228 +- DDCore/include/DD4hep/config.h | 8 +- DDCore/include/XML/Conversions.h | 64 +- DDCore/include/XML/DocumentHandler.h | 14 +- DDCore/include/XML/Evaluator.h | 479 ++- DDCore/include/XML/Layering.h | 85 +- DDCore/include/XML/UnicodeValues.h | 903 +++--- DDCore/include/XML/XMLDetector.h | 48 +- DDCore/include/XML/XMLDimension.h | 129 +- DDCore/include/XML/XMLElements.h | 534 ++-- DDCore/include/XML/XMLTags.h | 1 - DDCore/include/XML/config.h | 11 +- DDCore/include/XML/tinyxml.h | 3439 ++++++++++++---------- DDCore/src/Detector.cpp | 422 +-- DDCore/src/ExpressionEvaluator.cpp | 16 +- DDCore/src/FieldTypes.cpp | 25 +- DDCore/src/Fields.cpp | 80 +- DDCore/src/GeoHandler.cpp | 88 +- DDCore/src/GeometryTreeDump.cpp | 285 +- DDCore/src/GeometryTreeDump.h | 13 +- DDCore/src/Handle.cpp | 154 +- DDCore/src/IDDescriptor.cpp | 91 +- DDCore/src/InstanceCount.cpp | 64 +- DDCore/src/LCDDImp.cpp | 287 +- DDCore/src/LCDDImp.h | 353 ++- DDCore/src/MatrixHelpers.cpp | 32 +- DDCore/src/MatrixHelpers.h | 14 +- DDCore/src/Objects.cpp | 229 +- DDCore/src/Plugins.cpp | 12 +- DDCore/src/Printout.cpp | 202 +- DDCore/src/Readout.cpp | 55 +- DDCore/src/Segementations.cpp | 108 +- DDCore/src/Shapes.cpp | 428 +-- DDCore/src/SimpleGDMLWriter.cpp | 283 +- DDCore/src/SimpleGDMLWriter.h | 14 +- DDCore/src/VolumeManager.cpp | 657 ++--- DDCore/src/Volumes.cpp | 595 ++-- DDCore/src/XML/DocumentHandler.cpp | 306 +- DDCore/src/XML/Layering.cpp | 71 +- DDCore/src/XML/XMLDetector.cpp | 44 +- DDCore/src/XML/XMLDimension.cpp | 306 +- DDCore/src/XML/XMLElements.cpp | 701 +++-- DDCore/src/XML/XMLTags.cpp | 36 +- DDCore/src/plugins/Compact2Objects.cpp | 702 ++--- DDCore/src/plugins/Geant4XML.cpp | 18 +- DDCore/src/plugins/LCDD2Output.cpp | 58 +- DDCore/src/plugins/LCDDConverter.cpp | 1433 +++++---- DDCore/src/plugins/LCDDConverter.h | 132 +- DDCore/src/plugins/LCDDFields.cpp | 64 +- DDCore/src/plugins/PandoraConverter.cpp | 1414 +++++---- DDCore/src/plugins/StandardPlugins.cpp | 24 +- 70 files changed, 9979 insertions(+), 9316 deletions(-) diff --git a/DDCore/include/DD4hep/DetFactoryHelper.h b/DDCore/include/DD4hep/DetFactoryHelper.h index ac91cdc0c..49a04b363 100644 --- a/DDCore/include/DD4hep/DetFactoryHelper.h +++ b/DDCore/include/DD4hep/DetFactoryHelper.h @@ -1,6 +1,6 @@ // $Id$ //==================================================================== -// AIDA Detector description +// AIDA Detector description //-------------------------------------------------------------------- // // Author : M.Frank @@ -14,36 +14,34 @@ #include "DD4hep/Factories.h" // Shortcuts to elements of the XML namespace -typedef DD4hep::XML::Tag_t xml_tag_t; -typedef DD4hep::XML::Attribute xml_attr_t; -typedef DD4hep::XML::Collection_t xml_coll_t; -typedef DD4hep::XML::Handle_t xml_h; -typedef DD4hep::XML::Element xml_elt_t; -typedef DD4hep::XML::RefElement xml_ref_t; -typedef DD4hep::XML::DetElement xml_det_t; -typedef DD4hep::XML::Component xml_comp_t; -typedef DD4hep::XML::Dimension xml_dim_t; -typedef DD4hep::XML::Document xml_doc_t; -typedef DD4hep::XML::Strng_t Unicode; -typedef DD4hep::Geometry::LCDD lcdd_t; +typedef DD4hep::XML::Tag_t xml_tag_t; +typedef DD4hep::XML::Attribute xml_attr_t; +typedef DD4hep::XML::Collection_t xml_coll_t; +typedef DD4hep::XML::Handle_t xml_h; +typedef DD4hep::XML::Element xml_elt_t; +typedef DD4hep::XML::RefElement xml_ref_t; +typedef DD4hep::XML::DetElement xml_det_t; +typedef DD4hep::XML::Component xml_comp_t; +typedef DD4hep::XML::Dimension xml_dim_t; +typedef DD4hep::XML::Document xml_doc_t; +typedef DD4hep::XML::Strng_t Unicode; +typedef DD4hep::Geometry::LCDD lcdd_t; /* * DD4hep namespace declaration */ -namespace DD4hep { - +namespace DD4hep { + /* * Geometry sub-namespace declaration */ namespace Geometry { - static inline std::string _toString(const DD4hep::XML::XmlChar* value) - { - return XML::_toString(value); + static inline std::string _toString(const DD4hep::XML::XmlChar* value) { + return XML::_toString(value); } - - template <typename T> inline std::string _toString(T value, const char* fmt) - { - return XML::_toString(value, fmt); + + template <typename T> inline std::string _toString(T value, const char* fmt) { + return XML::_toString(value, fmt); } } } diff --git a/DDCore/include/DD4hep/Detector.h b/DDCore/include/DD4hep/Detector.h index d943e9300..494a9776d 100644 --- a/DDCore/include/DD4hep/Detector.h +++ b/DDCore/include/DD4hep/Detector.h @@ -25,78 +25,91 @@ * DD4hep namespace declaration */ namespace DD4hep { - + /* * Geometry namespace declaration */ - namespace Geometry { - + namespace Geometry { + // struct SensitiveDetector; // struct Detector; struct LCDD; - + /** @class SensitiveDetector Detector.h DD4hep/lcdd/Detector.h * * @author M.Frank * @version 1.0 */ - struct SensitiveDetector : public Ref_t { - public: + struct SensitiveDetector: public Ref_t { + public: /// Definition of the extension type - typedef std::map<const std::type_info*,void*> Extensions; + typedef std::map<const std::type_info*, void*> Extensions; - struct Object : public TNamed { + struct Object: public TNamed { unsigned int magic; - int verbose; - int combineHits; - double ecut; - std::string hitsCollection; - Readout readout; - Region region; - LimitSet limits; - Extensions extensions; + int verbose; + int combineHits; + double ecut; + std::string hitsCollection; + Readout readout; + Region region; + LimitSet limits; + Extensions extensions; /// Default constructor Object(); /// Internal object destructor: release extension object(s) virtual ~Object(); }; - protected: + protected: /// Templated destructor function - template <typename T> static void _delete(void* ptr) { delete (T*)(ptr); } + template <typename T> static void _delete(void* ptr) { + delete (T*) (ptr); + } /// Add an extension object to the detector element void* i_addExtension(void* ptr, const std::type_info& info, void (*destruct)(void*)); /// Access an existing extension object from the detector element - void* i_extension(const std::type_info& info) const; + void* i_extension(const std::type_info& info) const; - public: + public: /// Default constructor - SensitiveDetector() : Ref_t() {} + SensitiveDetector() + : Ref_t() { + } /// Copy from handle - SensitiveDetector(const SensitiveDetector& sd) : Ref_t(sd) {} - + SensitiveDetector(const SensitiveDetector& sd) + : Ref_t(sd) { + } + /// Copy from named handle - SensitiveDetector(const Ref_t& sd) : Ref_t(sd) {} - + SensitiveDetector(const Ref_t& sd) + : Ref_t(sd) { + } + /// Templated constructor for handle conversions template <typename Q> - SensitiveDetector(const Handle<Q>& e) : Ref_t(e) {} + SensitiveDetector(const Handle<Q>& e) + : Ref_t(e) { + } /// Constructor for a new sensitive detector element - SensitiveDetector(const std::string& name, const std::string& type="sensitive"); - + SensitiveDetector(const std::string& name, const std::string& type = "sensitive"); + /// Assignment operator - SensitiveDetector& operator=(const SensitiveDetector& sd) { m_element = sd.m_element; return *this; } + SensitiveDetector& operator=(const SensitiveDetector& sd) { + m_element = sd.m_element; + return *this; + } /// Access the type of the sensitive detector std::string type() const; - /// Set detector type (structure, tracker, calorimeter, etc.). + /// Set detector type (structure, tracker, calorimeter, etc.). SensitiveDetector& setType(const std::string& typ); /// Set flag to handle hits collection @@ -127,29 +140,31 @@ namespace DD4hep { SensitiveDetector& setEnergyCutoff(double value); /// Access energy cut off - double energyCutoff() const; + double energyCutoff() const; - /// Set the regional attributes to the sensitive detector + /// Set the regional attributes to the sensitive detector SensitiveDetector& setRegion(Region reg); /// Access to the region setting of the sensitive detector (not mandatory) Region region() const; - /// Set the limits to the sensitive detector + /// Set the limits to the sensitive detector SensitiveDetector& setLimitSet(LimitSet limits); - /// Access to the limit set of the sensitive detector (not mandatory). + /// Access to the limit set of the sensitive detector (not mandatory). LimitSet limits() const; /// Extend the sensitive detector element with an arbitrary structure accessible by the type - template<typename IFACE, typename CONCRETE> IFACE* addExtension(CONCRETE* c) - { return (IFACE*)i_addExtension(dynamic_cast<IFACE*>(c),typeid(IFACE),_delete<IFACE>); } + template <typename IFACE, typename CONCRETE> IFACE* addExtension(CONCRETE* c) { + return (IFACE*) i_addExtension(dynamic_cast<IFACE*>(c), typeid(IFACE), _delete<IFACE>); + } /// Access extension element by the type - template <class T> T* extension() const - { return (T*)i_extension(typeid(T)); } + template <class T> T* extension() const { + return (T*) i_extension(typeid(T)); + } }; - + /** @class SubDetector Detector.h DD4hep/lcdd/Detector.h * * The basic object type to access all information of a given @@ -159,48 +174,43 @@ namespace DD4hep { * @author M.Frank * @version 1.0 */ - struct DetElement : public Ref_t { - typedef Ref_t Parent; - typedef std::map<std::string,DetElement> Children; - typedef std::map<const std::type_info*,void*> Extensions; - - enum CopyParameters { - COPY_NONE = 0, - COPY_PLACEMENT = 1<<0, - COPY_PARENT = 1<<1, - COPY_ALIGNMENT = 1<<2, - LAST + struct DetElement: public Ref_t { + typedef Ref_t Parent; + typedef std::map<std::string, DetElement> Children; + typedef std::map<const std::type_info*, void*> Extensions; + + enum CopyParameters { + COPY_NONE = 0, COPY_PLACEMENT = 1 << 0, COPY_PARENT = 1 << 1, COPY_ALIGNMENT = 1 << 2, LAST }; - struct Object : public TNamed { - unsigned int magic; - int id; + struct Object: public TNamed { + unsigned int magic; + int id; /// Full path to this detector element. May be invalid - std::string path; - int combineHits; - Volume volume; - // Readout readout; - Alignment alignment; - Conditions conditions; - PlacedVolume placement; - Parent parent; - Parent reference; - Children children; - Extensions extensions; + std::string path; + int combineHits; + Volume volume; + Alignment alignment; + Conditions conditions; + PlacedVolume placement; + Parent parent; + Parent reference; + Children children; + Extensions extensions; /// Intermediate buffer to store the transformation to the world coordination system - TGeoMatrix* worldTrafo; + TGeoMatrix* worldTrafo; /// Intermediate buffer to store the transformation to the parent detector element - TGeoMatrix* parentTrafo; + TGeoMatrix* parentTrafo; /// Intermediate buffer for the transformation to an arbitrary DetElement - TGeoMatrix* referenceTrafo; + TGeoMatrix* referenceTrafo; /// The path to the placement of the detector element (if placed) - std::string placementPath; - + std::string placementPath; + /// Default constructor Object(); /// Internal object destructor: release extension object(s) virtual ~Object(); /// Deep object copy to replicate DetElement trees e.g. for reflection - virtual Object* clone(int new_id, int flag) const; + virtual Object* clone(int new_id, int flag) const; /// Conversion to reference object operator Ref_t(); /// Conversion to reference object @@ -212,176 +222,189 @@ namespace DD4hep { /// Create cached matrix to transform to reference coordinates TGeoMatrix* referenceTransformation(); }; - + /// Internal assert function to check conditions void check(bool condition, const std::string& msg) const; - + protected: - + /// Templated destructor function - template <typename T> static void _delete(void* ptr) { delete (T*)(ptr); } + template <typename T> static void _delete(void* ptr) { + delete (T*) (ptr); + } /// Templated copy constructor - template <typename T> static void* _copy(const void* ptr, DetElement elt) - { return new T(*(dynamic_cast<const T*>((T*)ptr)),elt); } - + template <typename T> static void* _copy(const void* ptr, DetElement elt) { + return new T(*(dynamic_cast<const T*>((T*) ptr)), elt); + } + /// Add an extension object to the detector element - void* i_addExtension(void* ptr, const std::type_info& info, void* (*copy)(const void*, DetElement), void (*destruct)(void*)); + void* i_addExtension(void* ptr, const std::type_info& info, void* (*copy)(const void*, DetElement), + void (*destruct)(void*)); /// Access an existing extension object from the detector element - void* i_extension(const std::type_info& info) const; - + void* i_extension(const std::type_info& info) const; + public: - + /// Default constructor - DetElement() : Ref_t() {} - + DetElement() + : Ref_t() { + } + /// Default constructor - template<typename Q> DetElement(Q* data, const std::string& name, const std::string& type) : Ref_t(data) - { this->assign(data, name, type); } - - template<typename Q> DetElement(const std::string& name, const std::string& type, int id, const Q&) - { assign(new Q(),name,type); - object<Object>().id = id; - } - + template <typename Q> DetElement(Q* data, const std::string& name, const std::string& type) + : Ref_t(data) { + this->assign(data, name, type); + } + + template <typename Q> DetElement(const std::string& name, const std::string& type, int id, const Q&) { + assign(new Q(), name, type); + object<Object>().id = id; + } + /// Construction function for a new subdetector element - template<typename Q> - static Q* createObject(const std::string& name, const std::string& type, int id) { - DetElement det; - Q *p = new Q(); + template <typename Q> + static Q* createObject(const std::string& name, const std::string& type, int id) { + DetElement det; + Q *p = new Q(); Object* o = p; - if ( o ) { // This should cause a compilation error if Q is - det.assign(p,name,type); // not a subclass of Object, which is mandatoryyyy - } - det.object<Object>().id = id; + if (o) { // This should cause a compilation error if Q is + det.assign(p, name, type); // not a subclass of Object, which is mandatoryyyy + } + det.object<Object>().id = id; return p; } /// Construction function for a new subdetector element - template<typename Q> - static DetElement create(const std::string& name, const std::string& type, int id, Q** ptr=0) { - Q* p = createObject<Q>(name,type,id); - if ( ptr ) *ptr = p; - return DetElement(Ref_t(p)); + template <typename Q> + static DetElement create(const std::string& name, const std::string& type, int id, Q** ptr = 0) { + Q* p = createObject<Q>(name, type, id); + if (ptr) + *ptr = p; + return DetElement(Ref_t(p)); } /// Templated constructor for handle conversions - template<typename Q> DetElement(const Handle<Q>& e) : Ref_t(e) {} - + template <typename Q> DetElement(const Handle<Q>& e) + : Ref_t(e) { + } + /// Constructor to copy handle - DetElement(const DetElement& e) : Ref_t(e) {} - + DetElement(const DetElement& e) + : Ref_t(e) { + } + /// Constructor for a new subdetector element DetElement(const std::string& name, const std::string& type, int id); - + /// Constructor for a new subdetector element DetElement(const std::string& name, int id); - + /// Constructor for a new subdetector element DetElement(DetElement parent, const std::string& name, int id); - + /// Additional data accessor - Object& _data() const { return object<Object>(); } + Object& _data() const { + return object<Object>(); + } /// Operator less to insert into a map - bool operator <(const DetElement e) const { return ptr() < e.ptr(); } + bool operator <(const DetElement e) const { + return ptr() < e.ptr(); + } /// Equality operator - bool operator ==(const DetElement e) const { return ptr() == e.ptr(); } + bool operator ==(const DetElement e) const { + return ptr() == e.ptr(); + } /// Assignment operator - DetElement& operator=(const DetElement& e) { m_element=e.m_element; return *this; } + DetElement& operator=(const DetElement& e) { + m_element = e.m_element; + return *this; + } /// Clone (Deep copy) the DetElement structure with a new name DetElement clone(const std::string& new_name) const; - + /// Clone (Deep copy) the DetElement structure with a new name and new identifier DetElement clone(const std::string& new_name, int new_id) const; - + /// Extend the detector element with an arbitrary structure accessible by the type - template<typename IFACE, typename CONCRETE> IFACE* addExtension(CONCRETE* c) - { return (IFACE*)i_addExtension(dynamic_cast<IFACE*>(c),typeid(IFACE),_copy<CONCRETE>,_delete<IFACE>); } - + template <typename IFACE, typename CONCRETE> IFACE* addExtension(CONCRETE* c) { + return (IFACE*) i_addExtension(dynamic_cast<IFACE*>(c), typeid(IFACE), _copy<CONCRETE>, _delete<IFACE>); + } + /// Access extension element by the type - template <class T> T* extension() const - { return (T*)i_extension(typeid(T)); } - + template <class T> T* extension() const { + return (T*) i_extension(typeid(T)); + } + /// Set the detector identifier - int id() const; + int id() const; /// Setter: Combine hits attribute - DetElement& setCombineHits(bool value, SensitiveDetector& sens); + DetElement& setCombineHits(bool value, SensitiveDetector& sens); /// Getter: Combine hits attribute - bool combineHits() const; - + bool combineHits() const; + /// Access detector type (structure, tracker, calorimeter, etc.). /** Required for determination of G4 sensitive detector. */ - std::string type() const; + std::string type() const; /// Set detector type (structure, tracker, calorimeter, etc.). - DetElement& setType(const std::string& typ); - + DetElement& setType(const std::string& typ); + /// Path of the detector element (not necessarily identical to placement path!) - std::string path() const; + std::string path() const; /// Access to the full path to the placed object - std::string placementPath() const; - + std::string placementPath() const; + /// Set all attributes in one go - DetElement& setAttributes(const LCDD& lcdd, const Volume& volume, - const std::string& region, - const std::string& limits, - const std::string& vis); - + DetElement& setAttributes(const LCDD& lcdd, const Volume& volume, const std::string& region, const std::string& limits, + const std::string& vis); + /// Set Visualization attributes to the detector element - DetElement& setVisAttributes(const LCDD& lcdd, const std::string& name, const Volume& volume); + DetElement& setVisAttributes(const LCDD& lcdd, const std::string& name, const Volume& volume); /// Set the regional attributes to the detector element - DetElement& setRegion(const LCDD& lcdd, const std::string& name, const Volume& volume); + DetElement& setRegion(const LCDD& lcdd, const std::string& name, const Volume& volume); /// Set the limits to the detector element - DetElement& setLimitSet(const LCDD& lcdd, const std::string& name, const Volume& volume); - -#if 0 - !!!! - !!!! MUST remove this: double caching and invalid information in case of reflection etc. - !!!! - /// Access the readout structure - Readout readout() const; - /// Assign readout definition - DetElement& setReadout(const Readout& readout); -#endif + DetElement& setLimitSet(const LCDD& lcdd, const std::string& name, const Volume& volume); + /// Access to the logical volume of the daughter placement - Volume volume() const; - + Volume volume() const; + /// Access to the physical volume of this detector element - PlacedVolume placement() const; + PlacedVolume placement() const; /// Set the physical volumes of the detector element - DetElement& setPlacement(const PlacedVolume& volume); - + DetElement& setPlacement(const PlacedVolume& volume); + /// Add new child to the detector structure - DetElement& add(DetElement sub_element); + DetElement& add(DetElement sub_element); /// Access to the list of children const Children& children() const; /// Access to individual children by name - DetElement child(const std::string& name) const; + DetElement child(const std::string& name) const; /// Access to the detector elements's parent - DetElement parent() const; - + DetElement parent() const; + /// Set detector element for reference transformations. Will delete existing reference trafo. - DetElement& setReference(DetElement reference); - + DetElement& setReference(DetElement reference); + /// Transformation from local coordinates of the placed volume to the world system - bool localToWorld(const Position& local, Position& global) const; + bool localToWorld(const Position& local, Position& global) const; /// Transformation from local coordinates of the placed volume to the parent system - bool localToParent(const Position& local, Position& parent) const; + bool localToParent(const Position& local, Position& parent) const; /// Transformation from local coordinates of the placed volume to arbitrary parent system set as reference - bool localToReference(const Position& local, Position& reference) const; - + bool localToReference(const Position& local, Position& reference) const; + /// Transformation from world coordinates of the local placed volume coordinates - bool worldToLocal(const Position& global, Position& local) const; + bool worldToLocal(const Position& global, Position& local) const; /// Transformation from world coordinates of the local placed volume coordinates - bool parentToLocal(const Position& parent, Position& local) const; + bool parentToLocal(const Position& parent, Position& local) const; /// Transformation from world coordinates of the local placed volume coordinates - bool referenceToLocal(const Position& reference, Position& local) const; - + bool referenceToLocal(const Position& reference, Position& local) const; + }; - - } /* End namespace Geometry */ -} /* End namespace DD4hep */ + + } /* End namespace Geometry */ +} /* End namespace DD4hep */ #endif /* DD4hep_LCDD_DETECTOR_H */ diff --git a/DDCore/include/DD4hep/Factories.h b/DDCore/include/DD4hep/Factories.h index f9466e4f6..f3d853cb0 100644 --- a/DDCore/include/DD4hep/Factories.h +++ b/DDCore/include/DD4hep/Factories.h @@ -1,6 +1,6 @@ // $Id$ //==================================================================== -// AIDA Detector description +// AIDA Detector description //-------------------------------------------------------------------- // // Author : M.Frank @@ -38,8 +38,9 @@ namespace DD4hep { struct SensitiveDetector; struct DetElement; - template <typename T> class ConstructionFactory { - public: static void* create(const char* arg); + template <typename T> class ConstructionFactory { + public: + static void* create(const char* arg); }; /** @class TranslationFactory Factories.h DDCore/Factories.h @@ -50,7 +51,7 @@ namespace DD4hep { * @version 1.0 * @date 2012/07/31 */ - template <typename T> class ApplyFactory { + template <typename T> class ApplyFactory { public: static long create(LCDD& lcdd, int argc, char** argv); }; @@ -63,7 +64,7 @@ namespace DD4hep { * @version 1.0 * @date 2012/07/31 */ - template <typename T> class TranslationFactory { + template <typename T> class TranslationFactory { public: static Ref_t create(LCDD& lcdd); }; @@ -75,7 +76,7 @@ namespace DD4hep { * @version 1.0 * @date 2012/07/31 */ - template <typename T> class XMLElementFactory { + template <typename T> class XMLElementFactory { public: static Ref_t create(LCDD& lcdd, XML::Handle_t e); }; @@ -87,7 +88,7 @@ namespace DD4hep { * @version 1.0 * @date 2012/07/31 */ - template <typename T> class XMLDocumentReaderFactory { + template <typename T> class XMLDocumentReaderFactory { public: static long create(LCDD& lcdd, XML::Handle_t e); }; @@ -99,7 +100,7 @@ namespace DD4hep { * @version 1.0 * @date 2012/07/31 */ - template <typename T> class XMLConversionFactory { + template <typename T> class XMLConversionFactory { public: static long create(LCDD& lcdd, Ref_t& handle, XML::Handle_t element); }; @@ -112,81 +113,79 @@ namespace DD4hep { * @version 1.0 * @date 2012/07/31 */ - template <typename T> class DetElementFactory { + template <typename T> class DetElementFactory { public: static Ref_t create(LCDD& lcdd, XML::Handle_t e, Ref_t sens); }; - } + } } namespace { - template < typename P > class Factory<P, void*(const char*)> { + template <typename P> class Factory<P, void*(const char*)> { public: - static void Func(void *ret, void*, const std::vector<void*>& arg, void*) - { *(void**)ret=DD4hep::Geometry::ConstructionFactory<P>::create((const char*)arg[0]); } + static void Func(void *ret, void*, const std::vector<void*>& arg, void*) { + *(void**) ret = DD4hep::Geometry::ConstructionFactory<P>::create((const char*) arg[0]); + } }; - template < typename P > class Factory<P, TNamed*(DD4hep::Geometry::LCDD*)> { + template <typename P> class Factory<P, TNamed*(DD4hep::Geometry::LCDD*)> { public: - typedef DD4hep::Geometry::LCDD LCDD; + typedef DD4hep::Geometry::LCDD LCDD; typedef DD4hep::Geometry::Ref_t Ref_t; static void Func(void *retaddr, void*, const std::vector<void*>& arg, void*) { - LCDD* lcdd = (LCDD* )arg[0]; + LCDD* lcdd = (LCDD*) arg[0]; Ref_t handle = DD4hep::Geometry::TranslationFactory<P>::create(*lcdd); - *(void**)retaddr = handle.ptr(); + *(void**) retaddr = handle.ptr(); } }; - template < typename P > class Factory<P, long(DD4hep::Geometry::LCDD*,int,char**)> { + template <typename P> class Factory<P, long(DD4hep::Geometry::LCDD*, int, char**)> { public: - typedef DD4hep::Geometry::LCDD LCDD; + typedef DD4hep::Geometry::LCDD LCDD; static void Func(void *retaddr, void*, const std::vector<void*>& arg, void*) { - LCDD* lcdd = (LCDD* )arg[0]; - long handle = DD4hep::Geometry::ApplyFactory<P>::create(*lcdd,*(int*)arg[1],(char**)arg[2]); - new(retaddr) (long)(handle); + LCDD* lcdd = (LCDD*) arg[0]; + long handle = DD4hep::Geometry::ApplyFactory<P>::create(*lcdd, *(int*) arg[1], (char**) arg[2]); + new (retaddr) (long)(handle); } }; - - template < typename P > class Factory<P, TNamed*(DD4hep::Geometry::LCDD*,DD4hep::XML::Handle_t*)> { + template <typename P> class Factory<P, TNamed*(DD4hep::Geometry::LCDD*, DD4hep::XML::Handle_t*)> { public: - typedef DD4hep::Geometry::LCDD LCDD; - typedef DD4hep::XML::Handle_t xml_h; + typedef DD4hep::Geometry::LCDD LCDD; + typedef DD4hep::XML::Handle_t xml_h; typedef DD4hep::Geometry::Ref_t Ref_t; static void Func(void *retaddr, void*, const std::vector<void*>& arg, void*) { - LCDD* lcdd = (LCDD* )arg[0]; - xml_h* elt = (xml_h*)arg[1]; - Ref_t handle = DD4hep::Geometry::XMLElementFactory<P>::create(*lcdd,*elt); - *(void**)retaddr = handle.ptr(); + LCDD* lcdd = (LCDD*) arg[0]; + xml_h* elt = (xml_h*) arg[1]; + Ref_t handle = DD4hep::Geometry::XMLElementFactory<P>::create(*lcdd, *elt); + *(void**) retaddr = handle.ptr(); } }; - - template < typename P > class Factory<P, long(DD4hep::Geometry::LCDD*,DD4hep::XML::Handle_t*)> { + template <typename P> class Factory<P, long(DD4hep::Geometry::LCDD*, DD4hep::XML::Handle_t*)> { public: - typedef DD4hep::Geometry::LCDD LCDD; - typedef DD4hep::XML::Handle_t xml_h; + typedef DD4hep::Geometry::LCDD LCDD; + typedef DD4hep::XML::Handle_t xml_h; static void Func(void *retaddr, void*, const std::vector<void*>& arg, void*) { - LCDD* lcdd = (LCDD* )arg[0]; - xml_h* elt = (xml_h*)arg[1]; - long ret = DD4hep::Geometry::XMLDocumentReaderFactory<P>::create(*lcdd,*elt); - new(retaddr) (long)(ret); + LCDD* lcdd = (LCDD*) arg[0]; + xml_h* elt = (xml_h*) arg[1]; + long ret = DD4hep::Geometry::XMLDocumentReaderFactory<P>::create(*lcdd, *elt); + new (retaddr) (long)(ret); } }; - - template < typename P > class Factory<P, TNamed*(DD4hep::Geometry::LCDD*,DD4hep::XML::Handle_t*,DD4hep::Geometry::Ref_t*)> { + template <typename P> class Factory<P, TNamed*(DD4hep::Geometry::LCDD*, DD4hep::XML::Handle_t*, DD4hep::Geometry::Ref_t*)> { public: - typedef DD4hep::Geometry::LCDD LCDD; - typedef DD4hep::XML::Handle_t xml_h; + typedef DD4hep::Geometry::LCDD LCDD; + typedef DD4hep::XML::Handle_t xml_h; typedef DD4hep::Geometry::Ref_t Ref_t; static void Func(void *retaddr, void*, const std::vector<void*>& arg, void*) { - LCDD* lcdd = (LCDD* )arg[0]; - xml_h* elt = (xml_h*)arg[1]; - Ref_t* sens = (Ref_t*)arg[2]; - Ref_t handle = DD4hep::Geometry::DetElementFactory<P>::create(*lcdd,*elt,*sens); - *(void**)retaddr = handle.ptr(); + LCDD* lcdd = (LCDD*) arg[0]; + xml_h* elt = (xml_h*) arg[1]; + Ref_t* sens = (Ref_t*) arg[2]; + Ref_t handle = DD4hep::Geometry::DetElementFactory<P>::create(*lcdd, *elt, *sens); + *(void**) retaddr = handle.ptr(); } }; } diff --git a/DDCore/include/DD4hep/FieldTypes.h b/DDCore/include/DD4hep/FieldTypes.h index 4385b2225..10586b205 100644 --- a/DDCore/include/DD4hep/FieldTypes.h +++ b/DDCore/include/DD4hep/FieldTypes.h @@ -22,34 +22,36 @@ namespace DD4hep { /* * Geoemtry namespace declaration */ - namespace Geometry { + namespace Geometry { /** @class ConstantField FieldTypes.h - * + * * Generic constant uniform field * * @author M.Frank * @version 1.0 */ - class ConstantField : public CartesianField::Object { + class ConstantField: public CartesianField::Object { public: /// Field direction Direction direction; public: /// Initializing constructor - ConstantField() : direction() { } + ConstantField() + : direction() { + } /// Call to access the field components at a given location virtual void fieldComponents(const double* /* pos */, double* field); }; /** @class SolenoidField FieldTypes.h DD4hep/FieldTypes.h - * + * * Generic solonoid magnetic field * * @author M.Frank * @version 1.0 */ - class SolenoidField : public CartesianField::Object { + class SolenoidField: public CartesianField::Object { public: double innerField; double outerField; @@ -66,18 +68,18 @@ namespace DD4hep { }; /** @class DipoleField FieldTypes.h DD4hep/FieldTypes.h - * + * * Generic solonoid magnetic field * * @author M.Frank * @version 1.0 */ - class DipoleField : public CartesianField::Object { + class DipoleField: public CartesianField::Object { public: typedef std::vector<double> Coefficents; - double zmax; - double zmin; - double rmax; + double zmax; + double zmin; + double rmax; Coefficents coefficents; public: /// Initializing constructor @@ -86,6 +88,6 @@ namespace DD4hep { virtual void fieldComponents(const double* pos, double* field); }; - } /* End namespace Geometry */ -} /* End namespace DD4hep */ + } /* End namespace Geometry */ +} /* End namespace DD4hep */ #endif /* DD4HEP_GEOMETRY_FIELDTYPES_H */ diff --git a/DDCore/include/DD4hep/Fields.h b/DDCore/include/DD4hep/Fields.h index 7e2674d2e..3364a3f7f 100644 --- a/DDCore/include/DD4hep/Fields.h +++ b/DDCore/include/DD4hep/Fields.h @@ -25,13 +25,13 @@ namespace DD4hep { /* * Geoemtry namespace declaration */ - namespace Geometry { + namespace Geometry { // Forward declarations typedef Position Direction; /** @class CartesianField Fields.h - * + * * Generic structure describing any field type (electric or magnetic) * with field components in Cartesian coordinates. * @@ -41,39 +41,52 @@ namespace DD4hep { * @author M.Frank * @version 1.0 */ - struct CartesianField : public Ref_t { - enum FieldType { UNKNOWN=0, ELECTRIC=0x1, MAGNETIC=0x2 }; - typedef std::map<std::string,std::string> PropertyValues; - typedef std::map<std::string,PropertyValues> Properties; + struct CartesianField: public Ref_t { + enum FieldType { + UNKNOWN = 0, ELECTRIC = 0x1, MAGNETIC = 0x2 + }; + typedef std::map<std::string, std::string> PropertyValues; + typedef std::map<std::string, PropertyValues> Properties; /// Internal data class shared by all handles of a given type - struct Object : public TNamed { - /// Field type - int type; - /// Field extensions - Properties properties; - /// Default constructor - Object(); - /// Default destructor - virtual ~Object(); - /// Call to access the field components at a given location - virtual void fieldComponents(const double* pos, double* field) = 0; + struct Object: public TNamed { + /// Field type + int type; + /// Field extensions + Properties properties; + /// Default constructor + Object(); + /// Default destructor + virtual ~Object(); + /// Call to access the field components at a given location + virtual void fieldComponents(const double* pos, double* field) = 0; }; /// Default constructor - CartesianField() : Ref_t() {} + CartesianField() + : Ref_t() { + } /// Constructor to be used when reading the already parsed DOM tree - CartesianField(const CartesianField& e) : Ref_t(e) {} + CartesianField(const CartesianField& e) + : Ref_t(e) { + } /// Constructor to be used when reading the already parsed DOM tree - template <typename Q> CartesianField(const Handle<Q>& e) : Ref_t(e) {} + template <typename Q> CartesianField(const Handle<Q>& e) + : Ref_t(e) { + } /// Assignment operator - CartesianField& operator=(const CartesianField& f) { m_element=f.m_element; return *this; } + CartesianField& operator=(const CartesianField& f) { + m_element = f.m_element; + return *this; + } /// Access the field type - int fieldType() const { return data<Object>()->type; } + int fieldType() const { + return data<Object>()->type; + } /// Access the field type (string) const char* type() const; @@ -82,24 +95,23 @@ namespace DD4hep { bool changesEnergy() const; /// Returns the 3 field components (x, y, z). - void value(const Position& pos, Direction& field) const;// { value(pos,&field.x); } + void value(const Position& pos, Direction& field) const; // { value(pos,&field.x); } /// Returns the 3 field components (x, y, z). - void value(const Position& pos, double* val) const;// { value(&pos.x,val); } + void value(const Position& pos, double* val) const; // { value(&pos.x,val); } /// Returns the 3 field components (x, y, z). - void value(const double* pos, double* val) const; + void value(const double* pos, double* val) const; /// Access to properties container - Properties& properties() const; + Properties& properties() const; }; typedef CartesianField ElectricField; typedef CartesianField MagneticField; - /** @class OverlayedField Fields.h - * + * * Generic structure describing any field type (electric or magnetic) * with field components in Cartesian coordinates. * @@ -109,37 +121,45 @@ namespace DD4hep { * @author M.Frank * @version 1.0 */ - struct OverlayedField : public Ref_t { - enum FieldType { ELECTRIC=0x1, MAGNETIC=0x2 }; - typedef std::map<std::string,std::string> PropertyValues; - typedef std::map<std::string,PropertyValues> Properties; - - struct Object : public TNamed { - int type; - CartesianField electric; - CartesianField magnetic; - std::vector<CartesianField> electric_components; - std::vector<CartesianField> magnetic_components; - /// Field extensions - Properties properties; - /// Default constructor - Object(); - /// Default destructor - virtual ~Object(); + struct OverlayedField: public Ref_t { + enum FieldType { + ELECTRIC = 0x1, MAGNETIC = 0x2 + }; + typedef std::map<std::string, std::string> PropertyValues; + typedef std::map<std::string, PropertyValues> Properties; + + struct Object: public TNamed { + int type; + CartesianField electric; + CartesianField magnetic; + std::vector<CartesianField> electric_components; + std::vector<CartesianField> magnetic_components; + /// Field extensions + Properties properties; + /// Default constructor + Object(); + /// Default destructor + virtual ~Object(); }; /// Default constructor - OverlayedField() : Ref_t() {} + OverlayedField() + : Ref_t() { + } /// Constructor to be used when reading the already parsed DOM tree - template <typename Q> - OverlayedField(const Handle<Q>& e) : Ref_t(e) {} + template <typename Q> + OverlayedField(const Handle<Q>& e) + : Ref_t(e) { + } /// Object constructor OverlayedField(const std::string& name); /// Access the field type - int type() const { return data<Object>()->type; } + int type() const { + return data<Object>()->type; + } /// Does the field change the energy of charged particles? bool changesEnergy() const; @@ -148,67 +168,67 @@ namespace DD4hep { void add(CartesianField field); /// Returns the 3 electric field components (x, y, z) if many components are present - void combinedElectric(const Position& pos, double* field) const { - combinedElectric((const double*)&pos,field); + void combinedElectric(const Position& pos, double* field) const { + combinedElectric((const double*) &pos, field); } /// Returns the 3 electric field components (x, y, z) if many components are present void combinedElectric(const double* pos, double* field) const; /// Returns the 3 magnetic field components (x, y, z) if many components are present - void combinedMagnetic(const Position& pos, double* field) const { - combinedMagnetic((const double*)&pos,field); + void combinedMagnetic(const Position& pos, double* field) const { + combinedMagnetic((const double*) &pos, field); } /// Returns the 3 magnetic field components (x, y, z) if many components are present - void combinedMagnetic(const double* pos, double* field) const; + void combinedMagnetic(const double* pos, double* field) const; /// Returns the 3 electric field components (x, y, z). - void electricField(const Position& pos, Direction& field) const { - electricField((const double*)&pos, (double*)&field); + void electricField(const Position& pos, Direction& field) const { + electricField((const double*) &pos, (double*) &field); } /// Returns the 3 electric field components (x, y, z). - void electricField(const Position& pos, double* field) const { - electricField((double*)&pos, field); + void electricField(const Position& pos, double* field) const { + electricField((double*) &pos, field); } /// Returns the 3 electric field components (x, y, z). - void electricField(const double* pos, double* field) const { - CartesianField f = data<Object>()->electric; - f.isValid() ? f.value(pos,field) : combinedElectric(pos,field); + void electricField(const double* pos, double* field) const { + CartesianField f = data<Object>()->electric; + f.isValid() ? f.value(pos, field) : combinedElectric(pos, field); } /// Returns the 3 magnetic field components (x, y, z). - void magneticField(const Position& pos, Direction& field) const { - magneticField((double*)&pos, (double*)&field); + void magneticField(const Position& pos, Direction& field) const { + magneticField((double*) &pos, (double*) &field); } /// Returns the 3 magnetic field components (x, y, z). - void magneticField(const Position& pos, double* field) const { - magneticField((double*)&pos, field); + void magneticField(const Position& pos, double* field) const { + magneticField((double*) &pos, field); } /// Returns the 3 magnetic field components (x, y, z). - void magneticField(const double* pos, double* field) const { - CartesianField f = data<Object>()->magnetic; - f.isValid() ? f.value(pos,field) : combinedMagnetic(pos,field); + void magneticField(const double* pos, double* field) const { + CartesianField f = data<Object>()->magnetic; + f.isValid() ? f.value(pos, field) : combinedMagnetic(pos, field); } /// Returns the 3 electric (val[0]-val[2]) and magnetic field components (val[3]-val[5]). - void electromagneticField(const Position& pos, double* val) const { - electromagneticField((double*)&pos,val); + void electromagneticField(const Position& pos, double* val) const { + electromagneticField((double*) &pos, val); } /// Returns the 3 electric (val[0]-val[2]) and magnetic field components (val[3]-val[5]). - void electromagneticField(const double* pos, double* val) const; + void electromagneticField(const double* pos, double* val) const; /// Access to properties container - Properties& properties() const; + Properties& properties() const; }; typedef OverlayedField ElectroMagneticField; - } /* End namespace Geometry */ -} /* End namespace DD4hep */ + } /* End namespace Geometry */ +} /* End namespace DD4hep */ #endif /* DD4HEP_GEOMETRY_FIELDS_H */ diff --git a/DDCore/include/DD4hep/GeoHandler.h b/DDCore/include/DD4hep/GeoHandler.h index 738151881..5e5ee4d7e 100644 --- a/DDCore/include/DD4hep/GeoHandler.h +++ b/DDCore/include/DD4hep/GeoHandler.h @@ -44,33 +44,33 @@ namespace DD4hep { */ class GeoHandlerTypes { public: - typedef std::set<TGeoVolume*> VolumeSet; - typedef std::vector<TGeoVolume*> VolumeVector; - typedef std::set<const TGeoVolume*> ConstVolumeSet; - typedef std::vector<std::pair<std::string, TGeoMatrix*> > TransformSet; - typedef std::set<TGeoShape*> SolidSet; - typedef std::set<TGeoMedium*> MaterialSet; - typedef std::map<const TNamed*,ConstVolumeSet> SensitiveVolumes; - typedef std::map<const TNamed*,ConstVolumeSet> RegionVolumes; - typedef std::map<const TNamed*,ConstVolumeSet> LimitVolumes; - typedef std::map<int, std::set<const TGeoNode*> > Data; - typedef std::set<const TNamed*> VisRefs; - typedef std::set<TNamed*> Fields; - typedef std::set<TNamed*> ObjectSet; - typedef LCDD::HandleMap DefinitionSet; - struct GeometryInfo { - SolidSet solids; - VolumeSet volumeSet; - VolumeVector volumes; - TransformSet trafos; - VisRefs vis; - Fields fields; - MaterialSet materials; - // SensitiveVolumes sensitives; - // RegionVolumes regions; - // LimitVolumes limits; - std::set<TGeoMedium*> media; - std::set<TGeoElement*> elements; + typedef std::set<TGeoVolume*> VolumeSet; + typedef std::vector<TGeoVolume*> VolumeVector; + typedef std::set<const TGeoVolume*> ConstVolumeSet; + typedef std::vector<std::pair<std::string, TGeoMatrix*> > TransformSet; + typedef std::set<TGeoShape*> SolidSet; + typedef std::set<TGeoMedium*> MaterialSet; + typedef std::map<const TNamed*, ConstVolumeSet> SensitiveVolumes; + typedef std::map<const TNamed*, ConstVolumeSet> RegionVolumes; + typedef std::map<const TNamed*, ConstVolumeSet> LimitVolumes; + typedef std::map<int, std::set<const TGeoNode*> > Data; + typedef std::set<const TNamed*> VisRefs; + typedef std::set<TNamed*> Fields; + typedef std::set<TNamed*> ObjectSet; + typedef LCDD::HandleMap DefinitionSet; + struct GeometryInfo { + SolidSet solids; + VolumeSet volumeSet; + VolumeVector volumes; + TransformSet trafos; + VisRefs vis; + Fields fields; + MaterialSet materials; + // SensitiveVolumes sensitives; + // RegionVolumes regions; + // LimitVolumes limits; + std::set<TGeoMedium*> media; + std::set<TGeoElement*> elements; }; }; @@ -79,7 +79,7 @@ namespace DD4hep { * @author M.Frank * @version 1.0 */ - class GeoHandler : public GeoHandlerTypes { + class GeoHandler: public GeoHandlerTypes { protected: Data* m_data; @@ -89,9 +89,12 @@ namespace DD4hep { private: /// Never call Copy constructor - GeoHandler(const GeoHandler&) {} + GeoHandler(const GeoHandler&) { + } /// Never call assignment operator - GeoHandler& operator=(const GeoHandler&) { return *this; } + GeoHandler& operator=(const GeoHandler&) { + return *this; + } public: /// Default constructor @@ -109,10 +112,10 @@ namespace DD4hep { }; struct GeoScan { - protected: + protected: /// Data holder GeoHandler::Data* m_data; - public: + public: /// Initializing constructor GeoScan(DetElement e); /// Default destructor @@ -124,4 +127,3 @@ namespace DD4hep { } // End namespace DD4hep #endif // DD4HEP_GEOHANDLER_H - diff --git a/DDCore/include/DD4hep/Handle.h b/DDCore/include/DD4hep/Handle.h index c3db148c2..8fa9d24f0 100644 --- a/DDCore/include/DD4hep/Handle.h +++ b/DDCore/include/DD4hep/Handle.h @@ -29,7 +29,7 @@ class TGeoManager; #ifndef RAD_2_DEGREE #define RAD_2_DEGREE 57.295779513082320876798154814105 #endif -#ifndef DEGREE_2_RAD +#ifndef DEGREE_2_RAD #define DEGREE_2_RAD 0.017453292519943295769236907684886 #endif #ifndef CM_2_MM @@ -39,7 +39,6 @@ class TGeoManager; #define MM_2_CM 0.1 #endif - #ifndef M_PI #define M_PI 3.14159265358979323846 #endif @@ -48,74 +47,94 @@ class TGeoManager; * DD4hep namespace declaration */ namespace DD4hep { - - /// Access to the CXX abi name + + /// Access to the CXX abi name std::string typeName(const std::type_info& type); /* * Geometry sub-namespace declaration */ - namespace Geometry { - struct LCDD; - - std::string _toString(bool value); - std::string _toString(int value); - std::string _toString(float value); - std::string _toString(double value); - - bool _toBool (const std::string& value); - int _toInt (const std::string& value); - long _toLong (const std::string& value); - float _toFloat (const std::string& value); - double _toDouble(const std::string& value); - - inline bool _toBool(bool value) { return value; } - inline int _toInt(int value) { return value; } - inline long _toLong(long value) { return value; } - inline float _toFloat(float value) { return value; } - inline double _toDouble(double value) { return value; } - - template<class T> T _multiply(const std::string& left, T right); - template<class T> T _multiply(T left, const std::string& right); - template<class T> T _multiply(const std::string& left, const std::string& right); - - template <> int _multiply<int>(const std::string& left, const std::string& right); - template <> inline int _multiply<int>(int left, const std::string& right) - { return left * _toInt(right); } - template <> inline int _multiply<int>(const std::string& left, int right) - { return _toInt(left) * right; } - - template <> long _multiply<long>(const std::string& left, const std::string& right); - template <> inline long _multiply<long>(long left, const std::string& right) - { return left * _toLong(right); } - template <> inline long _multiply<long>(const std::string& left, long right) - { return _toLong(left) * right; } - - template <> float _multiply<float>(const std::string& left, const std::string& right); - template <> inline float _multiply<float>(float left, const std::string& right) - { return left * _toFloat(right); } - template <> inline float _multiply<float>(const std::string& left, float right) - { return _toFloat(left) * right; } - - template <> double _multiply<double>(const std::string& left, const std::string& right); - template <> inline double _multiply<double>(const std::string& left, double right) - { return _toDouble(left) * right; } - template <> inline double _multiply<double>(double left, const std::string& right) - { return left * _toDouble(right); } - + namespace Geometry { + struct LCDD; + + std::string _toString(bool value); + std::string _toString(int value); + std::string _toString(float value); + std::string _toString(double value); + + bool _toBool(const std::string& value); + int _toInt(const std::string& value); + long _toLong(const std::string& value); + float _toFloat(const std::string& value); + double _toDouble(const std::string& value); + + inline bool _toBool(bool value) { + return value; + } + inline int _toInt(int value) { + return value; + } + inline long _toLong(long value) { + return value; + } + inline float _toFloat(float value) { + return value; + } + inline double _toDouble(double value) { + return value; + } + + template <class T> T _multiply(const std::string& left, T right); + template <class T> T _multiply(T left, const std::string& right); + template <class T> T _multiply(const std::string& left, const std::string& right); + + template <> int _multiply<int>(const std::string& left, const std::string& right); + template <> inline int _multiply<int>(int left, const std::string& right) { + return left * _toInt(right); + } + template <> inline int _multiply<int>(const std::string& left, int right) { + return _toInt(left) * right; + } + + template <> long _multiply<long>(const std::string& left, const std::string& right); + template <> inline long _multiply<long>(long left, const std::string& right) { + return left * _toLong(right); + } + template <> inline long _multiply<long>(const std::string& left, long right) { + return _toLong(left) * right; + } + + template <> float _multiply<float>(const std::string& left, const std::string& right); + template <> inline float _multiply<float>(float left, const std::string& right) { + return left * _toFloat(right); + } + template <> inline float _multiply<float>(const std::string& left, float right) { + return _toFloat(left) * right; + } + + template <> double _multiply<double>(const std::string& left, const std::string& right); + template <> inline double _multiply<double>(const std::string& left, double right) { + return _toDouble(left) * right; + } + template <> inline double _multiply<double>(double left, const std::string& right) { + return left * _toDouble(right); + } + void _toDictionary(const std::string& name, const std::string& value); long num_object_validations(); void increment_object_validations(); - - inline unsigned long long int magic_word() { return 0xFEEDAFFEDEADFACEULL; } - + + inline unsigned long long int magic_word() { + return 0xFEEDAFFEDEADFACEULL; + } + /** @class Value Handle.h - * + * * @author M.Frank * @version 1.0 */ - struct Counted { + struct Counted { /// Standard constructor Counted(); /// Standard destructor @@ -123,108 +142,147 @@ namespace DD4hep { }; /** @class Value Handle.h - * + * * Class to simply combine to object types to one * * @author M.Frank * @version 1.0 */ - template <typename Q, typename P> struct Value : public Q, public P + template <typename Q, typename P> struct Value: public Q, public P #ifdef DD4HEP_INSTANCE_COUNTS - , public Counted + , public Counted #endif { - typedef Q first_base; - typedef P second_base; + typedef Q first_base; + typedef P second_base; /// Standard constructor Value(); /// Standard destructor virtual ~Value(); }; - template <typename Q, typename P> inline Value<Q,P>::Value() { + template <typename Q, typename P> inline Value<Q, P>::Value() { #ifdef DD4HEP_INSTANCE_COUNTS - InstanceCount::increment(this); + InstanceCount::increment(this); #endif } - template <typename Q, typename P> inline Value<Q,P>::~Value() { + template <typename Q, typename P> inline Value<Q, P>::~Value() { #ifdef DD4HEP_INSTANCE_COUNTS - InstanceCount::decrement(this); + InstanceCount::decrement(this); #endif } /** @class Handle Handle.h - * + * * @author M.Frank * @version 1.0 */ - template <typename T=TNamed> struct Handle { + template <typename T = TNamed> struct Handle { typedef T Implementation; typedef Handle<Implementation> handle_t; T* m_element; - Handle() : m_element(0) { } - Handle(T* e) : m_element(e) { } - Handle(const Handle<T>& e) : m_element(e.m_element) { } - template<typename Q> Handle(Q* e) - : m_element((T*)e) { verifyObject(); } - template<typename Q> Handle(const Handle<Q>& e) - : m_element((T*)e.m_element) { verifyObject(); } - Handle<T>& operator=(const Handle<T>& e){ m_element=e.m_element; return *this; } - bool isValid() const { return 0 != m_element; } - bool operator!() const { return 0 == m_element; } - void clear() { m_element = 0; } - T* operator->() const { return m_element; } - operator T& () const { return *m_element; } - T& operator*() const { return *m_element; } - T* ptr() const { return m_element; } - template <typename Q> Q* _ptr() const { return (Q*)m_element; } - template <typename Q> Q* data() const { return (Q*)m_element; } - template <typename Q> Q& object() const{ return *(Q*)m_element; } + Handle() + : m_element(0) { + } + Handle(T* e) + : m_element(e) { + } + Handle(const Handle<T>& e) + : m_element(e.m_element) { + } + template <typename Q> Handle(Q* e) + : m_element((T*) e) { + verifyObject(); + } + template <typename Q> Handle(const Handle<Q>& e) + : m_element((T*) e.m_element) { + verifyObject(); + } + Handle<T>& operator=(const Handle<T>& e) { + m_element = e.m_element; + return *this; + } + bool isValid() const { + return 0 != m_element; + } + bool operator!() const { + return 0 == m_element; + } + void clear() { + m_element = 0; + } + T* operator->() const { + return m_element; + } + operator T&() const { + return *m_element; + } + T& operator*() const { + return *m_element; + } + T* ptr() const { + return m_element; + } + template <typename Q> Q* _ptr() const { + return (Q*) m_element; + } + template <typename Q> Q* data() const { + return (Q*) m_element; + } + template <typename Q> Q& object() const { + return *(Q*) m_element; + } void verifyObject() const { increment_object_validations(); - if ( m_element && dynamic_cast<T*>(m_element) == 0 ) { - bad_assignment(typeid(*m_element),typeid(T)); + if (m_element && dynamic_cast<T*>(m_element) == 0) { + bad_assignment(typeid(*m_element), typeid(T)); } } const char* name() const; static void bad_assignment(const std::type_info& from, const std::type_info& to); - void assign(Implementation* n, const std::string& nam, const std::string& title); + void assign(Implementation* n, const std::string& nam, const std::string& title); }; - typedef Handle<> Elt_t; + typedef Handle<> Elt_t; typedef Handle<TNamed> Ref_t; - + /// Helper to delete objects from heap and reset the handle - template <typename T> inline void destroyHandle(T& h) { + template <typename T> inline void destroyHandle(T& h) { deletePtr(h.m_element); } /// Helper to delete objects from heap and reset the handle - template <typename T> inline void releaseHandle(T& h) { + template <typename T> inline void releaseHandle(T& h) { releasePtr(h.m_element); } /// Functor to destroy handles and delete the cached object - template <typename T=Ref_t> struct DestroyHandle { + template <typename T = Ref_t> struct DestroyHandle { void operator()(T p) const { - destroyHandle(p); + destroyHandle(p); } }; /// Functor to destroy handles and delete the cached object - template <typename T=Ref_t> struct ReleaseHandle { + template <typename T = Ref_t> struct ReleaseHandle { void operator()(T p) const { - releaseHandle(p); + releaseHandle(p); } }; /// map Functor to destroy handles and delete the cached object template <typename M> struct DestroyHandles { M& object; - DestroyHandles(M& m) : object(m) {} - ~DestroyHandles() { object.clear(); } - void operator()(std::pair<typename M::key_type,typename M::mapped_type> p) const { - DestroyHandle<typename M::mapped_type>()(p.second); + DestroyHandles(M& m) + : object(m) { + } + ~DestroyHandles() { + object.clear(); + } + void operator()(std::pair<typename M::key_type, typename M::mapped_type> p) const { + DestroyHandle<typename M::mapped_type>()(p.second); } }; - template<typename M> DestroyHandles<M> destroyHandles(M& m) { return DestroyHandles<M>(m); } - + template <typename M> DestroyHandles<M> destroyHandles(M& m) { + return DestroyHandles<M>(m); + } - } /* End namespace Geometry */ -} /* End namespace DD4hep */ + } /* End namespace Geometry */ +} /* End namespace DD4hep */ #endif /* DD4HEP_ELEMENTS_H */ + diff --git a/DDCore/include/DD4hep/IDDescriptor.h b/DDCore/include/DD4hep/IDDescriptor.h index 6ebb7ee74..c5d70b40a 100644 --- a/DDCore/include/DD4hep/IDDescriptor.h +++ b/DDCore/include/DD4hep/IDDescriptor.h @@ -31,62 +31,66 @@ namespace DD4hep { namespace Geometry { /** @class IDDescriptor IDDescriptor.h DDCore/IDDescriptor.h - * + * * @author M.Frank * @version 1.0 * @date 2012/07/31 */ - struct IDDescriptor : public Ref_t { + struct IDDescriptor: public Ref_t { public: - typedef std::pair<std::string,int> VolID; + typedef std::pair<std::string, int> VolID; typedef DDSegmentation::BitFieldValue* Field; - typedef std::vector<std::pair<std::string,Field> > FieldMap; - typedef std::vector<std::pair<size_t,std::string> > FieldIDs; - typedef std::pair<Field,VolumeID> VolIDField; - typedef std::vector<VolIDField> VolIDFields; + typedef std::vector<std::pair<std::string, Field> > FieldMap; + typedef std::vector<std::pair<size_t, std::string> > FieldIDs; + typedef std::pair<Field, VolumeID> VolIDField; + typedef std::vector<VolIDField> VolIDFields; /** @class IDDescriptor::Object IDDescriptor.h DDCore/IDDescriptor.h - * + * * @author M.Frank * @version 1.0 * @date 2012/07/31 */ - struct Object : public TNamed, public DDSegmentation::BitField64 { - FieldMap fieldMap; - FieldIDs fieldIDs; - std::string description; - /// Standard constructor - Object(const std::string& initString); - /// Default destructor - virtual ~Object(); - /// Access to the field container of the BitField64 - const std::vector<DDSegmentation::BitFieldValue*> fields() const { - return _fields; - } + struct Object: public TNamed, public DDSegmentation::BitField64 { + FieldMap fieldMap; + FieldIDs fieldIDs; + std::string description; + /// Standard constructor + Object(const std::string& initString); + /// Default destructor + virtual ~Object(); + /// Access to the field container of the BitField64 + const std::vector<DDSegmentation::BitFieldValue*> fields() const { + return _fields; + } }; - public: + public: /// Default constructor - IDDescriptor() : Ref_t() {} + IDDescriptor() + : Ref_t() { + } /// Constructor to be used when reading the already parsed object - template <typename Q> IDDescriptor(const Handle<Q>& e) : Ref_t(e) {} + template <typename Q> IDDescriptor(const Handle<Q>& e) + : Ref_t(e) { + } /// Initializing constructor IDDescriptor(const std::string& description); // the string description of all fields - std::string fieldDescription() const ; + std::string fieldDescription() const; /// The total number of encoding bits for this descriptor unsigned maxBit() const; - /// Access the field-id container + /// Access the field-id container const FieldIDs& ids() const; - /// Access the fieldmap container + /// Access the fieldmap container const FieldMap& fields() const; /// Get the field descriptor of one field by name - Field field(const std::string& field_name) const; + Field field(const std::string& field_name) const; /// Get the field identifier of one field by name - size_t fieldID(const std::string& field_name) const; + size_t fieldID(const std::string& field_name) const; /// Get the field descriptor of one field by its identifier - Field field(size_t identifier) const; + Field field(size_t identifier) const; /// Encode a set of volume identifiers (corresponding to this description of course!) to a volumeID. - VolumeID encode(const std::vector<VolID>& ids) const; + VolumeID encode(const std::vector<VolID>& ids) const; /// Decode volume IDs and return filled descriptor with all fields void decodeFields(VolumeID vid, VolIDFields& fields); /// Access string representation @@ -94,6 +98,6 @@ namespace DD4hep { /// Access the BitField64 object DDSegmentation::BitField64* decoder(); }; - } /* End namespace Geometry */ -} /* End namespace DD4hep */ + } /* End namespace Geometry */ +} /* End namespace DD4hep */ #endif /* DD4hep_IDDESCRIPTOR_H */ diff --git a/DDCore/include/DD4hep/InstanceCount.h b/DDCore/include/DD4hep/InstanceCount.h index d85e998d5..9ad1756d0 100644 --- a/DDCore/include/DD4hep/InstanceCount.h +++ b/DDCore/include/DD4hep/InstanceCount.h @@ -25,14 +25,12 @@ namespace DD4hep { * @author Markus Frank * @version 1.0 */ - struct InstanceCount { + struct InstanceCount { public: typedef long long int counter_t; /// Enumeration to steer the output - enum { NONE = 1<<0, - STRING = 1<<1, - TYPEINFO = 1<<2, - ALL=STRING|TYPEINFO + enum { + NONE = 1 << 0, STRING = 1 << 1, TYPEINFO = 1 << 2, ALL = STRING | TYPEINFO }; /** @class Counter * @@ -41,7 +39,7 @@ namespace DD4hep { * @author Markus Frank * @version 1.0 */ - class Counter { + class Counter { private: /// Reference counter value counter_t m_count; @@ -49,20 +47,33 @@ namespace DD4hep { counter_t m_tot; public: /// Default constructor - Counter() : m_count(0), m_tot(0) { } + Counter() + : m_count(0), m_tot(0) { + } /// Copy constructor - Counter(const Counter& c) - : m_count(c.m_count), m_tot(c.m_tot){ } + Counter(const Counter& c) + : m_count(c.m_count), m_tot(c.m_tot) { + } /// Destructor - ~Counter() { } + ~Counter() { + } /// Increment counter - void increment() { ++m_count; ++m_tot; } + void increment() { + ++m_count; + ++m_tot; + } /// Decrement counter - void decrement() { --m_count; } + void decrement() { + --m_count; + } /// Access counter value - counter_t value() const { return m_count; } + counter_t value() const { + return m_count; + } /// Access counter value - counter_t total() const { return m_tot; } + counter_t total() const { + return m_tot; + } }; public: /// Standard Constructor - No need to call explicitly @@ -74,41 +85,50 @@ namespace DD4hep { /// Access counter object for local caching on optimizations static Counter* getCounter(const std::string& typ); /// Increment count according to type information - template<class T> static void increment(T*) - { getCounter(typeid(T))->increment(); } + template <class T> static void increment(T*) { + getCounter(typeid(T))->increment(); + } /// Decrement count according to type information - template<class T> static void decrement(T*) - { getCounter(typeid(T))->decrement(); } + template <class T> static void decrement(T*) { + getCounter(typeid(T))->decrement(); + } /// Access current counter - template<class T> static counter_t get(T*) - { return getCounter(typeid(T))->value(); } + template <class T> static counter_t get(T*) { + return getCounter(typeid(T))->value(); + } /// Increment count according to type information - static void increment(const std::type_info& typ) - { getCounter(typ)->increment(); } + static void increment(const std::type_info& typ) { + getCounter(typ)->increment(); + } /// Decrement count according to type information - static void decrement(const std::type_info& typ) - { getCounter(typ)->decrement(); } + static void decrement(const std::type_info& typ) { + getCounter(typ)->decrement(); + } /// Access current counter - static counter_t get(const std::type_info& typ) - { return getCounter(typ)->value(); } + static counter_t get(const std::type_info& typ) { + return getCounter(typ)->value(); + } /// Increment count according to string information - static void increment(const std::string& typ) - { getCounter(typ)->increment(); } + static void increment(const std::string& typ) { + getCounter(typ)->increment(); + } /// Decrement count according to string information - static void decrement(const std::string& typ) - { getCounter(typ)->decrement(); } + static void decrement(const std::string& typ) { + getCounter(typ)->decrement(); + } /// Access current counter - static counter_t get(const std::string& typ) - { return getCounter(typ)->value(); } + static counter_t get(const std::string& typ) { + return getCounter(typ)->value(); + } /// Dump list of instance counters - static void dump(int which=ALL); + static void dump(int which = ALL); /// Clear list of instance counters - static void clear(int which=ALL); + static void clear(int which = ALL); /// Check if tracing is enabled. static bool doTrace(); /// Enable/Disable tracing static void doTracing(bool value); }; -} /* End namespace DD4hep */ +} /* End namespace DD4hep */ #endif /* DD4HEP_GEOMETRY_INSTANCECOUNT_H */ diff --git a/DDCore/include/DD4hep/LCDD.h b/DDCore/include/DD4hep/LCDD.h index 6f1281faa..552ade231 100644 --- a/DDCore/include/DD4hep/LCDD.h +++ b/DDCore/include/DD4hep/LCDD.h @@ -31,40 +31,36 @@ class TGeoManager; * DD4hep namespace declaration */ namespace DD4hep { - + /* * Geometry namespace declaration */ - namespace Geometry { + namespace Geometry { /** @enum LCDDBuildType LCDD.h DD4hep/LCDD.h * Detector description build types. - * The corresponding flag is ONLY valid while parsing the + * The corresponding flag is ONLY valid while parsing the * compact description. If no eometry, ie. at all other times * the accessor to the flag returns BUILD_NONE. */ enum LCDDBuildType { - BUILD_NONE = 0, - BUILD_DEFAULT = 1, - BUILD_SIMU = BUILD_DEFAULT, - BUILD_RECO, - BUILD_DISPLAY + BUILD_NONE = 0, BUILD_DEFAULT = 1, BUILD_SIMU = BUILD_DEFAULT, BUILD_RECO, BUILD_DISPLAY }; - /** @class LCDD LCDD.h DD4hep/LCDD.h - * + * * @author M.Frank * @version 1.0 */ struct LCDD { - typedef std::map<std::string,Handle<> > HandleMap; - typedef std::map<std::string,std::string> PropertyValues; - typedef std::map<std::string,PropertyValues> Properties; + typedef std::map<std::string, Handle<> > HandleMap; + typedef std::map<std::string, std::string> PropertyValues; + typedef std::map<std::string, PropertyValues> Properties; /// Destructor - virtual ~LCDD() {} + virtual ~LCDD() { + } /// Access flag to steer the detail of building of the geometry/detector description virtual LCDDBuildType buildType() const = 0; @@ -82,7 +78,7 @@ namespace DD4hep { /// Return handle to material describing vacuum virtual Material vacuum() const = 0; /// Return handle to "invisible" visualization attributes - virtual VisAttr invisible() const = 0; + virtual VisAttr invisible() const = 0; /// Return reference to the top-most (world) detector element virtual DetElement world() const = 0; @@ -90,15 +86,15 @@ namespace DD4hep { virtual DetElement trackers() const = 0; /// Return handle to the world volume containing everything - virtual Volume worldVolume() const = 0; - /// Return handle to the world volume containing the volume with the tracking devices - virtual Volume trackingVolume() const = 0; + virtual Volume worldVolume() const = 0; + /// Return handle to the volume containing the tracking devices + virtual Volume trackingVolume() const = 0; /// Return handle to the VolumeManager virtual VolumeManager volumeManager() const = 0; /// Accessor to the map of header entries - virtual Header header() const = 0; + virtual Header header() const = 0; /// Accessor to the header entry virtual void setHeader(Header h) = 0; @@ -106,71 +102,71 @@ namespace DD4hep { virtual OverlayedField field() const = 0; /// Accessor to the map of constants - virtual const HandleMap& constants() const = 0; + virtual const HandleMap& constants() const = 0; /// Accessor to the map of region settings virtual const HandleMap& regions() const = 0; /// Accessor to the map of sub-detectors - virtual const HandleMap& detectors() const = 0; + virtual const HandleMap& detectors() const = 0; /// Accessor to the map of readout structures virtual const HandleMap& readouts() const = 0; /// Accessor to the map of visualisation attributes virtual const HandleMap& visAttributes() const = 0; /// Accessor to the map of limit settings - virtual const HandleMap& limitsets() const = 0; + virtual const HandleMap& limitsets() const = 0; /// Accessor to the map of aligment entries - virtual const HandleMap& alignments() const = 0; + virtual const HandleMap& alignments() const = 0; /// Accessor to the map of field entries, which together form the global field - virtual const HandleMap& fields() const = 0; + virtual const HandleMap& fields() const = 0; - virtual Volume pickMotherVolume(const DetElement& sd) const = 0; + virtual Volume pickMotherVolume(const DetElement& sd) const = 0; /// Typed access to constants: access string values - virtual std::string constantAsString(const std::string& name) const = 0; + virtual std::string constantAsString(const std::string& name) const = 0; /// Typed access to constants: long values - virtual long constantAsLong(const std::string& name) const = 0; + virtual long constantAsLong(const std::string& name) const = 0; /// Typed access to constants: double values - virtual double constantAsDouble(const std::string& name) const = 0; + virtual double constantAsDouble(const std::string& name) const = 0; /// Retrieve a constant by it's name from the detector description - virtual Constant constant(const std::string& name) const = 0; + virtual Constant constant(const std::string& name) const = 0; /// Typed access to constants: access any type values - template<class T> T constant(const std::string& name) const; + template <class T> T constant(const std::string& name) const; /// Retrieve a matrial by it's name from the detector description - virtual Material material(const std::string& name) const = 0; + virtual Material material(const std::string& name) const = 0; /// Retrieve a id descriptor by it's name from the detector description - virtual IDDescriptor idSpecification(const std::string& name) const = 0; + virtual IDDescriptor idSpecification(const std::string& name) const = 0; /// Retrieve a region object by it's name from the detector description - virtual Region region(const std::string& name) const = 0; + virtual Region region(const std::string& name) const = 0; /// Retrieve a visualization attribute by it's name from the detector description - virtual VisAttr visAttributes(const std::string& name) const = 0; + virtual VisAttr visAttributes(const std::string& name) const = 0; /// Retrieve a limitset by it's name from the detector description - virtual LimitSet limitSet(const std::string& name) const = 0; + virtual LimitSet limitSet(const std::string& name) const = 0; /// Retrieve a readout object by it's name from the detector description - virtual Readout readout(const std::string& name) const = 0; + virtual Readout readout(const std::string& name) const = 0; /// Retrieve an alignment entry by it's name from the detector description - virtual AlignmentEntry alignment(const std::string& path) const = 0; + virtual AlignmentEntry alignment(const std::string& path) const = 0; /// Retrieve a sensitive detector by it's name from the detector description virtual SensitiveDetector sensitiveDetector(const std::string& name) const = 0; /// Retrieve a subdetector element by it's name from the detector description - virtual CartesianField field(const std::string& name) const = 0; + virtual CartesianField field(const std::string& name) const = 0; /// Retrieve a field component by it's name from the detector description - virtual DetElement detector(const std::string& name) const = 0; + virtual DetElement detector(const std::string& name) const = 0; /// Add a new constant to the detector description - virtual LCDD& add(Constant constant) = 0; + virtual LCDD& add(Constant constant) = 0; /// Add a new visualisation attribute to the detector description - virtual LCDD& add(VisAttr attr) = 0; + virtual LCDD& add(VisAttr attr) = 0; /// Add a new limit set to the detector description - virtual LCDD& add(LimitSet limitset) = 0; + virtual LCDD& add(LimitSet limitset) = 0; /// Add a new detector region to the detector description - virtual LCDD& add(Region region) = 0; + virtual LCDD& add(Region region) = 0; /// Add a new id descriptor to the detector description - virtual LCDD& add(IDDescriptor spec) = 0; + virtual LCDD& add(IDDescriptor spec) = 0; /// Add a new detector readout to the detector description - virtual LCDD& add(Readout readout) = 0; + virtual LCDD& add(Readout readout) = 0; /// Add a new subdetector to the detector description - virtual LCDD& add(DetElement detector) = 0; + virtual LCDD& add(DetElement detector) = 0; /// Add alignment entry to the detector description virtual LCDD& add(AlignmentEntry entry) = 0; /// Add a field component to the detector description @@ -198,21 +194,23 @@ namespace DD4hep { virtual LCDD& addField(const Ref_t& field) = 0; /// Read compact geometry description or alignment file - virtual void fromCompact(const std::string& fname, LCDDBuildType type=BUILD_DEFAULT) = 0; + virtual void fromCompact(const std::string& fname, LCDDBuildType type = BUILD_DEFAULT) = 0; /// Read any geometry description or alignment file - virtual void fromXML(const std::string& fname, LCDDBuildType type=BUILD_DEFAULT) = 0; - /// + virtual void fromXML(const std::string& fname, LCDDBuildType type = BUILD_DEFAULT) = 0; + /// virtual void dump() const = 0; /// Manipulate geometry using facroy converter virtual void apply(const char* factory, int argc, char** argv) = 0; /// Extend the sensitive detector element with an arbitrary structure accessible by the type - template<typename IFACE, typename CONCRETE> IFACE* addExtension(CONCRETE* c) - { return (IFACE*)addUserExtension(dynamic_cast<IFACE*>(c),typeid(IFACE)); } + template <typename IFACE, typename CONCRETE> IFACE* addExtension(CONCRETE* c) { + return (IFACE*) addUserExtension(dynamic_cast<IFACE*>(c), typeid(IFACE)); + } /// Access extension element by the type - template <class T> T* extension() const - { return (T*)userExtension(typeid(T)); } + template <class T> T* extension() const { + return (T*) userExtension(typeid(T)); + } ///---Factory method------- static LCDD& getInstance(void); @@ -223,53 +221,61 @@ namespace DD4hep { /// Add an extension object to the detector element virtual void* addUserExtension(void* ptr, const std::type_info& info) = 0; /// Access an existing extension object from the detector element - virtual void* userExtension(const std::type_info& info) const = 0; + virtual void* userExtension(const std::type_info& info) const = 0; }; - /* * The following are convenience implementations to access constants by type. - * I do not think this violates the interface approach, but it is so much + * I do not think this violates the interface approach, but it is so much * more intuitiv to say constant<int>(name) than constantAsInt(name). */ #ifndef __CINT__ /// Typed access to constants: short values - template <> inline short LCDD::constant<short>(const std::string& name) const - { return (short)constantAsLong(name); } + template <> inline short LCDD::constant<short>(const std::string& name) const { + return (short) constantAsLong(name); + } /// Typed access to constants: unsigned short values - template <> inline unsigned short LCDD::constant<unsigned short>(const std::string& name) const - { return (unsigned short)constantAsLong(name); } + template <> inline unsigned short LCDD::constant<unsigned short>(const std::string& name) const { + return (unsigned short) constantAsLong(name); + } /// Typed access to constants: integer values - template <> inline int LCDD::constant<int>(const std::string& name) const - { return (int)constantAsLong(name); } + template <> inline int LCDD::constant<int>(const std::string& name) const { + return (int) constantAsLong(name); + } /// Typed access to constants: unsigned integer values - template <> inline unsigned int LCDD::constant<unsigned int>(const std::string& name) const - { return (unsigned int)constantAsLong(name); } + template <> inline unsigned int LCDD::constant<unsigned int>(const std::string& name) const { + return (unsigned int) constantAsLong(name); + } /// Typed access to constants: long values - template <> inline long LCDD::constant<long>(const std::string& name) const - { return constantAsLong(name); } + template <> inline long LCDD::constant<long>(const std::string& name) const { + return constantAsLong(name); + } /// Typed access to constants: unsigned long values - template <> inline unsigned long LCDD::constant<unsigned long>(const std::string& name) const - { return (unsigned long)constantAsLong(name); } + template <> inline unsigned long LCDD::constant<unsigned long>(const std::string& name) const { + return (unsigned long) constantAsLong(name); + } /// Typed access to constants: float values - template <> inline float LCDD::constant<float>(const std::string& name) const - { return (float)constantAsDouble(name); } + template <> inline float LCDD::constant<float>(const std::string& name) const { + return (float) constantAsDouble(name); + } /// Typed access to constants: double values - template <> inline double LCDD::constant<double>(const std::string& name) const - { return constantAsDouble(name); } + template <> inline double LCDD::constant<double>(const std::string& name) const { + return constantAsDouble(name); + } /// Typed access to constants: string values - template <> inline std::string LCDD::constant<std::string>(const std::string& name) const - { return constantAsString(name); } + template <> inline std::string LCDD::constant<std::string>(const std::string& name) const { + return constantAsString(name); + } #endif - } /* End namespace Geometry */ -} /* End namespace DD4hep */ + } /* End namespace Geometry */ +} /* End namespace DD4hep */ #endif /* DD4HEP_LCDD_LCDD_H */ diff --git a/DDCore/include/DD4hep/Objects.h b/DDCore/include/DD4hep/Objects.h index 59df82c70..6e23aa159 100644 --- a/DDCore/include/DD4hep/Objects.h +++ b/DDCore/include/DD4hep/Objects.h @@ -41,10 +41,9 @@ class TGeoIdentity; #define _USE_MATH_DEFINES #include <cmath> #ifndef M_PI - #define M_PI 3.14159265358979323846 +#define M_PI 3.14159265358979323846 #endif - /* * DD4hep namespace declaration */ @@ -53,31 +52,36 @@ namespace DD4hep { /* * Geoemtry namespace declaration */ - namespace Geometry { + namespace Geometry { // Forward declarations struct LCDD; class IDDescriptor; - /** Access to identity transformation */ TGeoIdentity* identityTransform(); /** @class Author Objects.h - * + * * @author M.Frank * @version 1.0 */ - struct Author : public Ref_t { + struct Author: public Ref_t { /// Definition of the implementation type typedef TNamed Object; /// Default constructor - Author() : Ref_t() {} + Author() + : Ref_t() { + } /// Constructorto be used for assignment from a handle - Author(const Author& e) : Ref_t(e) {} + Author(const Author& e) + : Ref_t(e) { + } /// Constructor to be used when reading the already parsed DOM tree - template <typename Q> - Author(const Handle<Q>& e) : Ref_t(e) {} + template <typename Q> + Author(const Handle<Q>& e) + : Ref_t(e) { + } /// Constructor to be used when creating a new DOM tree Author(LCDD& doc); /// Access the auhor's name @@ -90,92 +94,108 @@ namespace DD4hep { void setAuthorEmail(const std::string& addr); }; - /** @class Header Objects.h - * + * * Description of the geometry header. Containes useful auxiliary information. * * @author M.Frank * @version 1.0 */ - struct Header : public Ref_t { - struct Object : public TNamed { - std::string url; - std::string author; - std::string status; - std::string version; - std::string comment; - /// Standard constructor - Object(); - /// Default destructor - virtual ~Object(); + struct Header: public Ref_t { + struct Object: public TNamed { + std::string url; + std::string author; + std::string status; + std::string version; + std::string comment; + /// Standard constructor + Object(); + /// Default destructor + virtual ~Object(); }; /// Default constructor - Header() : Ref_t() {} + Header() + : Ref_t() { + } /// Constructorto be used for assignment from a handle - Header(const Header& e) : Ref_t(e) {} + Header(const Header& e) + : Ref_t(e) { + } /// Constructor to be used when reading the already parsed DOM tree - template <typename Q> Header(const Handle<Q>& e) : Ref_t(e) {} + template <typename Q> Header(const Handle<Q>& e) + : Ref_t(e) { + } /// Constructor to be used when creating a new DOM tree Header(const std::string& author, const std::string& url); /// Accessor to object name - const std::string name() const; + const std::string name() const; /// Accessor: set object name void setName(const std::string& new_name); /// Accessor to object title - const std::string title() const; + const std::string title() const; /// Accessor: set object title void setTitle(const std::string& new_title); /// Accessor to object author - const std::string& author() const; + const std::string& author() const; /// Accessor: set object author void setAuthor(const std::string& new_author); /// Accessor to object url - const std::string& url() const; + const std::string& url() const; /// Accessor: set object url void setUrl(const std::string& new_url); /// Accessor to object status - const std::string& status() const; + const std::string& status() const; /// Accessor: set object status void setStatus(const std::string& new_status); /// Accessor to object version - const std::string& version() const; + const std::string& version() const; /// Accessor: set object version void setVersion(const std::string& new_version); /// Accessor to object comment - const std::string& comment() const; + const std::string& comment() const; /// Accessor: set object comment void setComment(const std::string& new_comment); }; /** @class Constant Objects.h - * + * * @author M.Frank * @version 1.0 */ - struct Constant : public Ref_t { + struct Constant: public Ref_t { /// Definition of the implementation type typedef TNamed Object; /// Default constructor - Constant() : Ref_t() {} + Constant() + : Ref_t() { + } /// Constructorto be used for assignment from a handle - Constant(const Constant& e) : Ref_t(e) {} + Constant(const Constant& e) + : Ref_t(e) { + } /// Constructor to be used when reading the already parsed DOM tree - template <typename Q> - Constant(const Handle<Q>& e) : Ref_t(e) {} + template <typename Q> + Constant(const Handle<Q>& e) + : Ref_t(e) { + } /// Constructor to be used when creating a new DOM tree Constant(const std::string& name); /// Constructor to be used when creating a new DOM tree Constant(const std::string& name, const std::string& val); /// String representation of this object - std::string toString() const; + std::string toString() const; }; typedef ROOT::Math::XYZVector Position; - template <class V> V RotateX(const V& v, double a) { return ROOT::Math::VectorUtil::RotateX(v,a); } - template <class V> V RotateY(const V& v, double a) { return ROOT::Math::VectorUtil::RotateY(v,a); } - template <class V> V RotateZ(const V& v, double a) { return ROOT::Math::VectorUtil::RotateZ(v,a); } - + template <class V> V RotateX(const V& v, double a) { + return ROOT::Math::VectorUtil::RotateX(v, a); + } + template <class V> V RotateY(const V& v, double a) { + return ROOT::Math::VectorUtil::RotateY(v, a); + } + template <class V> V RotateZ(const V& v, double a) { + return ROOT::Math::VectorUtil::RotateZ(v, a); + } /** Rotation class with the (3D) rotation represented by * angles describing first a rotation of @@ -187,58 +207,70 @@ namespace DD4hep { * (Z-X-Z or 313 sequence) which is used by the ROOT::Math::EulerAngles class. * @see http://root.cern.ch/root/html/ROOT__Math__RotationZYX.html */ - typedef ROOT::Math::RotationZYX RotationZYX; + typedef ROOT::Math::RotationZYX RotationZYX; /** @see http://root.cern.ch/root/html/ROOT__Math__RotationZ.html */ - typedef ROOT::Math::RotationZ RotationZ; + typedef ROOT::Math::RotationZ RotationZ; /** @see http://root.cern.ch/root/html/ROOT__Math__RotationY.html */ - typedef ROOT::Math::RotationY RotationY; + typedef ROOT::Math::RotationY RotationY; /** @see http://root.cern.ch/root/html/ROOT__Math__RotationX.html */ - typedef ROOT::Math::RotationX RotationX; + typedef ROOT::Math::RotationX RotationX; /** @see http://root.cern.ch/root/html/ROOT__Math__Rotation3D.html */ - typedef ROOT::Math::Rotation3D Rotation3D; + typedef ROOT::Math::Rotation3D Rotation3D; /** @see http://root.cern.ch/root/html/ROOT__Math__EulerAngels.html */ - typedef ROOT::Math::EulerAngles EulerAngles; + typedef ROOT::Math::EulerAngles EulerAngles; /** @see http://root.cern.ch/root/html/ROOT__Math__Transform3D.html */ - typedef ROOT::Math::Transform3D Transform3D; + typedef ROOT::Math::Transform3D Transform3D; /** @see http://root.cern.ch/root/html/ROOT__Math__Translations3D.html */ typedef ROOT::Math::Translation3D Translation3D; /** @class Atom Objects.h - * + * * @author M.Frank * @version 1.0 */ - struct Atom : public Handle<TGeoElement> { + struct Atom: public Handle<TGeoElement> { /// Definition of the implementation type typedef TGeoElement Object; /// Default constructor - Atom() : Handle<TGeoElement>() {} + Atom() + : Handle<TGeoElement>() { + } /// Constructorto be used for assignment from a handle - Atom(const Handle<TGeoElement>& e) : Handle<TGeoElement>(e) {} + Atom(const Handle<TGeoElement>& e) + : Handle<TGeoElement>(e) { + } /// Constructor to be used when creating from a object handle - template <typename Q> - Atom(const Handle<Q>& e) : Handle<TGeoElement>(e) {} + template <typename Q> + Atom(const Handle<Q>& e) + : Handle<TGeoElement>(e) { + } /// Constructor to be used when reading the already parsed DOM tree Atom(const std::string& name, const std::string& formula, int Z, int N, double density); }; /** @class Material Objects.h - * + * * @author M.Frank * @version 1.0 */ - struct Material : public Handle<TGeoMedium> { + struct Material: public Handle<TGeoMedium> { /// Definition of the implementation type typedef TGeoMedium Object; /// Default constructor - Material() : Handle<TGeoMedium>() {} + Material() + : Handle<TGeoMedium>() { + } /// Constructorto be used for assignment from material handle - Material(const Handle<TGeoMedium>& e) : Handle<TGeoMedium>(e) {} + Material(const Handle<TGeoMedium>& e) + : Handle<TGeoMedium>(e) { + } /// Constructorto be used for assignment from object handle - template <typename Q> - Material(const Handle<Q>& e) : Handle<TGeoMedium>(e) {} + template <typename Q> + Material(const Handle<Q>& e) + : Handle<TGeoMedium>(e) { + } /// String representation of this object - std::string toString() const; + std::string toString() const; /// Access the radiation length of the underlying material double radLength() const; /// Access the interaction length of the underlying material @@ -246,39 +278,45 @@ namespace DD4hep { }; /** @class VisAttr Objects.h - * + * * @author M.Frank * @version 1.0 */ - struct VisAttr : public Ref_t { - enum Style { - SOLID=0x1, - WIREFRAME=0x2, - DASHED=0x2, - LAST_STYLE + struct VisAttr: public Ref_t { + enum Style { + SOLID = 0x1, WIREFRAME = 0x2, DASHED = 0x2, LAST_STYLE }; - struct Object : public TNamed { - unsigned long magic; - void* col; - int color; - float alpha; + struct Object: public TNamed { + unsigned long magic; + void* col; + int color; + float alpha; unsigned char drawingStyle, lineStyle, showDaughters, visible; - /// Standard constructor - Object(); - /// Default destructor - virtual ~Object(); + /// Standard constructor + Object(); + /// Default destructor + virtual ~Object(); }; /// Default constructor - VisAttr() : Ref_t() {} + VisAttr() + : Ref_t() { + } /// Constructor to be used for assignment from object handle - template <typename Q> - VisAttr(const Handle<Q>& e) : Ref_t(e) {} + template <typename Q> + VisAttr(const Handle<Q>& e) + : Ref_t(e) { + } /// Copy constructor for handle - VisAttr(const VisAttr& e) : Ref_t(e) {} + VisAttr(const VisAttr& e) + : Ref_t(e) { + } /// Constructor to be used when creating a new registered visualization object VisAttr(const std::string& name); /// Assignment operator - VisAttr& operator=(const VisAttr& attr) { m_element = attr.m_element; return *this; } + VisAttr& operator=(const VisAttr& attr) { + m_element = attr.m_element; + return *this; + } /// Get Flag to show/hide daughter elements bool showDaughters() const; @@ -296,7 +334,7 @@ namespace DD4hep { void setLineStyle(int style); /// Get drawing style - int drawingStyle() const; + int drawingStyle() const; /// Set drawing style void setDrawingStyle(int style); @@ -306,7 +344,7 @@ namespace DD4hep { void setAlpha(float value); /// Get object color - int color() const; + int color() const; /// Set object color void setColor(float red, float green, float blue); @@ -314,35 +352,36 @@ namespace DD4hep { bool rgb(float& red, float& green, float& blue) const; /// String representation of this object - std::string toString() const; + std::string toString() const; }; /**@class AligmentEntry - * - * Class representing an alignment entry + * + * Class representing an alignment entry * * @author M.Frank * @version 1.0 */ - struct AlignmentEntry : public Handle<TGeoPhysicalNode> { + struct AlignmentEntry: public Handle<TGeoPhysicalNode> { typedef Handle<TGeoPhysicalNode> Base; /// Constructor to be used when reading the already parsed DOM tree - template <typename Q> - AlignmentEntry(const Handle<Q>& h) : Base(h) {} + template <typename Q> + AlignmentEntry(const Handle<Q>& h) + : Base(h) { + } /// Constructor to be used when creating a new aligment entry AlignmentEntry(const std::string& path); /// Align the PhysicalNode (translation only) - int align(const Position& pos, bool check=false, double overlap=0.001); + int align(const Position& pos, bool check = false, double overlap = 0.001); /// Align the PhysicalNode (rotation only) - int align(const RotationZYX& rot, bool check=false, double overlap=0.001); + int align(const RotationZYX& rot, bool check = false, double overlap = 0.001); /// Align the PhysicalNode (translation + rotation) - int align(const Position& pos, const RotationZYX& rot, bool check=false, double overlap=0.001); + int align(const Position& pos, const RotationZYX& rot, bool check = false, double overlap = 0.001); }; - /** @class Limit Objects.h - * Small object describing a limit structure - * + * Small object describing a limit structure + * * @author M.Frank * @version 1.0 */ @@ -351,38 +390,46 @@ namespace DD4hep { std::string name; std::string unit; std::string content; - double value; + double value; /// Default constructor - Limit() : particles(), name(), unit(), content(), value(0.0) {} + Limit() + : particles(), name(), unit(), content(), value(0.0) { + } /// Copy constructor - Limit(const Limit& c) : particles(c.particles), name(c.name), unit(c.unit), content(c.content), value(c.value) {} + Limit(const Limit& c) + : particles(c.particles), name(c.name), unit(c.unit), content(c.content), value(c.value) { + } /// Assignment operator Limit& operator=(const Limit& c); /// Equality operator bool operator==(const Limit& c) const; /// operator less - bool operator< (const Limit& c) const; + bool operator<(const Limit& c) const; /// Conversion to a string representation - std::string toString() const; + std::string toString() const; }; /** @class LimitSet Objects.h - * + * * @author M.Frank * @version 1.0 */ - struct LimitSet : public Ref_t { - struct Object : public TNamed, public std::set<Limit> { - /// Standard constructor - Object(); - /// Default destructor - virtual ~Object(); + struct LimitSet: public Ref_t { + struct Object: public TNamed, public std::set<Limit> { + /// Standard constructor + Object(); + /// Default destructor + virtual ~Object(); }; /// Constructor to be used when reading the already parsed DOM tree - LimitSet() : Ref_t() {} + LimitSet() + : Ref_t() { + } /// Constructor to be used when reading the already parsed DOM tree - template <typename Q> - LimitSet(const Handle<Q>& e) : Ref_t(e) {} + template <typename Q> + LimitSet(const Handle<Q>& e) + : Ref_t(e) { + } /// Constructor to be used when creating a new object LimitSet(const std::string& name); /// Add new limit. Returns true if the new limit was added, false if it already existed. @@ -392,28 +439,32 @@ namespace DD4hep { }; /** @class Region Objects.h - * + * * @author M.Frank * @version 1.0 */ - struct Region : public Ref_t { - struct Object : public TNamed { - unsigned long magic; - double threshold; - double cut; - bool store_secondaries; - std::string lunit, eunit; - std::vector<std::string> user_limits; - /// Standard constructor - Object(); - /// Default destructor - virtual ~Object(); + struct Region: public Ref_t { + struct Object: public TNamed { + unsigned long magic; + double threshold; + double cut; + bool store_secondaries; + std::string lunit, eunit; + std::vector<std::string> user_limits; + /// Standard constructor + Object(); + /// Default destructor + virtual ~Object(); }; /// Default constructor - Region() : Ref_t() {} + Region() + : Ref_t() { + } /// Constructor to be used when reading the already parsed DOM tree - template <typename Q> - Region(const Handle<Q>& e) : Ref_t(e) {} + template <typename Q> + Region(const Handle<Q>& e) + : Ref_t(e) { + } /// Constructor to be used when creating a new object Region(const std::string& name); @@ -426,7 +477,7 @@ namespace DD4hep { std::vector<std::string>& limits() const; /// Access cut value - double cut() const; + double cut() const; /// Access production threshold double threshold() const; /// Access secondaries flag @@ -437,22 +488,26 @@ namespace DD4hep { const std::string& energyUnit() const; }; - } /* End namespace Geometry */ -} /* End namespace DD4hep */ - + } /* End namespace Geometry */ +} /* End namespace DD4hep */ -namespace ROOT { namespace Math { +namespace ROOT { + namespace Math { typedef DD4hep::Geometry::Position Position; /// Dot product of 3-vectors. - inline double operator * (const Position& l, const Position& r) - { return sqrt(l.X()*r.X() + l.Y()*r.Y() + l.Z()*r.Z()); } + inline double operator *(const Position& l, const Position& r) { + return sqrt(l.X() * r.X() + l.Y() * r.Y() + l.Z() * r.Z()); + } /// Calculate the mean length of two vectors - inline double mean_length(const Position& p1, const Position& p2) - { return 0.5* (p1.R() + p2.R()) / 2.0; } + inline double mean_length(const Position& p1, const Position& p2) { + return 0.5 * (p1.R() + p2.R()) / 2.0; + } /// Calculate the mean direction of two vectors - inline Position mean_direction(const Position& p1, const Position& p2) - { return 0.5 * (p1 + p2); } + inline Position mean_direction(const Position& p1, const Position& p2) { + return 0.5 * (p1 + p2); + } -}} + } +} #endif /* DD4HEP_GEOMETRY_OBJECTS_H */ diff --git a/DDCore/include/DD4hep/Plugins.h b/DDCore/include/DD4hep/Plugins.h index 2aa41e9cd..087a2d1bc 100644 --- a/DDCore/include/DD4hep/Plugins.h +++ b/DDCore/include/DD4hep/Plugins.h @@ -16,11 +16,11 @@ * DD4hep namespace declaration */ namespace DD4hep { - + typedef ROOT::Reflex::PluginService PluginService; /** @class PluginDebug. PluginDebug.h DD4hep/PluginDebug.h - * + * * Small helper class to adjust the plugin service debug level * for a limited code scope. Automatically back-adjusts the debug * level at object destruction. @@ -31,12 +31,12 @@ namespace DD4hep { struct PluginDebug { int m_debug; /// Default constructor - PluginDebug(int dbg=2); + PluginDebug(int dbg = 2); /// Default destructor ~PluginDebug(); /// Helper to check factory existence std::string missingFactory(const std::string& name) const; }; -} /* End namespace DD4hep */ +} /* End namespace DD4hep */ #endif /* DD4HEP_PLUGINS_H */ diff --git a/DDCore/include/DD4hep/Primitives.h b/DDCore/include/DD4hep/Primitives.h index 3c8799e1a..d119cfdb8 100644 --- a/DDCore/include/DD4hep/Primitives.h +++ b/DDCore/include/DD4hep/Primitives.h @@ -22,7 +22,8 @@ namespace DD4hep { /// Helper to delete objects from heap and reset the pointer. Saves many many lines of code template <typename T> inline void deletePtr(T*& p) { - if ( 0 != p ) delete p; + if (0 != p) + delete p; p = 0; } /// Helper to delete objects from heap and reset the pointer @@ -31,51 +32,81 @@ namespace DD4hep { } /// Functor to delete objects from heap and reset the pointer template <typename T> struct DestroyObject { - void operator()(T& p) const { + void operator()(T& p) const { destroyObject(p); } }; /// map Functor to delete objects from heap template <typename M> struct DestroyObjects { M& object; - DestroyObjects(M& m) : object(m) {} - ~DestroyObjects() { object.clear(); } - void operator()(std::pair<typename M::key_type,typename M::mapped_type> p) const { - DestroyObject<typename M::mapped_type>()(p.second); + DestroyObjects(M& m) + : object(m) { + } + ~DestroyObjects() { + object.clear(); + } + void operator()(std::pair<typename M::key_type, typename M::mapped_type> p) const { + DestroyObject<typename M::mapped_type>()(p.second); } }; - template<typename M> DestroyObjects<M> destroyObjects(M& m) { return DestroyObjects<M>(m); } + template <typename M> DestroyObjects<M> destroyObjects(M& m) { + return DestroyObjects<M>(m); + } + + /// map Functor to delete objects from heap + template <typename M> struct DestroyFirst { + M& object; + DestroyFirst(M& m) + : object(m) { + } + ~DestroyFirst() { + object.clear(); + } + void operator()(std::pair<typename M::key_type, typename M::mapped_type> p) const { + DestroyObject<typename M::key_type>()(p.first); + } + }; + template <typename M> DestroyFirst<M> destroyFirst(M& m) { + return DestroyFirst<M>(m); + } /// Helper to delete objects from heap and reset the pointer. Saves many many lines of code template <typename T> inline void releasePtr(T*& p) { - if ( 0 != p ) p->release(); + if (0 != p) + p->release(); p = 0; } /// Functor to delete objects from heap and reset the pointer template <typename T> struct ReleaseObject { - void operator()(T& p) const { + void operator()(T& p) const { releasePtr(p); } }; /// map Functor to delete objects from heap template <typename M> struct ReleaseObjects { M& object; - ReleaseObjects(M& m) : object(m) {} - ~ReleaseObjects() { object.clear(); } - void operator()(std::pair<typename M::key_type,typename M::mapped_type> p) const { - ReleaseObject<typename M::mapped_type>()(p.second); + ReleaseObjects(M& m) + : object(m) { + } + ~ReleaseObjects() { + object.clear(); + } + void operator()(std::pair<typename M::key_type, typename M::mapped_type> p) const { + ReleaseObject<typename M::mapped_type>()(p.second); } }; - template<typename M> ReleaseObjects<M> releaseObjects(M& m) { return ReleaseObjects<M>(m); } - + template <typename M> ReleaseObjects<M> releaseObjects(M& m) { + return ReleaseObjects<M>(m); + } + /* * Geometry namespace declaration */ namespace Geometry { - // Put here global basic type defintiions derived from primitive types of the Geometry namespace + // Put here global basic type defintiions derived from primitive types of the Geometry namespace - } // End namespace Geometry + }// End namespace Geometry } // End namespace DD4hep #endif // DD4HEP_DD4HEP_PRIMITIVES_H diff --git a/DDCore/include/DD4hep/Printout.h b/DDCore/include/DD4hep/Printout.h index f686a7e50..c17d7bc18 100644 --- a/DDCore/include/DD4hep/Printout.h +++ b/DDCore/include/DD4hep/Printout.h @@ -28,9 +28,9 @@ class TNamed; * DD4hep namespace declaration */ namespace DD4hep { - - /// Forward declarations - namespace Geometry { + +/// Forward declarations + namespace Geometry { template <typename T> struct Handle; class LCDD; class VisAttr; @@ -39,14 +39,7 @@ namespace DD4hep { } enum PrintLevel { - NOLOG=0, - VERBOSE, - DEBUG, - INFO, - WARNING, - ERROR, - FATAL, - ALWAYS + NOLOG = 0, VERBOSE, DEBUG, INFO, WARNING, ERROR, FATAL, ALWAYS }; typedef size_t (*output_function_t)(void*, PrintLevel severity, const char*, const char*); @@ -134,11 +127,10 @@ namespace DD4hep { */ std::string format(const std::string& src, const std::string& fmt, va_list& args); - - /// Set new print level. Returns the old print level +/// Set new print level. Returns the old print level PrintLevel setPrintLevel(PrintLevel new_level); - /// Customize printer function +/// Customize printer function void setPrinter(void* print_arg, output_function_t fcn); /** @class Printer Conversions.h DD4hep/compact/Conversions.h @@ -148,23 +140,24 @@ namespace DD4hep { * @author M.Frank * @version 1.0 */ - template <typename T> struct Printer { + template <typename T> struct Printer { /// Reference to the detector description object - const Geometry::LCDD* lcdd; + const Geometry::LCDD* lcdd; /// Reference to the output stream object, the Printer object should write - std::ostream& os; + std::ostream& os; /// Optional text prefix when formatting the output - std::string prefix; + std::string prefix; /// Initializing constructor of the functor - Printer(const Geometry::LCDD* l, std::ostream& stream, const std::string& p="") - : lcdd(l), os(stream), prefix(p) {} + Printer(const Geometry::LCDD* l, std::ostream& stream, const std::string& p = "") + : lcdd(l), os(stream), prefix(p) { + } /// Callback operator to be specialized depending on the element type void operator()(const T& value) const; }; - template <typename T> inline - std::ostream& print(const T& object,std::ostream& os=std::cout,const std::string& indent="") { - Printer<T>(0,os,indent)(object); + template <typename T> inline std::ostream& print(const T& object, std::ostream& os = std::cout, + const std::string& indent = "") { + Printer<T>(0, os, indent)(object); return os; } @@ -177,27 +170,32 @@ namespace DD4hep { */ template <typename T> struct PrintMap { typedef T item_type; - typedef const std::map<std::string,Geometry::Handle<TNamed> > cont_type; + typedef const std::map<std::string, Geometry::Handle<TNamed> > cont_type; /// Reference to the detector description object - const Geometry::LCDD* lcdd; + const Geometry::LCDD* lcdd; /// Reference to the output stream object, the Printer object should write - std::ostream& os; + std::ostream& os; /// Optional text prefix when formatting the output - std::string text; + std::string text; /// Reference to the container data of the map. - cont_type& cont; + cont_type& cont; /// Initializing constructor of the functor - PrintMap(const Geometry::LCDD* l, std::ostream& stream, cont_type& c, const std::string& t="") - : lcdd(l), os(stream), text(t), cont(c) {} + PrintMap(const Geometry::LCDD* l, std::ostream& stream, cont_type& c, const std::string& t = "") + : lcdd(l), os(stream), text(t), cont(c) { + } /// Callback operator to be specialized depending on the element type void operator()() const; }; - /// Helper function to print booleans in format YES/NO - inline const char* yes_no(bool value) { return value ? "YES" : "NO "; } - /// Helper function to print booleans in format true/false - inline const char* true_false(bool value) { return value ? "true " : "false"; } +/// Helper function to print booleans in format YES/NO + inline const char* yes_no(bool value) { + return value ? "YES" : "NO "; + } +/// Helper function to print booleans in format true/false + inline const char* true_false(bool value) { + return value ? "true " : "false"; + } -} /* End namespace DD4hep */ +} /* End namespace DD4hep */ #endif /* DD4HEP_PRINTOUT_H */ diff --git a/DDCore/include/DD4hep/Readout.h b/DDCore/include/DD4hep/Readout.h index cdecee6d0..328c5eef6 100644 --- a/DDCore/include/DD4hep/Readout.h +++ b/DDCore/include/DD4hep/Readout.h @@ -24,105 +24,121 @@ namespace DD4hep { /* * Geometry namespace declaration */ - namespace Geometry { + namespace Geometry { - class DetElement; + class DetElement; /** @class Readout Readout.h DD4hep/Readout.h - * - * @author M.Frank - * @version 1.0 - */ - struct Readout : public Ref_t { + * + * @author M.Frank + * @version 1.0 + */ + struct Readout: public Ref_t { public: - + /** @class Readout::Object Readout.h DD4hep/Readout.h * * @author M.Frank * @version 1.0 */ - struct Object : public TNamed { - /// Handle to the readout segmentation + struct Object: public TNamed { + /// Handle to the readout segmentation Segmentation segmentation; - /// Handle to the volume + /// Handle to the volume Volume readoutWorld; - /// Handle to the field descriptor + /// Handle to the field descriptor IDDescriptor id; - /// Standard constructor - Object(); - /// Default destructor - virtual ~Object(); + /// Standard constructor + Object(); + /// Default destructor + virtual ~Object(); }; public: /// Default constructor - Readout() : Ref_t() {} + Readout() + : Ref_t() { + } /// Constructor to be used when reading the already parsed object - template <typename Q> Readout(const Handle<Q>& e) : Ref_t(e) {} + template <typename Q> Readout(const Handle<Q>& e) + : Ref_t(e) { + } /// Initializing constructor Readout(const std::string& name); /// Assign IDDescription to readout structure - void setIDDescriptor(const Ref_t& spec) const; + void setIDDescriptor(const Ref_t& spec) const; /// Access IDDescription structure IDDescriptor idSpec() const; /// Assign segmentation structure to readout void setSegmentation(const Segmentation& segment) const; /// Access segmentation structure - Segmentation segmentation() const; + Segmentation segmentation() const; /// ID decoder interface PlacedVolume getPlacement(const long64& cellID) const; - DetElement getSubDetector(const long64& cellID) const; - DetElement getDetectorElement(const long64& cellID) const; - Position getPosition(const long64& cellID) const; - Position getLocalPosition(const long64& cellID) const; + DetElement getSubDetector(const long64& cellID) const; + DetElement getDetectorElement(const long64& cellID) const; + Position getPosition(const long64& cellID) const; + Position getLocalPosition(const long64& cellID) const; const TGeoMatrix& getWorldTransformation(const long64& cellID) const; }; /** @class Alignment Readoutn.h DD4hep/lcdd/Readout.h - * - * @author M.Frank - * @version 1.0 - */ - struct Alignment : public Ref_t { - struct Object : public TNamed { + * + * @author M.Frank + * @version 1.0 + */ + struct Alignment: public Ref_t { + struct Object: public TNamed { Volume volume; - /// Standard constructor - Object(); - /// Default destructor - virtual ~Object(); + /// Standard constructor + Object(); + /// Default destructor + virtual ~Object(); }; /// Default constructor - Alignment() : Ref_t() {} + Alignment() + : Ref_t() { + } /// Constructor to be used when reading the already parsed object - template <typename Q> Alignment(const Handle<Q>& e) : Ref_t(e) {} + template <typename Q> Alignment(const Handle<Q>& e) + : Ref_t(e) { + } /// Initializing constructor Alignment(const LCDD& doc, const std::string& name); /// Additional data accessor - Object& _data() const { return *data<Object>(); } + Object& _data() const { + return *data<Object>(); + } }; /** @class Conditions Readout.h DD4hep/lcdd/Readout.h - * - * @author M.Frank - * @version 1.0 - */ - struct Conditions : public Ref_t { - struct Object : public TNamed { - /// Standard constructor - Object(); - /// Default destructor - virtual ~Object(); + * + * @author M.Frank + * @version 1.0 + */ + struct Conditions: public Ref_t { + struct Object: public TNamed { + /// Standard constructor + Object(); + /// Default destructor + virtual ~Object(); }; /// Default constructor - Conditions() : Ref_t() {} + Conditions() + : Ref_t() { + } /// Constructor to be used when reading the already parsed object - template <typename Q> Conditions(const Handle<Q>& e) : Ref_t(e) {} + template <typename Q> Conditions(const Handle<Q>& e) + : Ref_t(e) { + } /// Initializing constructor Conditions(const LCDD& doc, const std::string& name); /// Additional data accessor - Object& _data() const { return *data<Object>(); } + Object& _data() const { + return *data<Object>(); + } }; - } /* End namespace Geometry */ -} /* End namespace DD4hep */ + } /* End namespace Geometry */ +} /* End namespace DD4hep */ #endif /* DD4hep_GEOMETRY_READOUT_H */ diff --git a/DDCore/include/DD4hep/Segmentations.h b/DDCore/include/DD4hep/Segmentations.h index 885cb5f55..51d512fd0 100644 --- a/DDCore/include/DD4hep/Segmentations.h +++ b/DDCore/include/DD4hep/Segmentations.h @@ -22,11 +22,11 @@ * DD4hep namespace declaration */ namespace DD4hep { - + /* * XML namespace declaration */ - namespace Geometry { + namespace Geometry { typedef DDSegmentation::BitField64 BitField64; @@ -35,7 +35,7 @@ namespace DD4hep { * @author M.Frank * @version 1.0 */ - struct Segmentation : public Handle<DDSegmentation::Segmentation> { + struct Segmentation: public Handle<DDSegmentation::Segmentation> { public: typedef DDSegmentation::Segmentation BaseSegmentation; @@ -44,30 +44,34 @@ namespace DD4hep { * @author M.Frank * @version 1.0 */ - struct Object { + struct Object { /// Magic word to check object integrity unsigned long magic; /// Flag to use segmentation for hit positioning unsigned char useForHitPosition; - /// Reference to base segmentation - BaseSegmentation* segmentation; - /// Standard constructor + /// Reference to base segmentation + BaseSegmentation* segmentation; + /// Standard constructor Object(); - /// Default destructor + /// Default destructor virtual ~Object(); }; public: /// Default constructor - Segmentation() : Handle<Implementation>() {} + Segmentation() + : Handle<Implementation>() { + } /// Initializing constructor creating new object template <typename T> Segmentation(T* o, const std::string& nam, const std::string& typ) - : Handle<Implementation>() { - o->segmentation = o; - assign(o,nam,typ); + : Handle<Implementation>() { + o->segmentation = o; + assign(o, nam, typ); } /// Constructor to be used when reading the already parsed object - template <typename Q> Segmentation(const Handle<Q>& e) : Handle<Implementation>(e) {} + template <typename Q> Segmentation(const Handle<Q>& e) + : Handle<Implementation>(e) { + } /// Access flag for hit positioning bool useForHitPosition() const; /// Accessor: Segmentation type @@ -87,14 +91,16 @@ namespace DD4hep { * @author M.Frank * @version 1.0 */ - struct SegmentationParams : public Segmentation { + struct SegmentationParams: public Segmentation { public: /// Segmentation parameter definition - typedef std::pair<std::string,double> Parameter; + typedef std::pair<std::string, double> Parameter; /// Segmentation parameter container definition - typedef std::vector<Parameter> Parameters; + typedef std::vector<Parameter> Parameters; /// Constructor to be used when reading the already parsed object - SegmentationParams(const Segmentation& e) : Segmentation(e) {} + SegmentationParams(const Segmentation& e) + : Segmentation(e) { + } /// Segmentation type std::string type() const; /// Access to the parameters @@ -106,25 +112,29 @@ namespace DD4hep { * @author M.Frank * @version 1.0 */ - struct ProjectiveCylinder : public Segmentation { + struct ProjectiveCylinder: public Segmentation { - struct Data : public Object, public BaseSegmentation { - int nphi; - int ntheta; - int nz; - /// Default constructor - Data(BitField64* decoder=0) : Object(), BaseSegmentation(decoder), nphi(0), ntheta(0), nz(0) {} - /// Default destructor - virtual ~Data(); - /// determine the position based on the cell ID - virtual std::vector<double> getPosition(const long64& cellID) const; - /// determine the local position based on the cell ID - virtual std::vector<double> getLocalPosition(const long64& cellID) const; - /// determine the cell ID based on the local position - virtual long64 getCellID(double x, double y, double z) const; + struct Data: public Object, public BaseSegmentation { + int nphi; + int ntheta; + int nz; + /// Default constructor + Data(BitField64* decoder = 0) + : Object(), BaseSegmentation(decoder), nphi(0), ntheta(0), nz(0) { + } + /// Default destructor + virtual ~Data(); + /// determine the position based on the cell ID + virtual std::vector<double> getPosition(const long64& cellID) const; + /// determine the local position based on the cell ID + virtual std::vector<double> getLocalPosition(const long64& cellID) const; + /// determine the cell ID based on the local position + virtual long64 getCellID(double x, double y, double z) const; }; /// Constructor to be used when reading the already parsed object - template <typename Q> ProjectiveCylinder(const Handle<Q>& e) : Segmentation(e) {} + template <typename Q> ProjectiveCylinder(const Handle<Q>& e) + : Segmentation(e) { + } /// Constructor to create a new segmentation object ProjectiveCylinder(LCDD& lcdd); /// Accessors: get number of bins in theta @@ -140,30 +150,35 @@ namespace DD4hep { /// Accessors: set number of bins in Z void setZBins(int value); }; - + /** @class NonProjectiveCylinder Segmentations.h DD4hep/Segmentations.h * * @author M.Frank * @version 1.0 */ - struct NonProjectiveCylinder : public Segmentation { - struct Data : public Object, public BaseSegmentation { - double grid_size_phi; - double grid_size_theta; - double grid_size_z; - /// Default constructor - Data(BitField64* decoder=0) : Object(), BaseSegmentation(decoder) { grid_size_phi=grid_size_theta=grid_size_z=0;} - /// Default destructor - virtual ~Data(); - /// determine the position based on the cell ID - virtual std::vector<double> getPosition(const long64& cellID) const; - /// determine the local position based on the cell ID - virtual std::vector<double> getLocalPosition(const long64& cellID) const; - /// determine the cell ID based on the local position - virtual long64 getCellID(double x, double y, double z) const; + struct NonProjectiveCylinder: public Segmentation { + struct Data: public Object, public BaseSegmentation { + double grid_size_phi; + double grid_size_theta; + double grid_size_z; + /// Default constructor + Data(BitField64* decoder = 0) + : Object(), BaseSegmentation(decoder) { + grid_size_phi = grid_size_theta = grid_size_z = 0; + } + /// Default destructor + virtual ~Data(); + /// determine the position based on the cell ID + virtual std::vector<double> getPosition(const long64& cellID) const; + /// determine the local position based on the cell ID + virtual std::vector<double> getLocalPosition(const long64& cellID) const; + /// determine the cell ID based on the local position + virtual long64 getCellID(double x, double y, double z) const; }; /// Constructor to be used when reading the already parsed object - template <typename Q> NonProjectiveCylinder(const Handle<Q>& e) : Segmentation(e) {} + template <typename Q> NonProjectiveCylinder(const Handle<Q>& e) + : Segmentation(e) { + } /// Constructor to create a new segmentation object NonProjectiveCylinder(LCDD& lcdd); /// Accessors: get size of bins in Z @@ -175,30 +190,35 @@ namespace DD4hep { /// Accessors: set grid size in Y void setPhiBinSize(double value); }; - + /** @class ProjectiveZPlane Segmentations.h DD4hep/Segmentations.h * * @author M.Frank * @version 1.0 */ - struct ProjectiveZPlane : public Segmentation { - struct Data : public Object, public BaseSegmentation { - int nphi; - int ntheta; - int nz; - /// Default constructor - Data(BitField64* decoder=0) : Object(), BaseSegmentation(decoder) { nphi=ntheta=nz=0;} - /// Default destructor - virtual ~Data(); - /// determine the position based on the cell ID - virtual std::vector<double> getPosition(const long64& cellID) const; - /// determine the local position based on the cell ID - virtual std::vector<double> getLocalPosition(const long64& cellID) const; - /// determine the cell ID based on the local position - virtual long64 getCellID(double x, double y, double z) const; + struct ProjectiveZPlane: public Segmentation { + struct Data: public Object, public BaseSegmentation { + int nphi; + int ntheta; + int nz; + /// Default constructor + Data(BitField64* decoder = 0) + : Object(), BaseSegmentation(decoder) { + nphi = ntheta = nz = 0; + } + /// Default destructor + virtual ~Data(); + /// determine the position based on the cell ID + virtual std::vector<double> getPosition(const long64& cellID) const; + /// determine the local position based on the cell ID + virtual std::vector<double> getLocalPosition(const long64& cellID) const; + /// determine the cell ID based on the local position + virtual long64 getCellID(double x, double y, double z) const; }; /// Constructor to be used when reading the already parsed object - template <typename Q> ProjectiveZPlane(const Handle<Q>& e) : Segmentation(e) {} + template <typename Q> ProjectiveZPlane(const Handle<Q>& e) + : Segmentation(e) { + } /// Constructor to create a new segmentation object ProjectiveZPlane(LCDD& lcdd); /// Accessors: get number of bins in theta @@ -210,21 +230,25 @@ namespace DD4hep { /// Accessors: set grid size in Y void setPhiBins(int value); }; - + /** @class GridXY Segmentations.h DD4hep/Segmentations.h * * @author M.Frank * @version 1.0 */ - struct GridXY : public Segmentation { - struct Data : public Object, public DDSegmentation::CartesianGridXY { - /// Default constructor - Data(BitField64* decoder=0) : Object(), DDSegmentation::CartesianGridXY(decoder) {} - /// Default destructor - virtual ~Data(); + struct GridXY: public Segmentation { + struct Data: public Object, public DDSegmentation::CartesianGridXY { + /// Default constructor + Data(BitField64* decoder = 0) + : Object(), DDSegmentation::CartesianGridXY(decoder) { + } + /// Default destructor + virtual ~Data(); }; /// Constructor to be used when reading the already parsed object - template <typename Q> GridXY(const Handle<Q>& e) : Segmentation(e) {} + template <typename Q> GridXY(const Handle<Q>& e) + : Segmentation(e) { + } /// Constructor to create a new segmentation object GridXY(LCDD& lcdd, const std::string& typ); /// Accessors: set grid size in X @@ -232,25 +256,29 @@ namespace DD4hep { /// Accessors: set grid size in Y void setGridSizeY(double value); /// Accessors: get grid size in X - double getGridSizeX() const; + double getGridSizeX() const; /// Accessors: get grid size in Y - double getGridSizeY() const; + double getGridSizeY() const; }; - + /** @class GridXYZ Segmentations.h DD4hep/Segmentations.h * * @author M.Frank * @version 1.0 */ - struct GridXYZ : public Segmentation { - struct Data : public Object, public DDSegmentation::CartesianGridXYZ { - /// Default constructor - Data(BitField64* decoder=0) : Object(), DDSegmentation::CartesianGridXYZ(decoder) {} - /// Default destructor - virtual ~Data(); + struct GridXYZ: public Segmentation { + struct Data: public Object, public DDSegmentation::CartesianGridXYZ { + /// Default constructor + Data(BitField64* decoder = 0) + : Object(), DDSegmentation::CartesianGridXYZ(decoder) { + } + /// Default destructor + virtual ~Data(); }; /// Constructor to be used when reading the already parsed object - template <typename Q> GridXYZ(const Handle<Q>& e) : GridXY(e) {} + template <typename Q> GridXYZ(const Handle<Q>& e) + : GridXY(e) { + } /// Constructor to be used when creating a new object. GridXYZ(LCDD& lcdd, const std::string& typ); /// Accessors: set grid size in X @@ -260,13 +288,13 @@ namespace DD4hep { /// Accessors: set grid size in Z void setGridSizeZ(double value); /// Accessors: get grid size in X - double getGridSizeX() const; + double getGridSizeX() const; /// Accessors: get grid size in Y - double getGridSizeY() const; + double getGridSizeY() const; /// Accessors: get grid size in Z - double getGridSizeZ() const; + double getGridSizeZ() const; }; - } /* End namespace Geometry */ -} /* End namespace DD4hep */ + } /* End namespace Geometry */ +} /* End namespace DD4hep */ #endif /* DD4HEP_GEOMETRY_SEGMENTATIONS_H */ diff --git a/DDCore/include/DD4hep/Shapes.h b/DDCore/include/DD4hep/Shapes.h index 2f748e69a..f068f9ef7 100644 --- a/DDCore/include/DD4hep/Shapes.h +++ b/DDCore/include/DD4hep/Shapes.h @@ -50,89 +50,87 @@ namespace DD4hep { /* * Geometry namespace declaration */ - namespace Geometry { + namespace Geometry { - // Forward declarations +// Forward declarations - /**@class Solid_type Shapes.h + /**@class Solid_type Shapes.h * * Base class for Solid objects * * @author M.Frank * @version 1.0 */ - template <typename T> struct Solid_type : public Handle<T> { - protected: + template <typename T> struct Solid_type: public Handle<T> { + protected: typedef T Implementation; void _setDimensions(double* param); /// Assign pointrs and register solid to geometry void _assign(Implementation* n, const std::string& nam, const std::string& tit, bool cbbox); - public: + public: /// Default constructor for uninitialized object - Solid_type() : Handle<Implementation>() {} + Solid_type() + : Handle<Implementation>() { + } - /// Direct assignment using the implementation pointer - Solid_type(Implementation* p) : Handle<Implementation>(p) {} + /// Direct assignment using the implementation pointer + Solid_type(Implementation* p) + : Handle<Implementation>(p) { + } /// Constructor to be used when reading the already parsed object - Solid_type(const Handle<Implementation>& e) : Handle<Implementation>(e) {} + Solid_type(const Handle<Implementation>& e) + : Handle<Implementation>(e) { + } /// Constructor to be used when reading the already parsed object: need to check pointers - template <typename Q> Solid_type(const Handle<Q>& e) : Handle<T>(e) {} + template <typename Q> Solid_type(const Handle<Q>& e) + : Handle<T>(e) { + } /// Access to shape name const char* name() const; /// Auto conversion to underlying ROOT object - operator Implementation*() const { return this->m_element; } + operator Implementation*() const { + return this->m_element; + } /// Overloaded operator -> to access underlying object - Implementation* operator->() const { return this->m_element; } + Implementation* operator->() const { + return this->m_element; + } }; typedef Solid_type<TGeoShape> Solid; - - /**@class Box Shapes.h + /**@class Box Shapes.h * * @author M.Frank * @version 1.0 */ - struct Box : public Solid_type<TGeoBBox> { - protected: + struct Box: public Solid_type<TGeoBBox> { + protected: void make(const std::string& name, double x, double y, double z); - public: + public: /// Constructor to be used when reading the already parsed box object - template <typename Q> - Box(const Handle<Q>& e) : Solid_type<Implementation>(e) {} - - /// Constructor to be used when creating an identifiable new box object - Box(const std::string& name) - { make(name, 0, 0, 0); } - - /// Constructor to be used when creating an anonymous new box object (retrieves name from volume) - Box() - { make("", 0, 0, 0); } - - /// Constructor to be used when creating an identifiable new box object - Box(const std::string& name, double x, double y, double z) - { make(name, x, y, z); } - - /// Constructor to be used when creating an anonymous new box object (retrieves name from volume) - Box(double x, double y, double z) - { make("", x, y, z); } + template <typename Q> + Box(const Handle<Q>& e) + : Solid_type<Implementation>(e) { + } - /// Constructor to be used when creating an identifiable new box object - template<typename X, typename Y, typename Z> - Box(const std::string& name, const X& x, const Y& y, const Z& z) - { make(name, _toDouble(x),_toDouble(y),_toDouble(z)); } + /// Constructor to create an anonymous new box object (retrieves name from volume) + Box(double x, double y, double z) { + make("", x, y, z); + } - /// Constructor to be used when creating an anonymous new box object (retrieves name from volume) - template<typename X, typename Y, typename Z> - Box(const X& x, const Y& y, const Z& z) - { make("", _toDouble(x),_toDouble(y),_toDouble(z)); } + /// Constructor to create an anonymous new box object (retrieves name from volume) + template <typename X, typename Y, typename Z> + Box(const X& x, const Y& y, const Z& z) { + make("", _toDouble(x), _toDouble(y), _toDouble(z)); + } /// Set the box dimensions Box& setDimensions(double x, double y, double z); @@ -147,7 +145,7 @@ namespace DD4hep { double z() const; }; - /**@class Polycone Shapes.h + /**@class Polycone Shapes.h * * Polycone. It has at least 9 parameters : * - the lower phi limit; @@ -159,24 +157,18 @@ namespace DD4hep { * @author M.Frank * @version 1.0 */ - struct Polycone : public Solid_type<TGeoPcon> { + struct Polycone: public Solid_type<TGeoPcon> { /// Constructor to be used when reading the already parsed polycone object - template <typename Q> Polycone(const Handle<Q>& e) : Solid_type<Implementation>(e) {} - - /// Constructor to be used when creating a new polycone object - Polycone(const std::string& name=""); + template <typename Q> Polycone(const Handle<Q>& e) + : Solid_type<Implementation>(e) { + } - /// Constructor to be used when creating a new polycone object + /// Constructor to create a new polycone object Polycone(double start, double delta); - /// Constructor to be used when creating a new polycone object - Polycone(const std::string& name, double start, double delta); - - /// Constructor to be used when creating a new polycone object. Add at the same time all Z planes - Polycone(double start, double delta, const std::vector<double>& rmin, const std::vector<double>& rmax, const std::vector<double>& z); - - /// Constructor to be used when creating a new polycone object. Add at the same time all Z planes - Polycone(const std::string& name, double start, double delta, const std::vector<double>& rmin, const std::vector<double>& rmax, const std::vector<double>& z); + /// Constructor to create a new polycone object. Add at the same time all Z planes + Polycone(double start, double delta, const std::vector<double>& rmin, const std::vector<double>& rmax, + const std::vector<double>& z); /// Add Z-planes to the Polycone void addZPlanes(const std::vector<double>& rmin, const std::vector<double>& rmax, const std::vector<double>& z); @@ -190,372 +182,316 @@ namespace DD4hep { * @author M.Frank * @version 1.0 */ - struct ConeSegment : public Solid_type<TGeoConeSeg> { + struct ConeSegment: public Solid_type<TGeoConeSeg> { /// Constructor to be used when reading the already parsed ConeSegment object - template <typename Q> ConeSegment(const Handle<Q>& e) : Solid_type<Implementation>(e) {} - - /// Constructor to be used when creating a new ConeSegment object - ConeSegment(const std::string& name=""); - - /// Constructor to be used when initializing a new object - ConeSegment(double dz, double rmin1, double rmax1, double rmin2, double rmax2, double phi1=0.0, double phi2=2.0*M_PI); + template <typename Q> ConeSegment(const Handle<Q>& e) + : Solid_type<Implementation>(e) { + } - /// Constructor to be used when creating a new ConeSegment object - ConeSegment(const std::string& name,double dz, double rmin1, double rmax1, double rmin2, double rmax2, double phi1=0.0, double phi2=2.0*M_PI); + /// Constructor to create a new ConeSegment object + ConeSegment(double dz, double rmin1, double rmax1, double rmin2, double rmax2, double phi1 = 0.0, + double phi2 = 2.0 * M_PI); /// Set the cone segment dimensions - ConeSegment& setDimensions(double dz, double rmin1, double rmax1, double rmin2, double rmax2, double phi1=0.0, double phi2=2.0*M_PI); + ConeSegment& setDimensions(double dz, double rmin1, double rmax1, double rmin2, double rmax2, double phi1 = 0.0, + double phi2 = 2.0 * M_PI); }; - /**@class Tube Shapes.h + /**@class Tube Shapes.h * * @author M.Frank * @version 1.0 */ - struct MyConeSeg : public TGeoConeSeg { + struct MyConeSeg: public TGeoConeSeg { public: - MyConeSeg() : TGeoConeSeg() {} - virtual ~MyConeSeg() {} - double GetRmin() const { return GetRmin1(); } - double GetRmax() const { return GetRmax1(); } + MyConeSeg() + : TGeoConeSeg() { + } + virtual ~MyConeSeg() { + } + double GetRmin() const { + return GetRmin1(); + } + double GetRmax() const { + return GetRmax1(); + } }; - struct Tube : public Solid_type< /*TGeoTubeSeg */ MyConeSeg > { - protected: - void make(const std::string& name,double rmin,double rmax,double z,double startPhi,double deltaPhi); + struct Tube: public Solid_type< /*TGeoTubeSeg */MyConeSeg> { + protected: + void make(const std::string& name, double rmin, double rmax, double z, double startPhi, double deltaPhi); - public: + public: /// Constructor to assign an object - template <typename Q> Tube(const Handle<Q>& e) : Solid_type<Implementation>(e) {} - - /// Constructor to be used when creating a new anonymous tube object - Tube() - { make("",0, 0, 0, 0, 0); } - - /// Constructor to be used when creating a new identifiable tube object - Tube(const std::string& name) - { make(name,0, 0, 0, 0, 0); } - - /// Constructor to be used when creating a new anonymous tube object with attribute initialization - Tube(double rmin, double rmax, double z, double deltaPhi=2*M_PI) - { make("",rmin, rmax, z, 0, deltaPhi); } - - /// Constructor to be used when creating a new anonymous tube object with attribute initialization - Tube(double rmin, double rmax, double z, double startPhi, double deltaPhi) - { make("",rmin, rmax, z, startPhi, deltaPhi); } + template <typename Q> Tube(const Handle<Q>& e) + : Solid_type<Implementation>(e) { + } - /// Legacy: Constructor to be used when creating a new identifiable tube object with attribute initialization - Tube(const std::string& name, double rmin, double rmax, double z, double deltaPhi=2*M_PI) - { make(name,rmin, rmax, z, 0, deltaPhi); } + /// Constructor to create a new anonymous tube object with attribute initialization + Tube(double rmin, double rmax, double z, double deltaPhi = 2 * M_PI) { + make("", rmin, rmax, z, 0, deltaPhi); + } - /// Legacy: Constructor to be used when creating a new identifiable tube object with attribute initialization - template<typename RMIN, typename RMAX, typename Z, typename DELTAPHI> - Tube(const std::string& name, const RMIN& rmin, const RMAX& rmax, const Z& z, const DELTAPHI& deltaPhi) - { - make(name,_toDouble(rmin),_toDouble(rmax),_toDouble(z),0,_toDouble(deltaPhi)); + /// Constructor to create a new anonymous tube object with attribute initialization + Tube(double rmin, double rmax, double z, double startPhi, double deltaPhi) { + make("", rmin, rmax, z, startPhi, deltaPhi); } - /// Constructor to be used when creating a new anonymous tube object with attribute initialization - template<typename RMIN, typename RMAX, typename Z, typename DELTAPHI> - Tube(const RMIN& rmin, const RMAX& rmax, const Z& z, const DELTAPHI& deltaPhi) - { - make("",_toDouble(rmin),_toDouble(rmax),_toDouble(z),0,_toDouble(deltaPhi)); + /// Legacy: Constructor to create a new identifiable tube object with attribute initialization + Tube(const std::string& name, double rmin, double rmax, double z, double deltaPhi = 2 * M_PI) { + make(name, rmin, rmax, z, 0, deltaPhi); } - /// Constructor to be used when creating a new identifiable tube object with attribute initialization - template<typename RMIN, typename RMAX, typename Z, typename STARTPHI, typename DELTAPHI> - Tube(const std::string& name, const RMIN& rmin, const RMAX& rmax, const Z& z, const STARTPHI& startPhi, const DELTAPHI& deltaPhi) - { - make(name,_toDouble(rmin),_toDouble(rmax),_toDouble(z),_toDouble(startPhi),_toDouble(deltaPhi)); + /// Constructor to create a new anonymous tube object with attribute initialization + template <typename RMIN, typename RMAX, typename Z, typename DELTAPHI> + Tube(const RMIN& rmin, const RMAX& rmax, const Z& z, const DELTAPHI& deltaPhi) { + make("", _toDouble(rmin), _toDouble(rmax), _toDouble(z), 0, _toDouble(deltaPhi)); } /// Set the tube dimensions Tube& setDimensions(double rmin, double rmax, double z, double startPhi, double deltaPhi); }; - /**@class Cone Shapes.h + /**@class Cone Shapes.h * * @author M.Frank * @version 1.0 */ - struct Cone : public Solid_type<TGeoCone> { - protected: - void make(const std::string& name,double z,double rmin1,double rmax1,double rmin2,double rmax2); + struct Cone: public Solid_type<TGeoCone> { + protected: + void make(const std::string& name, double z, double rmin1, double rmax1, double rmin2, double rmax2); - public: + public: /// Constructor to be used when reading the already parsed object - template <typename Q> Cone(const Handle<Q>& e) : Solid_type<Implementation>(e) {} - - /// Constructor to be used when creating a new anonymous object - Cone() { make("",0, 0, 0, 0, 0); } - /// Constructor to be used when creating a new object - Cone(const std::string& name) { make(name,0, 0, 0, 0, 0); } - /// Constructor to be used when creating a new anonymous object with attribute initialization - Cone(double z, - double rmin1, - double rmax1, - double rmin2, - double rmax2) - { make("",z,rmin1,rmax1,rmin2,rmax2); } - /// Constructor to be used when creating a new object with attribute initialization - Cone(const std::string& name, - double z, - double rmin1, - double rmax1, - double rmin2, - double rmax2) - { make(name,z,rmin1,rmax1,rmin2,rmax2); } - - template<typename Z, typename RMIN1, typename RMAX1, typename RMIN2, typename RMAX2> - Cone(const Z& z, const RMIN1& rmin1, const RMAX1& rmax1, const RMIN2& rmin2, const RMAX2& rmax2) - { make("",_toDouble(z),_toDouble(rmin1),_toDouble(rmax1),_toDouble(rmin2),_toDouble(rmax2)); } - - template<typename Z, typename RMIN1, typename RMAX1, typename RMIN2, typename RMAX2> - Cone(const std::string& name, const Z& z, const RMIN1& rmin1, const RMAX1& rmax1, const RMIN2& rmin2, const RMAX2& rmax2) - { make(name,_toDouble(z),_toDouble(rmin1),_toDouble(rmax1),_toDouble(rmin2),_toDouble(rmax2)); } + template <typename Q> Cone(const Handle<Q>& e) + : Solid_type<Implementation>(e) { + } + + /// Constructor to create a new anonymous object with attribute initialization + Cone(double z, double rmin1, double rmax1, double rmin2, double rmax2) { + make("", z, rmin1, rmax1, rmin2, rmax2); + } + + template <typename Z, typename RMIN1, typename RMAX1, typename RMIN2, typename RMAX2> + Cone(const Z& z, const RMIN1& rmin1, const RMAX1& rmax1, const RMIN2& rmin2, const RMAX2& rmax2) { + make("", _toDouble(z), _toDouble(rmin1), _toDouble(rmax1), _toDouble(rmin2), _toDouble(rmax2)); + } /// Set the box dimensions - Cone& setDimensions(double z,double rmin1,double rmax1,double rmin2,double rmax2); + Cone& setDimensions(double z, double rmin1, double rmax1, double rmin2, double rmax2); }; - /**@class Trap Shapes.h + /**@class Trap Shapes.h * * @author M.Frank * @version 1.0 */ - struct Trap : public Solid_type<TGeoTrap> { + struct Trap: public Solid_type<TGeoTrap> { /// Constructor to be used when reading the already parsed object - template <typename Q> Trap( const Handle<Q>& e) : Solid_type<Implementation>(e) {} - - /// Constructor to be used when creating a new identified object with attribute initialization - Trap( const std::string& name, - double z, - double theta, - double phi, - double y1, - double x1, - double x2, - double alpha1, - double y2, - double x3, - double x4, - double alpha2); - /// Constructor to be used when creating a new anonymous object with attribute initialization - Trap( double z, - double theta, - double phi, - double y1, - double x1, - double x2, - double alpha1, - double y2, - double x3, - double x4, - double alpha2); + template <typename Q> Trap(const Handle<Q>& e) + : Solid_type<Implementation>(e) { + } + + /// Constructor to create a new anonymous object with attribute initialization + Trap(double z, double theta, double phi, double y1, double x1, double x2, double alpha1, double y2, double x3, double x4, + double alpha2); /// Constructor to create a new anonymous object for right angular wedge from STEP (Se G4 manual for details) - Trap( double pz, - double py, - double px, - double pLTX); + Trap(double pz, double py, double px, double pLTX); /// Set the trap dimensions - Trap& setDimensions(double z,double theta,double phi, - double y1,double x1,double x2,double alpha1, - double y2,double x3,double x4,double alpha2); + Trap& setDimensions(double z, double theta, double phi, double y1, double x1, double x2, double alpha1, double y2, + double x3, double x4, double alpha2); }; - /**@class Trapezoid Shapes.h + /**@class Trapezoid Shapes.h * * @author M.Frank * @version 1.0 */ - struct Trapezoid : public Solid_type<TGeoTrd2> { + struct Trapezoid: public Solid_type<TGeoTrd2> { /// Constructor to be used when reading the already parsed object - template <typename Q> Trapezoid(const Handle<Q>& e) : Solid_type<Implementation>(e) {} - - /// Constructor to be used when creating a new anonymous object - Trapezoid(); - /// Constructor to be used when creating a new identified object - Trapezoid(const std::string& name); - /// Constructor to be used when creating a new anonymous object with attribute initialization + template <typename Q> Trapezoid(const Handle<Q>& e) + : Solid_type<Implementation>(e) { + } + /// Constructor to create a new anonymous object with attribute initialization Trapezoid(double x1, double x2, double y1, double y2, double z); - /// Constructor to be used when creating a new identified object with attribute initialization - Trapezoid(const std::string& name, double x1, double x2, double y1, double y2, double z); /// Set the Trapezoid dimensions Trapezoid& setDimensions(double x1, double x2, double y1, double y2, double z); }; - /**@class Torus Shapes.h + /**@class Torus Shapes.h * * @author M.Frank * @version 1.0 */ - struct Torus : public Solid_type<TGeoTorus> { + struct Torus: public Solid_type<TGeoTorus> { /// Constructor to be used when reading the already parsed object - template <typename Q> Torus(const Handle<Q>& e) : Solid_type<Implementation>(e) {} - - /// Constructor to be used when creating a new anonymous object - Torus(); - /// Constructor to be used when creating a identified new object - Torus(const std::string& name); - /// Constructor to be used when creating a new anonymous object with attribute initialization - Torus(double r, double rmin, double rmax, double phi=M_PI, double delta_phi=2.*M_PI); - /// Constructor to be used when creating a new identified object with attribute initialization - Torus(const std::string& name, double r, double rmin, double rmax, double phi=M_PI, double delta_phi=2.*M_PI); + template <typename Q> Torus(const Handle<Q>& e) + : Solid_type<Implementation>(e) { + } + /// Constructor to create a new anonymous object with attribute initialization + Torus(double r, double rmin, double rmax, double phi = M_PI, double delta_phi = 2. * M_PI); /// Set the Torus dimensions Torus& setDimensions(double r, double rmin, double rmax, double phi, double delta_phi); }; - /**@class Sphere Shapes.h + /**@class Sphere Shapes.h * * @author M.Frank * @version 1.0 */ - struct Sphere : public Solid_type<TGeoSphere> { + struct Sphere: public Solid_type<TGeoSphere> { /// Constructor to be used when reading the already parsed object - template <typename Q> Sphere(const Handle<Q>& e) : Solid_type<Implementation>(e) {} - - /// Constructor to be used when creating a new anonymous object - Sphere(); - /// Constructor to be used when creating a identified new object - Sphere(const std::string& name); - /// Constructor to be used when creating a new anonymous object with attribute initialization - Sphere(double rmin, double rmax, double theta=0., double delta_theta=M_PI, double phi=0.0, double delta_phi=2.*M_PI); - /// Constructor to be used when creating a new identified object with attribute initialization - Sphere(const std::string& name, double rmin, double rmax, double theta=0., double delta_theta=M_PI, double phi=0., double delta_phi=2.*M_PI); + template <typename Q> Sphere(const Handle<Q>& e) + : Solid_type<Implementation>(e) { + } + /// Constructor to create a new anonymous object with attribute initialization + Sphere(double rmin, double rmax, double theta = 0., double delta_theta = M_PI, double phi = 0.0, + double delta_phi = 2. * M_PI); /// Set the Sphere dimensions Sphere& setDimensions(double rmin, double rmax, double theta, double delta_theta, double phi, double delta_phi); }; - /**@class Paraboloid Shapes.h + /**@class Paraboloid Shapes.h * * @author M.Frank * @version 1.0 */ - struct Paraboloid : public Solid_type<TGeoParaboloid> { + struct Paraboloid: public Solid_type<TGeoParaboloid> { /// Constructor to be used when reading the already parsed object - template <typename Q> Paraboloid(const Handle<Q>& e) : Solid_type<Implementation>(e) {} - - /// Constructor to be used when creating a new anonymous object - Paraboloid(); - /// Constructor to be used when creating a new identified object - Paraboloid(const std::string& name); - /// Constructor to be used when creating a new anonymous object with attribute initialization + template <typename Q> Paraboloid(const Handle<Q>& e) + : Solid_type<Implementation>(e) { + } + /// Constructor to create a new anonymous object with attribute initialization Paraboloid(double r_low, double r_high, double delta_z); - /// Constructor to be used when creating a new identified object with attribute initialization - Paraboloid(const std::string& name, double r_low, double r_high, double delta_z); /// Set the Paraboloid dimensions Paraboloid& setDimensions(double r_low, double r_high, double delta_z); }; - /**@class PolyhedraRegular Shapes.h + /**@class PolyhedraRegular Shapes.h * * @author M.Frank * @version 1.0 */ - struct PolyhedraRegular : public Solid_type<TGeoPgon> { - protected: + struct PolyhedraRegular: public Solid_type<TGeoPgon> { + protected: /// Helper function to create holy hedron - void _create(const std::string& name, int nsides, double rmin, double rmax, - double zpos, double zneg, double start, double delta); - public: + void _create(const std::string& name, int nsides, double rmin, double rmax, double zpos, double zneg, double start, + double delta); + public: /// Constructor to be used when reading the already parsed object - template <typename Q> - PolyhedraRegular(const Handle<Q>& e) : Solid_type<Implementation>(e) {} + template <typename Q> + PolyhedraRegular(const Handle<Q>& e) + : Solid_type<Implementation>(e) { + } - /// Constructor to be used when creating a new object + /// Constructor to create a new object. Phi(start)=0, deltaPhi=2PI, Z-planes at -zlen/2 and +zlen/2 PolyhedraRegular(int nsides, double rmin, double rmax, double zlen); - /// Constructor to be used when creating a new object + /// Constructor to create a new object. Phi(start)=0, deltaPhi=2PI, Z-planes a zplanes[0] and zplanes[1] PolyhedraRegular(int nsides, double rmin, double rmax, double zplanes[2]); - /// Constructor to be used when creating a new object + /// Constructor to create a new object with phi_start, deltaPhi=2PI, Z-planes at -zlen/2 and +zlen/2 PolyhedraRegular(int nsides, double phi_start, double rmin, double rmax, double zlen); - /// Constructor to be used when creating a new object - PolyhedraRegular(const std::string& name, int nsides, double rmin, double rmax, double zlen); }; - /**@class BooleanSolid Shapes.h + /**@class BooleanSolid Shapes.h * * @author M.Frank * @version 1.0 */ - struct BooleanSolid : public Solid_type<TGeoCompositeShape> { - protected: + struct BooleanSolid: public Solid_type<TGeoCompositeShape> { + protected: /// Constructor to be used when reading the already parsed object - BooleanSolid() : Solid_type<Implementation>() {} + BooleanSolid() + : Solid_type<Implementation>() { + } - public: + public: /// Constructor to be used when reading the already parsed object - template <typename Q> - BooleanSolid(const Handle<Q>& e) : Solid_type<Implementation>(e) {} + template <typename Q> + BooleanSolid(const Handle<Q>& e) + : Solid_type<Implementation>(e) { + } }; - /**@class SubtractionSolid Shapes.h + /**@class SubtractionSolid Shapes.h * * @author M.Frank * @version 1.0 */ - struct SubtractionSolid : public BooleanSolid { + struct SubtractionSolid: public BooleanSolid { /// Default constructor - SubtractionSolid() : BooleanSolid() {} + SubtractionSolid() + : BooleanSolid() { + } /// Constructor to be used when reading the already parsed object - template<typename Q> SubtractionSolid(const Handle<Q>& e) : BooleanSolid(e) {} - /// Constructor to be used when creating a new object. Position is identity, Rotation is identity-rotation! + template <typename Q> SubtractionSolid(const Handle<Q>& e) + : BooleanSolid(e) { + } + /// Constructor to create a new object. Position is identity, Rotation is identity-rotation! SubtractionSolid(const Solid& shape1, const Solid& shape2); - /// Constructor to be used when creating a new object. Placement by a generic transformation within the mother - SubtractionSolid(const Solid& shape1, const Solid& shape2, const Transform3D& pos); - /// Constructor to be used when creating a new object. Rotation is identity-rotation! + /// Constructor to create a new object. Placement by position, Rotation is identity-rotation! SubtractionSolid(const Solid& shape1, const Solid& shape2, const Position& pos); - /// Constructor to be used when creating a new object + /// Constructor to create a new object. Placement by a RotationZYX within the mother SubtractionSolid(const Solid& shape1, const Solid& shape2, const RotationZYX& rot); - /// Constructor to be used when creating a new object + /// Constructor to create a new object. Placement by a generic rotoation within the mother SubtractionSolid(const Solid& shape1, const Solid& shape2, const Rotation3D& rot); - }; + /// Constructor to create a new object. Placement by a generic transformation within the mother + SubtractionSolid(const Solid& shape1, const Solid& shape2, const Transform3D& pos); + }; - /**@class UnionSolid Shapes.h + /**@class UnionSolid Shapes.h * * @author M.Frank * @version 1.0 */ - struct UnionSolid : public BooleanSolid { + struct UnionSolid: public BooleanSolid { /// Default constructor - UnionSolid() : BooleanSolid() {} + UnionSolid() + : BooleanSolid() { + } /// Constructor to be used when reading the already parsed object - template<typename Q> UnionSolid(const Handle<Q>& e) : BooleanSolid(e) {} - /// Constructor to be used when creating a new object. Position is identity, Rotation is identity-rotation! + template <typename Q> UnionSolid(const Handle<Q>& e) + : BooleanSolid(e) { + } + /// Constructor to create a new object. Position is identity, Rotation is identity-rotation! UnionSolid(const Solid& shape1, const Solid& shape2); - /// Constructor to be used when creating a new object. Placement by a generic transformation within the mother - UnionSolid(const Solid& shape1, const Solid& shape2, const Transform3D& pos); - /// Constructor to be used when creating a new object. Rotation is identity-rotation! + /// Constructor to create a new object. Placement by position, Rotation is identity-rotation! UnionSolid(const Solid& shape1, const Solid& shape2, const Position& pos); - /// Constructor to be used when creating a new object + /// Constructor to create a new object. Placement by a RotationZYX within the mother UnionSolid(const Solid& shape1, const Solid& shape2, const RotationZYX& rot); - /// Constructor to be used when creating a new object + /// Constructor to create a new object. Placement by a generic rotoation within the mother UnionSolid(const Solid& shape1, const Solid& shape2, const Rotation3D& rot); + /// Constructor to create a new object. Placement by a generic transformation within the mother + UnionSolid(const Solid& shape1, const Solid& shape2, const Transform3D& pos); }; - /**@class IntersectionSolid Shapes.h + /**@class IntersectionSolid Shapes.h * * @author M.Frank * @version 1.0 */ - struct IntersectionSolid : public BooleanSolid { + struct IntersectionSolid: public BooleanSolid { /// Default constructor - IntersectionSolid() : BooleanSolid() {} + IntersectionSolid() + : BooleanSolid() { + } /// Constructor to be used when reading the already parsed object - template<typename Q> IntersectionSolid(const Handle<Q>& e) : BooleanSolid(e) {} - /// Constructor to be used when creating a new object. Position is identity, Rotation is identity-rotation! + template <typename Q> IntersectionSolid(const Handle<Q>& e) + : BooleanSolid(e) { + } + /// Constructor to create a new object. Position is identity, Rotation is identity-rotation! IntersectionSolid(const Solid& shape1, const Solid& shape2); - /// Constructor to be used when creating a new object. Placement by a generic transformation within the mother - IntersectionSolid(const Solid& shape1, const Solid& shape2, const Transform3D& pos); - /// Constructor to be used when creating a new object. Rotation is identity-rotation! + /// Constructor to create a new object. Placement by position, Rotation is identity-rotation! IntersectionSolid(const Solid& shape1, const Solid& shape2, const Position& pos); - /// Constructor to be used when creating a new object + /// Constructor to create a new object. Placement by a RotationZYX within the mother IntersectionSolid(const Solid& shape1, const Solid& shape2, const RotationZYX& rot); - /// Constructor to be used when creating a new object + /// Constructor to create a new object. Placement by a generic rotoation within the mother IntersectionSolid(const Solid& shape1, const Solid& shape2, const Rotation3D& rot); + /// Constructor to create a new object. Placement by a generic transformation within the mother + IntersectionSolid(const Solid& shape1, const Solid& shape2, const Transform3D& pos); }; - } /* End namespace Geometry */ -} /* End namespace DD4hep */ + } /* End namespace Geometry */ +} /* End namespace DD4hep */ #endif /* DD4HEP_GEOMETRY_SOLIDS_H */ diff --git a/DDCore/include/DD4hep/TGeoUnits.h b/DDCore/include/DD4hep/TGeoUnits.h index 479552364..ac70b8c4f 100644 --- a/DDCore/include/DD4hep/TGeoUnits.h +++ b/DDCore/include/DD4hep/TGeoUnits.h @@ -16,364 +16,360 @@ namespace tgeo { - // - // Length [L] - // - static const double millimeter = 0.1; - static const double millimeter2 = millimeter*millimeter; - static const double millimeter3 = millimeter*millimeter*millimeter; - - static const double centimeter = 10.*millimeter; - static const double centimeter2 = centimeter*centimeter; - static const double centimeter3 = centimeter*centimeter*centimeter; - - static const double meter = 1000.*millimeter; - static const double meter2 = meter*meter; - static const double meter3 = meter*meter*meter; - - static const double kilometer = 1000.*meter; - static const double kilometer2 = kilometer*kilometer; - static const double kilometer3 = kilometer*kilometer*kilometer; - - static const double parsec = 3.0856775807e+16*meter; - - static const double micrometer = 1.e-6 *meter; - static const double nanometer = 1.e-9 *meter; - static const double angstrom = 1.e-10*meter; - static const double fermi = 1.e-15*meter; - - static const double barn = 1.e-28*meter2; - static const double millibarn = 1.e-3 *barn; - static const double microbarn = 1.e-6 *barn; - static const double nanobarn = 1.e-9 *barn; - static const double picobarn = 1.e-12*barn; - - // symbols - static const double nm = nanometer; - static const double um = micrometer; - - static const double mm = millimeter; +// +// Length [L] +// + static const double millimeter = 0.1; + static const double millimeter2 = millimeter * millimeter; + static const double millimeter3 = millimeter * millimeter * millimeter; + + static const double centimeter = 10. * millimeter; + static const double centimeter2 = centimeter * centimeter; + static const double centimeter3 = centimeter * centimeter * centimeter; + + static const double meter = 1000. * millimeter; + static const double meter2 = meter * meter; + static const double meter3 = meter * meter * meter; + + static const double kilometer = 1000. * meter; + static const double kilometer2 = kilometer * kilometer; + static const double kilometer3 = kilometer * kilometer * kilometer; + + static const double parsec = 3.0856775807e+16 * meter; + + static const double micrometer = 1.e-6 * meter; + static const double nanometer = 1.e-9 * meter; + static const double angstrom = 1.e-10 * meter; + static const double fermi = 1.e-15 * meter; + + static const double barn = 1.e-28 * meter2; + static const double millibarn = 1.e-3 * barn; + static const double microbarn = 1.e-6 * barn; + static const double nanobarn = 1.e-9 * barn; + static const double picobarn = 1.e-12 * barn; + +// symbols + static const double nm = nanometer; + static const double um = micrometer; + + static const double mm = millimeter; static const double mm2 = millimeter2; static const double mm3 = millimeter3; - static const double cm = centimeter; + static const double cm = centimeter; static const double cm2 = centimeter2; static const double cm3 = centimeter3; - static const double m = meter; + static const double m = meter; static const double m2 = meter2; static const double m3 = meter3; - static const double km = kilometer; + static const double km = kilometer; static const double km2 = kilometer2; static const double km3 = kilometer3; static const double pc = parsec; - // - // Angle - // - static const double radian = 180./3.14159265358979323846; // => degree=1 - static const double milliradian = 1.e-3*radian; - static const double degree = 1.;//= (3.14159265358979323846/180.0)*radian; - - static const double steradian = 1.; - - // symbols - static const double rad = radian; +// +// Angle +// + static const double radian = 180. / 3.14159265358979323846; // => degree=1 + static const double milliradian = 1.e-3 * radian; + static const double degree = 1.; //= (3.14159265358979323846/180.0)*radian; + + static const double steradian = 1.; + +// symbols + static const double rad = radian; static const double mrad = milliradian; - static const double sr = steradian; - static const double deg = degree; - - // - // Time [T] - // - static const double nanosecond = 1.e-9; - static const double second = 1.e+9 *nanosecond; - static const double millisecond = 1.e-3 *second; - static const double microsecond = 1.e-6 *second; - static const double picosecond = 1.e-12*second; - - static const double hertz = 1./second; - static const double kilohertz = 1.e+3*hertz; - static const double megahertz = 1.e+6*hertz; - - // symbols + static const double sr = steradian; + static const double deg = degree; + +// +// Time [T] +// + static const double nanosecond = 1.e-9; + static const double second = 1.e+9 * nanosecond; + static const double millisecond = 1.e-3 * second; + static const double microsecond = 1.e-6 * second; + static const double picosecond = 1.e-12 * second; + + static const double hertz = 1. / second; + static const double kilohertz = 1.e+3 * hertz; + static const double megahertz = 1.e+6 * hertz; + +// symbols static const double ns = nanosecond; - static const double s = second; + static const double s = second; static const double ms = millisecond; - // - // Electric charge [Q] - // - static const double eplus = 1. ;// positron charge - static const double e_SI = 1.602176487e-19;// positron charge in coulomb - static const double coulomb = eplus/e_SI;// coulomb = 6.24150 e+18 * eplus +// +// Electric charge [Q] +// + static const double eplus = 1.; // positron charge + static const double e_SI = 1.602176487e-19; // positron charge in coulomb + static const double coulomb = eplus / e_SI; // coulomb = 6.24150 e+18 * eplus - // - // Energy [E] - // +// +// Energy [E] +// static const double megaelectronvolt = 1.e-3; - static const double electronvolt = 1.e-6*megaelectronvolt; - static const double kiloelectronvolt = 1.e-3*megaelectronvolt; - static const double gigaelectronvolt = 1.e+3*megaelectronvolt; - static const double teraelectronvolt = 1.e+6*megaelectronvolt; - static const double petaelectronvolt = 1.e+9*megaelectronvolt; + static const double electronvolt = 1.e-6 * megaelectronvolt; + static const double kiloelectronvolt = 1.e-3 * megaelectronvolt; + static const double gigaelectronvolt = 1.e+3 * megaelectronvolt; + static const double teraelectronvolt = 1.e+6 * megaelectronvolt; + static const double petaelectronvolt = 1.e+9 * megaelectronvolt; - static const double joule = electronvolt/e_SI;// joule = 6.24150 e+12 * MeV + static const double joule = electronvolt / e_SI; // joule = 6.24150 e+12 * MeV - // symbols +// symbols static const double MeV = megaelectronvolt; - static const double eV = electronvolt; + static const double eV = electronvolt; static const double keV = kiloelectronvolt; static const double GeV = gigaelectronvolt; static const double TeV = teraelectronvolt; static const double PeV = petaelectronvolt; - // - // Mass [E][T^2][L^-2] - // - static const double kilogram = joule*second*second/(meter*meter); - static const double gram = 1.e-3*kilogram; - static const double milligram = 1.e-3*gram; - - // symbols - static const double kg = kilogram; - static const double g = gram; - static const double mg = milligram; - - // - // Power [E][T^-1] - // - static const double watt = joule/second;// watt = 6.24150 e+3 * MeV/ns - - // - // Force [E][L^-1] - // - static const double newton = joule/meter;// newton = 6.24150 e+9 * MeV/mm - - // - // Pressure [E][L^-3] - // -#define pascal hep_pascal // a trick to avoid warnings - static const double hep_pascal = newton/m2; // pascal = 6.24150 e+3 * MeV/mm3 - static const double bar = 100000*pascal; // bar = 6.24150 e+8 * MeV/mm3 - static const double atmosphere = 101325*pascal; // atm = 6.32420 e+8 * MeV/mm3 - - // - // Electric current [Q][T^-1] - // - static const double ampere = coulomb/second; // ampere = 6.24150 e+9 * eplus/ns - static const double milliampere = 1.e-3*ampere; - static const double microampere = 1.e-6*ampere; - static const double nanoampere = 1.e-9*ampere; - - // - // Electric potential [E][Q^-1] - // - static const double megavolt = megaelectronvolt/eplus; - static const double kilovolt = 1.e-3*megavolt; - static const double volt = 1.e-6*megavolt; - - // - // Electric resistance [E][T][Q^-2] - // - static const double ohm = volt/ampere;// ohm = 1.60217e-16*(MeV/eplus)/(eplus/ns) - - // - // Electric capacitance [Q^2][E^-1] - // - static const double farad = coulomb/volt;// farad = 6.24150e+24 * eplus/Megavolt - static const double millifarad = 1.e-3*farad; - static const double microfarad = 1.e-6*farad; - static const double nanofarad = 1.e-9*farad; - static const double picofarad = 1.e-12*farad; - - // - // Magnetic Flux [T][E][Q^-1] - // - static const double weber = volt*second;// weber = 1000*megavolt*ns - - // - // Magnetic Field [T][E][Q^-1][L^-2] - // - static const double tesla = volt*second/meter2;// tesla =0.001*megavolt*ns/mm2 - - static const double gauss = 1.e-4*tesla; - static const double kilogauss = 1.e-1*tesla; - - // - // Inductance [T^2][E][Q^-2] - // - static const double henry = weber/ampere;// henry = 1.60217e-7*MeV*(ns/eplus)**2 - - // - // Temperature - // +// +// Mass [E][T^2][L^-2] +// + static const double kilogram = joule * second * second / (meter * meter); + static const double gram = 1.e-3 * kilogram; + static const double milligram = 1.e-3 * gram; + +// symbols + static const double kg = kilogram; + static const double g = gram; + static const double mg = milligram; + +// +// Power [E][T^-1] +// + static const double watt = joule / second; // watt = 6.24150 e+3 * MeV/ns + +// +// Force [E][L^-1] +// + static const double newton = joule / meter; // newton = 6.24150 e+9 * MeV/mm + +// +// Pressure [E][L^-3] +// +#define pascal hep_pascal // a trick to avoid warnings + static const double hep_pascal = newton / m2; // pascal = 6.24150 e+3 * MeV/mm3 + static const double bar = 100000 * pascal; // bar = 6.24150 e+8 * MeV/mm3 + static const double atmosphere = 101325 * pascal; // atm = 6.32420 e+8 * MeV/mm3 + +// +// Electric current [Q][T^-1] +// + static const double ampere = coulomb / second; // ampere = 6.24150 e+9 * eplus/ns + static const double milliampere = 1.e-3 * ampere; + static const double microampere = 1.e-6 * ampere; + static const double nanoampere = 1.e-9 * ampere; + +// +// Electric potential [E][Q^-1] +// + static const double megavolt = megaelectronvolt / eplus; + static const double kilovolt = 1.e-3 * megavolt; + static const double volt = 1.e-6 * megavolt; + +// +// Electric resistance [E][T][Q^-2] +// + static const double ohm = volt / ampere; // ohm = 1.60217e-16*(MeV/eplus)/(eplus/ns) + +// +// Electric capacitance [Q^2][E^-1] +// + static const double farad = coulomb / volt; // farad = 6.24150e+24 * eplus/Megavolt + static const double millifarad = 1.e-3 * farad; + static const double microfarad = 1.e-6 * farad; + static const double nanofarad = 1.e-9 * farad; + static const double picofarad = 1.e-12 * farad; + +// +// Magnetic Flux [T][E][Q^-1] +// + static const double weber = volt * second; // weber = 1000*megavolt*ns + +// +// Magnetic Field [T][E][Q^-1][L^-2] +// + static const double tesla = volt * second / meter2; // tesla =0.001*megavolt*ns/mm2 + + static const double gauss = 1.e-4 * tesla; + static const double kilogauss = 1.e-1 * tesla; + +// +// Inductance [T^2][E][Q^-2] +// + static const double henry = weber / ampere; // henry = 1.60217e-7*MeV*(ns/eplus)**2 + +// +// Temperature +// static const double kelvin = 1.; - // - // Amount of substance - // +// +// Amount of substance +// static const double mole = 1.; - // - // Activity [T^-1] - // - static const double becquerel = 1./second ; +// +// Activity [T^-1] +// + static const double becquerel = 1. / second; static const double curie = 3.7e+10 * becquerel; - // - // Absorbed dose [L^2][T^-2] - // - static const double gray = joule/kilogram ; - static const double kilogray = 1.e+3*gray; - static const double milligray = 1.e-3*gray; - static const double microgray = 1.e-6*gray; - - // - // Luminous intensity [I] - // +// +// Absorbed dose [L^2][T^-2] +// + static const double gray = joule / kilogram; + static const double kilogray = 1.e+3 * gray; + static const double milligray = 1.e-3 * gray; + static const double microgray = 1.e-6 * gray; + +// +// Luminous intensity [I] +// static const double candela = 1.; - // - // Luminous flux [I] - // - static const double lumen = candela*steradian; +// +// Luminous flux [I] +// + static const double lumen = candela * steradian; - // - // Illuminance [I][L^-2] - // - static const double lux = lumen/meter2; +// +// Illuminance [I][L^-2] +// + static const double lux = lumen / meter2; - // - // Miscellaneous - // - static const double perCent = 0.01 ; +// +// Miscellaneous +// + static const double perCent = 0.01; static const double perThousand = 0.001; - static const double perMillion = 0.000001; - - // -*- C++ -*- - // $Id:$ - // ---------------------------------------------------------------------- - // HEP coherent Physical Constants - // - // This file has been provided by Geant4 (simulation toolkit for HEP). - // - // The basic units are : - // millimeter - // nanosecond - // Mega electron Volt - // positon charge - // degree Kelvin - // amount of substance (mole) - // luminous intensity (candela) - // radian - // steradian - // - // Below is a non exhaustive list of Physical CONSTANTS, - // computed in the Internal HEP System Of Units. - // - // Most of them are extracted from the Particle Data Book : - // Phys. Rev. D volume 50 3-1 (1994) page 1233 - // - // ...with a meaningful (?) name ... - // - // You can add your own constants. - // - // Author: M.Maire - // - // History: - // - // 23.02.96 Created - // 26.03.96 Added constants for standard conditions of temperature - // and pressure; also added Gas threshold. - // 29.04.08 use PDG 2006 values - // 03.11.08 use PDG 2008 values - - static const double pi = 3.14159265358979323846; - static const double twopi = 2*pi; - static const double halfpi = pi/2; - static const double pi2 = pi*pi; - - // - // - // - static const double Avogadro = 6.02214179e+23/mole; - - // - // c = 299.792458 mm/ns - // c^2 = 898.7404 (mm/ns)^2 - // - static const double c_light = 2.99792458e+8 * m/s; + static const double perMillion = 0.000001; + +// -*- C++ -*- +// $Id:$ +// ---------------------------------------------------------------------- +// HEP coherent Physical Constants +// +// This file has been provided by Geant4 (simulation toolkit for HEP). +// +// The basic units are : +// millimeter +// nanosecond +// Mega electron Volt +// positon charge +// degree Kelvin +// amount of substance (mole) +// luminous intensity (candela) +// radian +// steradian +// +// Below is a non exhaustive list of Physical CONSTANTS, +// computed in the Internal HEP System Of Units. +// +// Most of them are extracted from the Particle Data Book : +// Phys. Rev. D volume 50 3-1 (1994) page 1233 +// +// ...with a meaningful (?) name ... +// +// You can add your own constants. +// +// Author: M.Maire +// +// History: +// +// 23.02.96 Created +// 26.03.96 Added constants for standard conditions of temperature +// and pressure; also added Gas threshold. +// 29.04.08 use PDG 2006 values +// 03.11.08 use PDG 2008 values + + static const double pi = 3.14159265358979323846; + static const double twopi = 2 * pi; + static const double halfpi = pi / 2; + static const double pi2 = pi * pi; + +// +// +// + static const double Avogadro = 6.02214179e+23 / mole; + +// +// c = 299.792458 mm/ns +// c^2 = 898.7404 (mm/ns)^2 +// + static const double c_light = 2.99792458e+8 * m / s; static const double c_squared = c_light * c_light; - // - // h = 4.13566e-12 MeV*ns - // hbar = 6.58212e-13 MeV*ns - // hbarc = 197.32705e-12 MeV*mm - // - static const double h_Planck = 6.62606896e-34 * joule*s; - static const double hbar_Planck = h_Planck/twopi; - static const double hbarc = hbar_Planck * c_light; +// +// h = 4.13566e-12 MeV*ns +// hbar = 6.58212e-13 MeV*ns +// hbarc = 197.32705e-12 MeV*mm +// + static const double h_Planck = 6.62606896e-34 * joule * s; + static const double hbar_Planck = h_Planck / twopi; + static const double hbarc = hbar_Planck * c_light; static const double hbarc_squared = hbarc * hbarc; - // - // - // - static const double electron_charge = - eplus; // see SystemOfUnits.h +// +// +// + static const double electron_charge = -eplus; // see SystemOfUnits.h static const double e_squared = eplus * eplus; - // - // amu_c2 - atomic equivalent mass unit - // - AKA, unified atomic mass unit (u) - // amu - atomic mass unit - // +// +// amu_c2 - atomic equivalent mass unit +// - AKA, unified atomic mass unit (u) +// amu - atomic mass unit +// static const double electron_mass_c2 = 0.510998910 * MeV; - static const double proton_mass_c2 = 938.272013 * MeV; - static const double neutron_mass_c2 = 939.56536 * MeV; - static const double amu_c2 = 931.494028 * MeV; - static const double amu = amu_c2/c_squared; - - // - // permeability of free space mu0 = 2.01334e-16 Mev*(ns*eplus)^2/mm - // permittivity of free space epsil0 = 5.52636e+10 eplus^2/(MeV*mm) - // - static const double mu0 = 4*pi*1.e-7 * henry/m; - static const double epsilon0 = 1./(c_squared*mu0); - - // - // electromagnetic coupling = 1.43996e-12 MeV*mm/(eplus^2) - // - static const double elm_coupling = e_squared/(4*pi*epsilon0); - static const double fine_structure_const = elm_coupling/hbarc; - static const double classic_electr_radius = elm_coupling/electron_mass_c2; - static const double electron_Compton_length = hbarc/electron_mass_c2; - static const double Bohr_radius = electron_Compton_length/fine_structure_const; - - static const double alpha_rcl2 = fine_structure_const - *classic_electr_radius - *classic_electr_radius; - - static const double twopi_mc2_rcl2 = twopi*electron_mass_c2 - *classic_electr_radius - *classic_electr_radius; - // - // - // - static const double k_Boltzmann = 8.617343e-11 * MeV/kelvin; - - // - // - // - static const double STP_Temperature = 273.15*kelvin; - static const double STP_Pressure = 1.*atmosphere; - static const double kGasThreshold = 10.*mg/cm3; - - // - // - // - static const double universe_mean_density = 1.e-25*g/cm3; + static const double proton_mass_c2 = 938.272013 * MeV; + static const double neutron_mass_c2 = 939.56536 * MeV; + static const double amu_c2 = 931.494028 * MeV; + static const double amu = amu_c2 / c_squared; + +// +// permeability of free space mu0 = 2.01334e-16 Mev*(ns*eplus)^2/mm +// permittivity of free space epsil0 = 5.52636e+10 eplus^2/(MeV*mm) +// + static const double mu0 = 4 * pi * 1.e-7 * henry / m; + static const double epsilon0 = 1. / (c_squared * mu0); + +// +// electromagnetic coupling = 1.43996e-12 MeV*mm/(eplus^2) +// + static const double elm_coupling = e_squared / (4 * pi * epsilon0); + static const double fine_structure_const = elm_coupling / hbarc; + static const double classic_electr_radius = elm_coupling / electron_mass_c2; + static const double electron_Compton_length = hbarc / electron_mass_c2; + static const double Bohr_radius = electron_Compton_length / fine_structure_const; + + static const double alpha_rcl2 = fine_structure_const * classic_electr_radius * classic_electr_radius; + + static const double twopi_mc2_rcl2 = twopi * electron_mass_c2 * classic_electr_radius * classic_electr_radius; +// +// +// + static const double k_Boltzmann = 8.617343e-11 * MeV / kelvin; + +// +// +// + static const double STP_Temperature = 273.15 * kelvin; + static const double STP_Pressure = 1. * atmosphere; + static const double kGasThreshold = 10. * mg / cm3; + +// +// +// + static const double universe_mean_density = 1.e-25 * g / cm3; } #endif /* DD4HEP_TGEOUNITS_H */ diff --git a/DDCore/include/DD4hep/VolumeManager.h b/DDCore/include/DD4hep/VolumeManager.h index 660cbf7e4..a0805400d 100644 --- a/DDCore/include/DD4hep/VolumeManager.h +++ b/DDCore/include/DD4hep/VolumeManager.h @@ -24,33 +24,33 @@ namespace DD4hep { /* * Geometry namespace declaration */ - namespace Geometry { + namespace Geometry { - // Forward declarations +// Forward declarations class LCDD; /** @class VolumeManager VolumeManager.h DD4hep/lcdd/VolumeManager.h - * - * The VolumeManager manages the repository of sensitive physical + * + * The VolumeManager manages the repository of sensitive physical * volumes (placements). These volumes can then be accessed together with * basic other elements, such as the top level Detector element of the * subdetector or the coordinate trasformation to world coordinates. - * The basic key to access this information is the 'VolumeID', a 64 bit + * The basic key to access this information is the 'VolumeID', a 64 bit * number, which uniquely identifies a placement. * * There are 2 working modes: * - * 1) Starting from the top level element, the next level is addressed + * 1) Starting from the top level element, the next level is addressed * separately and the volumes are stored in a 2-level 'tree'. Placements * this way are partitioned e.g. 'by subdetector'. This tries to keep * the number of mapped elements at a reasonable level. * - * 2) All placements are mapped to the top-level element. Good for small - * setups. Note, that the system field of all IDDescriptors of the + * 2) All placements are mapped to the top-level element. Good for small + * setups. Note, that the system field of all IDDescriptors of the * subdetectors must have the same length to ensure the uniqueness of the * placement keys. - * - * By default the volume manager in TREE mode (-> 1)) is attached to the + * + * By default the volume manager in TREE mode (-> 1)) is attached to the * LCDD instance and also managed by this instance. * If you wish to create instances yourself, you must ensure that the * handle is destroyed once no other references are present. @@ -59,16 +59,15 @@ namespace DD4hep { * @author M.Frank * @version 1.0 */ - struct VolumeManager : public Ref_t { + struct VolumeManager: public Ref_t { public: typedef DD4hep::VolumeID VolumeID; // Creation flags enum PopulateFlags { - NONE = 0, - TREE = 1<<1, // Build 1 level DetElement hierarchy while populating - ONE = 1<<2, // Populate all daughter volumes into one big lookup-container - // This flag may be in parallel with 'TREE' - LAST + NONE = 0, TREE = 1 << 1, // Build 1 level DetElement hierarchy while populating + ONE = 1 << 2, // Populate all daughter volumes into one big lookup-container + // This flag may be in parallel with 'TREE' + LAST }; #if 0 @@ -77,37 +76,37 @@ namespace DD4hep { * @author M.Frank * @version 1.0 */ - struct VolIdentifier { + struct VolIdentifier { public: - /// The volume identifier and it's mask - VolumeID identifier, mask; + /// The volume identifier and it's mask + VolumeID identifier, mask; private: - /// Equality operator is provate. Not to be used! - bool operator==(const VolIdentifier& c) const { - return identifier == c.identifier && mask == c.mask; - } + /// Equality operator is provate. Not to be used! + bool operator==(const VolIdentifier& c) const { + return identifier == c.identifier && mask == c.mask; + } public: - /// Default constructor - VolIdentifier() : identifier(0), mask(~0x0ull) { - } - /// Initializing constructor - VolIdentifier(VolumeID id, VolumeID msk) : identifier(id), mask(msk) { - } - /// Copt constructor - VolIdentifier(const VolIdentifier& c) : identifier(c.identifier), mask(c.mask) { - } - /** Operator less for map storage. - * Note, that this takes advantag, the only volumes with the same descriptor length are - * stored in one map, because some bits are masked out. Otherwise all breaks! - */ - bool operator< (const VolIdentifier& c) const { - return identifier < (c.identifier&mask); - } - /// Assignment operator - VolIdentifier& operator=(const VolIdentifier& c) { - identifier=c.identifier; mask=c.mask; - return *this; - } + /// Default constructor + VolIdentifier() : identifier(0), mask(~0x0ull) { + } + /// Initializing constructor + VolIdentifier(VolumeID id, VolumeID msk) : identifier(id), mask(msk) { + } + /// Copt constructor + VolIdentifier(const VolIdentifier& c) : identifier(c.identifier), mask(c.mask) { + } + /** Operator less for map storage. + * Note, that this takes advantag, the only volumes with the same descriptor length are + * stored in one map, because some bits are masked out. Otherwise all breaks! + */ + bool operator< (const VolIdentifier& c) const { + return identifier < (c.identifier&mask); + } + /// Assignment operator + VolIdentifier& operator=(const VolIdentifier& c) { + identifier=c.identifier; mask=c.mask; + return *this; + } }; #endif typedef VolumeID VolIdentifier; @@ -119,40 +118,40 @@ namespace DD4hep { * @author M.Frank * @version 1.0 */ - struct Context { + struct Context { public: - typedef std::vector<const TGeoNode*> Path; - typedef PlacedVolume::VolIDs::Base VolIDs; + typedef std::vector<const TGeoNode*> Path; + typedef PlacedVolume::VolIDs::Base VolIDs; - /// Placement identifier - VolumeID identifier; - /// Ignore mask of the placement identifier - VolumeID mask; - /// The placement - PlacedVolume placement; - /// Handle to the subdetector element handle - DetElement detector; - /// Handle to the closest Detector element - DetElement element; - /// The transformation of space-points to the corrdinate system of the closests detector element - TGeoHMatrix toDetector; - /// The transformation of space-points to the world corrdinate system - TGeoHMatrix toWorld; - /// Volume IDS corresponding to this element - VolIDs volID; - /// Path of placements to this sensitive volume - Path path; + /// Placement identifier + VolumeID identifier; + /// Ignore mask of the placement identifier + VolumeID mask; + /// The placement + PlacedVolume placement; + /// Handle to the subdetector element handle + DetElement detector; + /// Handle to the closest Detector element + DetElement element; + /// The transformation of space-points to the corrdinate system of the closests detector element + TGeoHMatrix toDetector; + /// The transformation of space-points to the world corrdinate system + TGeoHMatrix toWorld; + /// Volume IDS corresponding to this element + VolIDs volID; + /// Path of placements to this sensitive volume + Path path; public: - /// Default constructor - Context(); - /// Default destructor - ~Context(); + /// Default constructor + Context(); + /// Default destructor + ~Context(); }; /// Some useful Container abbreviations used by the VolumeManager - typedef std::map<VolumeID,VolumeManager> Managers; - typedef std::map<DetElement,VolumeManager> Detectors; - typedef std::map<TGeoNode*,Context*> PhysVolumes; - typedef std::map<VolIdentifier,Context*> Volumes; + typedef std::map<VolumeID, VolumeManager> Managers; + typedef std::map<DetElement, VolumeManager> Detectors; + typedef std::map<TGeoNode*, Context*> PhysVolumes; + typedef std::map<VolIdentifier, Context*> Volumes; /** @class VolumeManager::Object VolumeManager.h DD4hep/lcdd/VolumeManager.h * @@ -161,61 +160,70 @@ namespace DD4hep { * @author M.Frank * @version 1.0 */ - struct Object : public TNamed { + struct Object: public TNamed { public: - typedef IDDescriptor::Field Field; + typedef IDDescriptor::Field Field; public: - /// Reference to the LCDD instance - LCDD& lcdd; - /// The container of subdetector elements - Detectors subdetectors; - /// The volume managers for the individual subdetector elements - Managers managers; - /// The container of placements managed by this instance - Volumes volumes; - /// Map of placed volumes and their corresponding context - PhysVolumes phys_volumes; - /// The Detector element handle managed by this instance - DetElement detector; - /// The ID descriptor object - IDDescriptor id; - /// The reference to the TOP level VolumeManager - TNamed* top; - /// The system field descriptor - Field system; - /// System identifier - VolumeID sysID; - /// Sub-detector mask - VolumeID detMask; - /// Population flags - int flags; + /// Reference to the LCDD instance + LCDD& lcdd; + /// The container of subdetector elements + Detectors subdetectors; + /// The volume managers for the individual subdetector elements + Managers managers; + /// The container of placements managed by this instance + Volumes volumes; + /// Map of placed volumes and their corresponding context + PhysVolumes phys_volumes; + /// The Detector element handle managed by this instance + DetElement detector; + /// The ID descriptor object + IDDescriptor id; + /// The reference to the TOP level VolumeManager + TNamed* top; + /// The system field descriptor + Field system; + /// System identifier + VolumeID sysID; + /// Sub-detector mask + VolumeID detMask; + /// Population flags + int flags; public: - /// Default constructor - Object(LCDD& lcdd); - /// Default destructor - virtual ~Object(); - /// Search the locally cached volumes for a matching ID - Context* search(const VolIdentifier& id) const; - /// Search the locally cached volumes for a matching physical volume - Context* search(const PlacedVolume pv) const; + /// Default constructor + Object(LCDD& lcdd); + /// Default destructor + virtual ~Object(); + /// Search the locally cached volumes for a matching ID + Context* search(const VolIdentifier& id) const; + /// Search the locally cached volumes for a matching physical volume + Context* search(const PlacedVolume pv) const; }; protected: /// Additional data accessor - Object& _data() const { return *(Object*)ptr(); } + Object& _data() const { + return *(Object*) ptr(); + } public: /// Default constructor - VolumeManager() : Ref_t() {} + VolumeManager() + : Ref_t() { + } /// Constructor to be used when reading the already parsed object - VolumeManager(const VolumeManager& e) : Ref_t(e) {} + VolumeManager(const VolumeManager& e) + : Ref_t(e) { + } /// Constructor to be used when reading the already parsed object - template <typename Q> VolumeManager(const Handle<Q>& e) : Ref_t(e) {} + template <typename Q> VolumeManager(const Handle<Q>& e) + : Ref_t(e) { + } /** Initializing constructor. The tree will automatically be built if the detelement is valid * Please see enum PopulateFlags for further info. * No action whatsoever is performed here, if the detector element is not valid. */ - VolumeManager(LCDD& lcdd, const std::string& name, DetElement world=DetElement(), Readout ro=Readout(), int flags=NONE); + VolumeManager(LCDD& lcdd, const std::string& name, DetElement world = DetElement(), Readout ro = Readout(), int flags = + NONE); /// Add a new Volume manager section according to a new subdetector VolumeManager addSubdetector(DetElement detector, Readout ro); /// Access the volume manager by cell id @@ -226,7 +234,7 @@ namespace DD4hep { /// Access the top level detector element DetElement detector() const; /// Assign IDDescription to VolumeManager structure - void setIDDescriptor(IDDescriptor spec) const; + void setIDDescriptor(IDDescriptor spec) const; /// Access IDDescription structure IDDescriptor idSpec() const; @@ -235,24 +243,24 @@ namespace DD4hep { /// Register physical volume with the manager and pre-computed volume id bool adoptPlacement(VolumeID volume_id, Context* context); - /** This set of functions is required when reading/analyzing + /** This set of functions is required when reading/analyzing * already created hits which have a VolumeID attached. */ /// Lookup the context, which belongs to a registered physical volume. - Context* lookupContext(VolumeID volume_id) const; + Context* lookupContext(VolumeID volume_id) const; /// Lookup a physical (placed) volume identified by its 64 bit hit ID PlacedVolume lookupPlacement(VolumeID volume_id) const; /// Lookup a top level subdetector detector element according to a contained 64 bit hit ID - DetElement lookupDetector(VolumeID volume_id) const; + DetElement lookupDetector(VolumeID volume_id) const; /// Lookup the closest subdetector detector element in the hierarchy according to a contained 64 bit hit ID - DetElement lookupDetElement(VolumeID volume_id) const; + DetElement lookupDetElement(VolumeID volume_id) const; /// Access the transformation of a physical volume to the world coordinate system - const TGeoMatrix& worldTransformation(VolumeID volume_id) const; + const TGeoMatrix& worldTransformation(VolumeID volume_id) const; }; - /// Enable printouts for debugging +/// Enable printouts for debugging std::ostream& operator<<(std::ostream& os, const VolumeManager& m); - } /* End namespace Geometry */ -} /* End namespace DD4hep */ + } /* End namespace Geometry */ +} /* End namespace DD4hep */ #endif /* DD4hep_GEOMETRY_READOUT_H */ diff --git a/DDCore/include/DD4hep/Volumes.h b/DDCore/include/DD4hep/Volumes.h index 613dafb39..ff8c6d15b 100644 --- a/DDCore/include/DD4hep/Volumes.h +++ b/DDCore/include/DD4hep/Volumes.h @@ -26,13 +26,13 @@ * DD4hep namespace declaration */ namespace DD4hep { - + /* * Geometry namespace declaration */ - namespace Geometry { - - // Forward declarations + namespace Geometry { + +// Forward declarations struct LCDD; struct Region; struct LimitSet; @@ -41,52 +41,70 @@ namespace DD4hep { struct Volume; struct PlacedVolume; struct SensitiveDetector; - + /** @class PlacedVolume Volume.h DD4hep/lcdd/Volume.h - * + * * @author M.Frank * @version 1.0 */ - struct PlacedVolume : Handle<TGeoNode> { - typedef std::pair<std::string,int> VolID; - struct VolIDs : public std::vector<VolID> { - typedef std::vector<VolID> Base; - VolIDs() : Base() {} - ~VolIDs () {} - Base::const_iterator find(const std::string& name) const; - std::pair<Base::iterator,bool> insert(const std::string& name, int value); + struct PlacedVolume: Handle<TGeoNode> { + typedef std::pair<std::string, int> VolID; + struct VolIDs: public std::vector<VolID> { + typedef std::vector<VolID> Base; + VolIDs() + : Base() { + } + ~VolIDs() { + } + Base::const_iterator find(const std::string& name) const; + std::pair<Base::iterator, bool> insert(const std::string& name, int value); }; - struct Object { - /// Magic word + struct Object { + /// Magic word unsigned long magic; - /// ID container - VolIDs volIDs; - /// Default constructor + /// ID container + VolIDs volIDs; + /// Default constructor Object(); - /// Copy constructor - Object(const Object& c); - /// Default destructor + /// Copy constructor + Object(const Object& c); + /// Default destructor virtual ~Object(); - /// Assignment operator - Object& operator=(const Object& c) { magic=c.magic; volIDs=c.volIDs; return *this; } + /// Assignment operator + Object& operator=(const Object& c) { + magic = c.magic; + volIDs = c.volIDs; + return *this; + } }; /// Constructor to be used when reading the already parsed DOM tree - PlacedVolume(const TGeoNode* e) : Handle<TGeoNode>(e) {} + PlacedVolume(const TGeoNode* e) + : Handle<TGeoNode>(e) { + } /// Default constructor - PlacedVolume() : Handle<TGeoNode>() {} + PlacedVolume() + : Handle<TGeoNode>() { + } /// Copy assignment - PlacedVolume(const PlacedVolume& e) : Handle<TGeoNode>(e) {} + PlacedVolume(const PlacedVolume& e) + : Handle<TGeoNode>(e) { + } /// Copy assignment from other handle type - template <typename T> PlacedVolume(const Handle<T>& e) : Handle<TGeoNode>(e) {} + template <typename T> PlacedVolume(const Handle<T>& e) + : Handle<TGeoNode>(e) { + } /// Assignment operator (must match copy constructor) - PlacedVolume& operator=(const PlacedVolume& v) { m_element=v.m_element; return *this; } + PlacedVolume& operator=(const PlacedVolume& v) { + m_element = v.m_element; + return *this; + } /// Add identifier PlacedVolume& addPhysVolID(const std::string& name, int value); /// Volume material Material material() const; /// Logical volume of this placement - Volume volume() const; + Volume volume() const; /// Parent volume (envelope) Volume motherVol() const; /// Access to the volume IDs @@ -94,87 +112,94 @@ namespace DD4hep { /// String dump std::string toString() const; }; - + /** @class Volume Volume.h DD4hep/lcdd/Volume.h - * + * * Handle describing a Volume * * @author M.Frank * @version 1.0 */ - struct Volume : public Handle<TGeoVolume> { + struct Volume: public Handle<TGeoVolume> { - public: + public: typedef Handle<TGeoVolume> Base; - struct Object { + struct Object { unsigned long magic; - Region region; - LimitSet limits; - VisAttr vis; - Ref_t sens_det; - int referenced; - /// Default constructor + Region region; + LimitSet limits; + VisAttr vis; + Ref_t sens_det; + int referenced; + /// Default constructor Object(); - /// Default destructor + /// Default destructor virtual ~Object(); - /// Copy the object - void copy(const Object& c) { - magic = c.magic; - region = c.region; - limits = c.limits; - vis = c.vis; - sens_det = c.sens_det; - referenced = c.referenced; - } + /// Copy the object + void copy(const Object& c) { + magic = c.magic; + region = c.region; + limits = c.limits; + vis = c.vis; + sens_det = c.sens_det; + referenced = c.referenced; + } }; - public: + public: /// Default constructor - Volume() : Base(0) {} - + Volume() + : Base(0) { + } + /// Copy from handle - Volume(const Volume& v) : Base(v) {} - + Volume(const Volume& v) + : Base(v) { + } + /// Copy from arbitrary Element - template <typename T> Volume(const Handle<T>& v) : Base(v) {} - + template <typename T> Volume(const Handle<T>& v) + : Base(v) { + } + /// Constructor to be used when creating a new geometry tree. Volume(const std::string& name); - + /// Constructor to be used when creating a new geometry tree. Also sets materuial and solid attributes Volume(const std::string& name, const Solid& s, const Material& m); - + /// Assignment operator (must match copy constructor) - Volume& operator=(const Volume& a) { m_element=a.m_element; return *this; } + Volume& operator=(const Volume& a) { + m_element = a.m_element; + return *this; + } /// Place daughter volume. The position and rotation are the identity - PlacedVolume placeVolume(const Volume& vol) const; + PlacedVolume placeVolume(const Volume& vol) const; /// Place daughter volume according to generic Transform3D - PlacedVolume placeVolume(const Volume& volume, const Transform3D& tr) const; + PlacedVolume placeVolume(const Volume& volume, const Transform3D& tr) const; /// Place un-rotated daughter volume at the given position. - PlacedVolume placeVolume(const Volume& vol, const Position& pos) const; + PlacedVolume placeVolume(const Volume& vol, const Position& pos) const; /// Place rotated daughter volume. The position is automatically the identity position - PlacedVolume placeVolume(const Volume& vol, const RotationZYX& rot) const; + PlacedVolume placeVolume(const Volume& vol, const RotationZYX& rot) const; /// Place rotated daughter volume. The position is automatically the identity position - PlacedVolume placeVolume(const Volume& vol, const Rotation3D& rot) const; - + PlacedVolume placeVolume(const Volume& vol, const Rotation3D& rot) const; + /// Attach attributes to the volume - const Volume& setAttributes(const LCDD& lcdd, - const std::string& region, - const std::string& limits, - const std::string& vis) const; - + const Volume& setAttributes(const LCDD& lcdd, const std::string& region, const std::string& limits, + const std::string& vis) const; + /// Set the regional attributes to the volume. Note: If the name string is empty, the action is ignored. - const Volume& setRegion(const LCDD& lcdd, const std::string& name) const; + const Volume& setRegion(const LCDD& lcdd, const std::string& name) const; /// Set the regional attributes to the volume - const Volume& setRegion(const Region& obj) const; + const Volume& setRegion(const Region& obj) const; /// Access to the handle to the region structure Region region() const; - + /// Set the limits to the volume. Note: If the name string is empty, the action is ignored. - const Volume& setLimitSet(const LCDD& lcdd, const std::string& name) const; + const Volume& setLimitSet(const LCDD& lcdd, const std::string& name) const; /// Set the limits to the volume - const Volume& setLimitSet(const LimitSet& obj) const; + const Volume& setLimitSet(const LimitSet& obj) const; /// Access to the limit set LimitSet limitSet() const; @@ -183,8 +208,8 @@ namespace DD4hep { /// Set Visualization attributes to the volume. Note: If the name string is empty, the action is ignored. const Volume& setVisAttributes(const LCDD& lcdd, const std::string& name) const; /// Access the visualisation attributes - VisAttr visAttributes() const; - + VisAttr visAttributes() const; + /// Assign the sensitive detector structure const Volume& setSensitiveDetector(const SensitiveDetector& obj) const; /// Access to the handle to the sensitive detector @@ -193,43 +218,54 @@ namespace DD4hep { bool isSensitive() const; /// Set the volume's solid shape - const Volume& setSolid(const Solid& s) const; + const Volume& setSolid(const Solid& s) const; /// Access to Solid (Shape) Solid solid() const; - + /// Set the volume's material - const Volume& setMaterial(const Material& m) const; + const Volume& setMaterial(const Material& m) const; /// Access to the Volume material Material material() const; - + /// Auto conversion to underlying ROOT object - operator TGeoVolume*() const { return m_element; } + operator TGeoVolume*() const { + return m_element; + } }; - + /** @class Assembly Volume.h DD4hep/lcdd/Volume.h - * + * * Handle describing a volume assembly * * @author M.Frank * @version 1.0 */ - struct Assembly : public Volume { + struct Assembly: public Volume { /// Default constructor - Assembly() : Volume() {} - + Assembly() + : Volume() { + } + /// Copy from handle - Assembly(const Assembly& v) : Volume(v) {} - + Assembly(const Assembly& v) + : Volume(v) { + } + /// Copy from arbitrary Element - template <typename T> Assembly(const Handle<T>& v) : Volume(v) {} - + template <typename T> Assembly(const Handle<T>& v) + : Volume(v) { + } + /// Constructor to be used when creating a new geometry tree. Assembly(const std::string& name); /// Assignment operator (must match copy constructor) - Assembly& operator=(const Assembly& a) { m_element=a.m_element; return *this; } + Assembly& operator=(const Assembly& a) { + m_element = a.m_element; + return *this; + } }; - } /* End namespace Geometry */ -} /* End namespace DD4hep */ + } /* End namespace Geometry */ +} /* End namespace DD4hep */ #endif /* DD4hep_GEOMETRY_VOLUMES_H */ diff --git a/DDCore/include/DD4hep/config.h b/DDCore/include/DD4hep/config.h index f9783de5e..337ca06ea 100644 --- a/DDCore/include/DD4hep/config.h +++ b/DDCore/include/DD4hep/config.h @@ -16,11 +16,11 @@ * DD4hep namespace declaration */ namespace DD4hep { - + /* * Geometry sub-namespace declaration */ - namespace Geometry { - } /* End namespace Geometry */ -} /* End namespace DD4hep */ + namespace Geometry { + } /* End namespace Geometry */ +} /* End namespace DD4hep */ #endif /* DD4HEP_CONFIG_H */ diff --git a/DDCore/include/XML/Conversions.h b/DDCore/include/XML/Conversions.h index 9ae37008e..40d69cf27 100644 --- a/DDCore/include/XML/Conversions.h +++ b/DDCore/include/XML/Conversions.h @@ -20,32 +20,42 @@ namespace DD4hep { // Forward declarations - namespace XML { struct Handle_t; } + namespace XML { + struct Handle_t; + } - /** @class Converter Conversions.h DD4hep/compact/Conversions.h - * - * Basic conversion objects for handling DD4hep XML files. - * - * @author M.Frank - * @version 1.0 - */ - template <typename T> struct Converter { - typedef T to_type; - typedef void* user_param; - /// Reference to the detector description object - Geometry::LCDD& lcdd; - /// Reference to optional user defined parameter - user_param param; - /// Initializing constructor of the functor - Converter(Geometry::LCDD& l) : lcdd(l), param(0) {} - /// Initializing constructor of the functor with initialization of the user parameter - Converter(Geometry::LCDD& l, user_param p) : lcdd(l), param(p) {} - /// Callback operator to be specialized depending on the element type - void operator()(XML::Handle_t xml) const; - /// Typed access to the user parameter (unchecked) - template <typename TYPE> TYPE* _param() const { return (TYPE*)param; } - /// Typed object access to the user parameter (unchecked) - template <typename TYPE> TYPE& _object() const { return *(TYPE*)param; } - }; -} /* End namespace DD4hep */ + /** @class Converter Conversions.h DD4hep/compact/Conversions.h + * + * Basic conversion objects for handling DD4hep XML files. + * + * @author M.Frank + * @version 1.0 + */ + template <typename T> struct Converter { + typedef T to_type; + typedef void* user_param; + /// Reference to the detector description object + Geometry::LCDD& lcdd; + /// Reference to optional user defined parameter + user_param param; + /// Initializing constructor of the functor + Converter(Geometry::LCDD& l) + : lcdd(l), param(0) { + } + /// Initializing constructor of the functor with initialization of the user parameter + Converter(Geometry::LCDD& l, user_param p) + : lcdd(l), param(p) { + } + /// Callback operator to be specialized depending on the element type + void operator()(XML::Handle_t xml) const; + /// Typed access to the user parameter (unchecked) + template <typename TYPE> TYPE* _param() const { + return (TYPE*) param; + } + /// Typed object access to the user parameter (unchecked) + template <typename TYPE> TYPE& _object() const { + return *(TYPE*) param; + } + }; +} /* End namespace DD4hep */ #endif /* DD4hep_COMPACT_CONVERSION_H */ diff --git a/DDCore/include/XML/DocumentHandler.h b/DDCore/include/XML/DocumentHandler.h index 30c598cc4..3d0eff70b 100644 --- a/DDCore/include/XML/DocumentHandler.h +++ b/DDCore/include/XML/DocumentHandler.h @@ -17,18 +17,18 @@ namespace DD4hep { /* - * XML namespace declaration - */ - namespace XML { + * XML namespace declaration + */ + namespace XML { // Forward declarations struct DocumentErrorHandler; /** @class DocumentHandler XMLDetector.h XML/XMLDetector.h - * + * * Wrapper object around the document parser. * Supports both, XercesC and TiXml. - * + * * @author M.Frank * @version 1.0 */ @@ -42,7 +42,7 @@ namespace DD4hep { /// Default destructor virtual ~DocumentHandler(); // Create new XML document by parsing empty xml buffer - Document create(const char* tag, const char* comment=0) const; + Document create(const char* tag, const char* comment = 0) const; /// Load XML file and parse it. virtual Document load(const std::string& fname) const; /// Load secondary XML file with relative addressing with respect to handle @@ -53,5 +53,5 @@ namespace DD4hep { virtual int output(Document doc, const std::string& fname) const; }; } -} /* End namespace DD4hep */ +} /* End namespace DD4hep */ #endif /* DD4HEP_XML_DOCUMENTHANDLER_H */ diff --git a/DDCore/include/XML/Evaluator.h b/DDCore/include/XML/Evaluator.h index 694a63ee6..4a6632c2b 100644 --- a/DDCore/include/XML/Evaluator.h +++ b/DDCore/include/XML/Evaluator.h @@ -7,255 +7,248 @@ namespace XmlTools { -/** - * Evaluator of arithmetic expressions with an extendable dictionary. - * - * Taken from CLHEP 1.9.2.1 - * - * Example: - * @code - * #include "XmlTools/Evaluator.h" - * XmlTools::Evaluator eval; - * eval.setStdMath(); - * double res = eval.evaluate("sin(30*degree)"); - * if (eval.status() != XmlTools::Evaluator::OK) eval.print_error(); - * @endcode - * - * @author Evgeni Chernyaev <Evgueni.Tcherniaev@cern.ch> - * @ingroup evaluator - */ -class Evaluator { - public: - - /** - * List of possible statuses. - * Status of the last operation can be obtained with status(). - * In case if status() is an ERROR the corresponding error message - * can be printed with print_error(). - * - * @see status - * @see error_position - * @see print_error - */ - enum { - OK, /**< Everything OK */ - WARNING_EXISTING_VARIABLE, /**< Redefinition of existing variable */ - WARNING_EXISTING_FUNCTION, /**< Redefinition of existing function */ - WARNING_BLANK_STRING, /**< Empty input string */ - ERROR_NOT_A_NAME, /**< Not allowed sysmbol in the name of variable or function */ - ERROR_SYNTAX_ERROR, /**< Systax error */ - ERROR_UNPAIRED_PARENTHESIS, /**< Unpaired parenthesis */ - ERROR_UNEXPECTED_SYMBOL, /**< Unexpected sysbol */ - ERROR_UNKNOWN_VARIABLE, /**< Non-existing variable */ - ERROR_UNKNOWN_FUNCTION, /**< Non-existing function */ - ERROR_EMPTY_PARAMETER, /**< Function call has empty parameter */ - ERROR_CALCULATION_ERROR /**< Error during calculation */ - }; - - /** - * Constructor. - */ - Evaluator(); - - /** - * Destructor. - */ - ~Evaluator(); - - /** - * Evaluates the arithmetic expression given as character string. - * The expression may consist of numbers, variables and functions - * separated by arithmetic (+, - , /, *, ^, **) and logical - * operators (==, !=, >, >=, <, <=, &&, ||). - * - * @param expression input expression. - * @return result of the evaluation. - * @see status - * @see error_position - * @see print_error - */ - double evaluate(const char * expression); - - /** - * Returns status of the last operation with the evaluator. - */ - int status() const; - - /** - * Returns position in the input string where the problem occured. - */ - int error_position() const; - - /** - * Prints error message if status() is an ERROR. - */ - void print_error() const; - - /** - * Adds to the dictionary a variable with given value. - * If a variable with such a name already exist in the dictionary, - * then status will be set to WARNING_EXISTING_VARIABLE. - * - * @param name name of the variable. - * @param value value assigned to the variable. - */ - void setVariable(const char * name, double value); - - /** - * Adds to the dictionary a variable with an arithmetic expression - * assigned to it. - * If a variable with such a name already exist in the dictionary, - * then status will be set to WARNING_EXISTING_VARIABLE. - * - * @param name name of the variable. - * @param expression arithmetic expression. - */ - void setVariable(const char * name, const char * expression); - - /** - * Adds to the dictionary a function without parameters. - * If such a function already exist in the dictionary, - * then status will be set to WARNING_EXISTING_FUNCTION. - * - * @param name function name. - * @param fun pointer to the real function in the user code. - */ - void setFunction(const char * name, double (*fun)()); - - /** - * Adds to the dictionary a function with one parameter. - * If such a function already exist in the dictionary, - * then status will be set to WARNING_EXISTING_FUNCTION. - * - * @param name function name. - * @param fun pointer to the real function in the user code. - */ - void setFunction(const char * name, double (*fun)(double)); - - /** - * Adds to the dictionary a function with two parameters. - * If such a function already exist in the dictionary, - * then status will be set to WARNING_EXISTING_FUNCTION. - * - * @param name function name. - * @param fun pointer to the real function in the user code. - */ - void setFunction(const char * name, double (*fun)(double,double)); - /** - * Adds to the dictionary a function with three parameters. - * If such a function already exist in the dictionary, - * then status will be set to WARNING_EXISTING_FUNCTION. + * Evaluator of arithmetic expressions with an extendable dictionary. * - * @param name function name. - * @param fun pointer to the real function in the user code. - */ - void setFunction(const char * name, double (*fun)(double,double,double)); - - /** - * Adds to the dictionary a function with four parameters. - * If such a function already exist in the dictionary, - * then status will be set to WARNING_EXISTING_FUNCTION. - * - * @param name function name. - * @param fun pointer to the real function in the user code. - */ - void setFunction(const char * name, - double (*fun)(double,double,double,double)); - - /** - * Adds to the dictionary a function with five parameters. - * If such a function already exist in the dictionary, - * then status will be set to WARNING_EXISTING_FUNCTION. + * Taken from CLHEP 1.9.2.1 * - * @param name function name. - * @param fun pointer to the real function in the user code. - */ - void setFunction(const char * name, - double (*fun)(double,double,double,double,double)); - - /** - * Finds the variable in the dictionary. - * - * @param name name of the variable. - * @return true if such a variable exists, false otherwise. - */ - bool findVariable(const char * name) const; - - /** - * Finds the function in the dictionary. - * - * @param name name of the function to be unset. - * @param npar number of parameters of the function. - * @return true if such a function exists, false otherwise. - */ - bool findFunction(const char * name, int npar) const; - - /** - * Removes the variable from the dictionary. - * - * @param name name of the variable. - */ - void removeVariable(const char * name); - - /** - * Removes the function from the dictionary. - * - * @param name name of the function to be unset. - * @param npar number of parameters of the function. - */ - void removeFunction(const char * name, int npar); - - /** - * Clear all settings. - */ - void clear(); - - /** - * Sets standard mathematical functions and constants. - */ - void setStdMath(); - - /** - * Sets system of units. Default is the SI system of units. - * To set the CGS (Centimeter-Gram-Second) system of units - * one should call: - * setSystemOfUnits(100., 1000., 1.0, 1.0, 1.0, 1.0, 1.0); - * - * To set system of units accepted in the GEANT4 simulation toolkit - * one should call: + * Example: * @code - * setSystemOfUnits(1.e+3, 1./1.60217733e-25, 1.e+9, 1./1.60217733e-10, - * 1.0, 1.0, 1.0); + * #include "XmlTools/Evaluator.h" + * XmlTools::Evaluator eval; + * eval.setStdMath(); + * double res = eval.evaluate("sin(30*degree)"); + * if (eval.status() != XmlTools::Evaluator::OK) eval.print_error(); * @endcode * - * The basic units in GEANT4 are: - * @code - * millimeter (millimeter = 1.) - * nanosecond (nanosecond = 1.) - * Mega electron Volt (MeV = 1.) - * positron charge (eplus = 1.) - * degree Kelvin (kelvin = 1.) - * the amount of substance (mole = 1.) - * luminous intensity (candela = 1.) - * radian (radian = 1.) - * steradian (steradian = 1.) - * @endcode - */ - void setSystemOfUnits(double meter = 1.0, - double kilogram = 1.0, - double second = 1.0, - double ampere = 1.0, - double kelvin = 1.0, - double mole = 1.0, - double candela = 1.0); - -private: - void * p; // private data - Evaluator(const Evaluator &); // copy constructor is not allowed - Evaluator & operator=(const Evaluator &); // assignment is not allowed -}; + * @author Evgeni Chernyaev <Evgueni.Tcherniaev@cern.ch> + * @ingroup evaluator + */ + class Evaluator { + public: + + /** + * List of possible statuses. + * Status of the last operation can be obtained with status(). + * In case if status() is an ERROR the corresponding error message + * can be printed with print_error(). + * + * @see status + * @see error_position + * @see print_error + */ + enum { + OK, /**< Everything OK */ + WARNING_EXISTING_VARIABLE, /**< Redefinition of existing variable */ + WARNING_EXISTING_FUNCTION, /**< Redefinition of existing function */ + WARNING_BLANK_STRING, /**< Empty input string */ + ERROR_NOT_A_NAME, /**< Not allowed sysmbol in the name of variable or function */ + ERROR_SYNTAX_ERROR, /**< Systax error */ + ERROR_UNPAIRED_PARENTHESIS, /**< Unpaired parenthesis */ + ERROR_UNEXPECTED_SYMBOL, /**< Unexpected sysbol */ + ERROR_UNKNOWN_VARIABLE, /**< Non-existing variable */ + ERROR_UNKNOWN_FUNCTION, /**< Non-existing function */ + ERROR_EMPTY_PARAMETER, /**< Function call has empty parameter */ + ERROR_CALCULATION_ERROR /**< Error during calculation */ + }; + + /** + * Constructor. + */ + Evaluator(); + + /** + * Destructor. + */ + ~Evaluator(); + + /** + * Evaluates the arithmetic expression given as character string. + * The expression may consist of numbers, variables and functions + * separated by arithmetic (+, - , /, *, ^, **) and logical + * operators (==, !=, >, >=, <, <=, &&, ||). + * + * @param expression input expression. + * @return result of the evaluation. + * @see status + * @see error_position + * @see print_error + */ + double evaluate(const char * expression); + + /** + * Returns status of the last operation with the evaluator. + */ + int status() const; + + /** + * Returns position in the input string where the problem occured. + */ + int error_position() const; + + /** + * Prints error message if status() is an ERROR. + */ + void print_error() const; + + /** + * Adds to the dictionary a variable with given value. + * If a variable with such a name already exist in the dictionary, + * then status will be set to WARNING_EXISTING_VARIABLE. + * + * @param name name of the variable. + * @param value value assigned to the variable. + */ + void setVariable(const char * name, double value); + + /** + * Adds to the dictionary a variable with an arithmetic expression + * assigned to it. + * If a variable with such a name already exist in the dictionary, + * then status will be set to WARNING_EXISTING_VARIABLE. + * + * @param name name of the variable. + * @param expression arithmetic expression. + */ + void setVariable(const char * name, const char * expression); + + /** + * Adds to the dictionary a function without parameters. + * If such a function already exist in the dictionary, + * then status will be set to WARNING_EXISTING_FUNCTION. + * + * @param name function name. + * @param fun pointer to the real function in the user code. + */ + void setFunction(const char * name, double (*fun)()); + + /** + * Adds to the dictionary a function with one parameter. + * If such a function already exist in the dictionary, + * then status will be set to WARNING_EXISTING_FUNCTION. + * + * @param name function name. + * @param fun pointer to the real function in the user code. + */ + void setFunction(const char * name, double (*fun)(double)); + + /** + * Adds to the dictionary a function with two parameters. + * If such a function already exist in the dictionary, + * then status will be set to WARNING_EXISTING_FUNCTION. + * + * @param name function name. + * @param fun pointer to the real function in the user code. + */ + void setFunction(const char * name, double (*fun)(double, double)); + + /** + * Adds to the dictionary a function with three parameters. + * If such a function already exist in the dictionary, + * then status will be set to WARNING_EXISTING_FUNCTION. + * + * @param name function name. + * @param fun pointer to the real function in the user code. + */ + void setFunction(const char * name, double (*fun)(double, double, double)); + + /** + * Adds to the dictionary a function with four parameters. + * If such a function already exist in the dictionary, + * then status will be set to WARNING_EXISTING_FUNCTION. + * + * @param name function name. + * @param fun pointer to the real function in the user code. + */ + void setFunction(const char * name, double (*fun)(double, double, double, double)); + + /** + * Adds to the dictionary a function with five parameters. + * If such a function already exist in the dictionary, + * then status will be set to WARNING_EXISTING_FUNCTION. + * + * @param name function name. + * @param fun pointer to the real function in the user code. + */ + void setFunction(const char * name, double (*fun)(double, double, double, double, double)); + + /** + * Finds the variable in the dictionary. + * + * @param name name of the variable. + * @return true if such a variable exists, false otherwise. + */ + bool findVariable(const char * name) const; + + /** + * Finds the function in the dictionary. + * + * @param name name of the function to be unset. + * @param npar number of parameters of the function. + * @return true if such a function exists, false otherwise. + */ + bool findFunction(const char * name, int npar) const; + + /** + * Removes the variable from the dictionary. + * + * @param name name of the variable. + */ + void removeVariable(const char * name); + + /** + * Removes the function from the dictionary. + * + * @param name name of the function to be unset. + * @param npar number of parameters of the function. + */ + void removeFunction(const char * name, int npar); + + /** + * Clear all settings. + */ + void clear(); + + /** + * Sets standard mathematical functions and constants. + */ + void setStdMath(); + + /** + * Sets system of units. Default is the SI system of units. + * To set the CGS (Centimeter-Gram-Second) system of units + * one should call: + * setSystemOfUnits(100., 1000., 1.0, 1.0, 1.0, 1.0, 1.0); + * + * To set system of units accepted in the GEANT4 simulation toolkit + * one should call: + * @code + * setSystemOfUnits(1.e+3, 1./1.60217733e-25, 1.e+9, 1./1.60217733e-10, + * 1.0, 1.0, 1.0); + * @endcode + * + * The basic units in GEANT4 are: + * @code + * millimeter (millimeter = 1.) + * nanosecond (nanosecond = 1.) + * Mega electron Volt (MeV = 1.) + * positron charge (eplus = 1.) + * degree Kelvin (kelvin = 1.) + * the amount of substance (mole = 1.) + * luminous intensity (candela = 1.) + * radian (radian = 1.) + * steradian (steradian = 1.) + * @endcode + */ + void setSystemOfUnits(double meter = 1.0, double kilogram = 1.0, double second = 1.0, double ampere = 1.0, double kelvin = + 1.0, double mole = 1.0, double candela = 1.0); + + private: + void * p; // private data + Evaluator(const Evaluator &); // copy constructor is not allowed + Evaluator & operator=(const Evaluator &); // assignment is not allowed + }; -} // namespace XmlTools +} // namespace XmlTools #endif /* XMLTOOLS_EVALUATOR_H */ diff --git a/DDCore/include/XML/Layering.h b/DDCore/include/XML/Layering.h index 7c1b38173..52755f2a7 100644 --- a/DDCore/include/XML/Layering.h +++ b/DDCore/include/XML/Layering.h @@ -18,64 +18,93 @@ */ namespace DD4hep { - struct LayerSlice { - bool _sensitive; + struct LayerSlice { + bool _sensitive; double _thickness; std::string _material; LayerSlice(bool s, double t, const std::string& m) - : _sensitive(s), _thickness(t), _material(m) {} + : _sensitive(s), _thickness(t), _material(m) { + } LayerSlice(const LayerSlice& c) - : _sensitive(c._sensitive), _thickness(c._thickness), _material(c._material) {} + : _sensitive(c._sensitive), _thickness(c._thickness), _material(c._material) { + } LayerSlice& operator=(const LayerSlice& c); }; - struct Layer { + struct Layer { double _thickness; double _preOffset; std::vector<LayerSlice> _slices; - Layer() : _thickness(0.), _preOffset(0.) {} + Layer() + : _thickness(0.), _preOffset(0.) { + } Layer(const Layer& c); Layer& operator=(const Layer& c); void compute(); - double thickness() const { return _thickness; } - double thicknessWithPreOffset() const { return _thickness+_preOffset; } - void add(const LayerSlice& s) { _slices.push_back(s); } + double thickness() const { + return _thickness; + } + double thicknessWithPreOffset() const { + return _thickness + _preOffset; + } + void add(const LayerSlice& s) { + _slices.push_back(s); + } }; - struct LayerStack { + struct LayerStack { std::vector<Layer*> _layers; - LayerStack() {} - LayerStack(const LayerStack& c) : _layers(c._layers) {} - ~LayerStack() {} - LayerStack& operator=(const LayerStack& c) { _layers = c._layers; return *this; } - std::vector<Layer*>& layers() { return _layers; } - const std::vector<Layer*>& layers() const { return _layers; } + LayerStack() { + } + LayerStack(const LayerStack& c) + : _layers(c._layers) { + } + ~LayerStack() { + } + LayerStack& operator=(const LayerStack& c) { + _layers = c._layers; + return *this; + } + std::vector<Layer*>& layers() { + return _layers; + } + const std::vector<Layer*>& layers() const { + return _layers; + } double sectionThickness(size_t is, size_t ie) const; - double totalThickness() const { return sectionThickness(0,_layers.size()-1); } + double totalThickness() const { + return sectionThickness(0, _layers.size() - 1); + } }; - struct Layering { + struct Layering { LayerStack _stack; Layering(); Layering(XML::Element e); virtual ~Layering(); - std::vector<Layer*>& layers() { return _stack.layers(); } + std::vector<Layer*>& layers() { + return _stack.layers(); + } const Layer* layer(size_t which) const; - double totalThickness() const { return _stack.totalThickness(); } - double singleLayerThickness(XML::Element e) const; + double totalThickness() const { + return _stack.totalThickness(); + } + double singleLayerThickness(XML::Element e) const; }; /* - * XML namespace declaration - */ - namespace XML { + * XML namespace declaration + */ + namespace XML { // Tag and attribute objects. See XMLTags.cpp for the instantiation - struct LayeringCnv : public Element { - LayeringCnv(Element e) : Element(e ) {} - void fromCompact(Layering& layering) const; + struct LayeringCnv: public Element { + LayeringCnv(Element e) + : Element(e) { + } + void fromCompact(Layering& layering) const; }; } -} /* End namespace DD4hep */ +} /* End namespace DD4hep */ #endif /* DD4hep_LAYERING_H */ diff --git a/DDCore/include/XML/UnicodeValues.h b/DDCore/include/XML/UnicodeValues.h index becb3e0cc..9bbdfe465 100644 --- a/DDCore/include/XML/UnicodeValues.h +++ b/DDCore/include/XML/UnicodeValues.h @@ -1,5 +1,5 @@ - -namespace DD4hep { namespace XML { +namespace DD4hep { + namespace XML { extern const Tag_t Unicode_NULL; extern const Tag_t Unicode_empty; @@ -7,453 +7,452 @@ namespace DD4hep { namespace XML { extern const Tag_t Unicode_PI; extern const Tag_t Unicode_TWOPI; - UNICODE(0); - UNICODE(1); - UNICODE(2); - UNICODE(3); - UNICODE(4); - UNICODE(5); - UNICODE(6); - UNICODE(7); - UNICODE(8); - UNICODE(9); - - - UNICODE(a); - UNICODE(A); - UNICODE(Air); - UNICODE(angle); - UNICODE(alignment); - UNICODE(alignments); - UNICODE(alpha); - UNICODE(alpha1); - UNICODE(alpha2); - UNICODE(alpha3); - UNICODE(alpha4); - UNICODE(arb8); - UNICODE(assembly); - UNICODE(atom); - UNICODE(attributes); - UNICODE(aunit); - UNICODE(author); - - UNICODE(b); - UNICODE(B); - UNICODE(barrel); - UNICODE(barrel_envelope); - UNICODE(beampipe); - UNICODE(beta); - UNICODE(box); - - UNICODE(c); - UNICODE(C); - UNICODE(calorimeter); - UNICODE(cartesian_grid_xy); - UNICODE(chamber); - UNICODE(chambers); - UNICODE(check); - UNICODE(checksum); - UNICODE(cm); - UNICODE(color); - UNICODE(combine_hits); - UNICODE(combineHits); - UNICODE(comment); - UNICODE(component); - UNICODE(composite); - UNICODE(cone); - UNICODE(constant); - UNICODE(crossing_angle); - UNICODE(cut); - - UNICODE(d); - UNICODE(D); - UNICODE(define); - UNICODE(delta); - UNICODE(deltaphi); - UNICODE(deltatheta); - UNICODE(depth); - UNICODE(desnity); - UNICODE(detector); - UNICODE(detectors); - UNICODE(dim_r); - UNICODE(dim_x); - UNICODE(dim_y); - UNICODE(dim_z); - UNICODE(dimensions); - UNICODE(dipole_coeff); - UNICODE(disk); - UNICODE(disks); - UNICODE(display); - UNICODE(dr); - UNICODE(drawing_style); - UNICODE(drawingStyle); - UNICODE(dx); - UNICODE(dy); - UNICODE(dz); - - UNICODE(e); - UNICODE(E); - UNICODE(ecut); - UNICODE(element); - UNICODE(eltube); - UNICODE(end); - UNICODE(end_module); - UNICODE(end_modules); - UNICODE(endcap); - UNICODE(endphi); - UNICODE(epsilon); - UNICODE(eunit); - UNICODE(end_x); - UNICODE(end_y); - UNICODE(end_z); - - UNICODE(f); - UNICODE(F); - UNICODE(false); - UNICODE(field); - UNICODE(fields); - UNICODE(field_name); - UNICODE(file); - UNICODE(first); - UNICODE(firstposition); - UNICODE(firstrotation); - UNICODE(formula); - UNICODE(fraction); - UNICODE(funit); - - UNICODE(g); - UNICODE(G); - UNICODE(gamma); - UNICODE(gap); - UNICODE(gas); - UNICODE(generator); - UNICODE(gdml); - UNICODE(gdmlFile); - UNICODE(glass); - UNICODE(global); - UNICODE(global_grid_xy); - UNICODE(grid_size_x); - UNICODE(grid_size_y); - UNICODE(grid_size_z); - UNICODE(grid_size_phi); - UNICODE(grid_xyz); - UNICODE(gridSizePhi); - UNICODE(gridSizeX); - UNICODE(gridSizeY); - UNICODE(gridSizeZ); - - UNICODE(h); - UNICODE(H); - UNICODE(half_x); - UNICODE(half_y); - UNICODE(half_z); - UNICODE(header); - UNICODE(height); - UNICODE(hits_collection); - UNICODE(hype); - - UNICODE(i); - UNICODE(I); - UNICODE(id); - UNICODE(iddict); - UNICODE(identity_rot); - UNICODE(identity_pos); - UNICODE(idfield); - UNICODE(idspec); - UNICODE(idspecref); - UNICODE(includes); - UNICODE(incoming_r); - UNICODE(info); - UNICODE(inner); - UNICODE(inner_field); - UNICODE(inner_r); - UNICODE(inner_radius); - UNICODE(inner_z); - UNICODE(insideTrackingVolume); - UNICODE(intersection); - UNICODE(InvisibleNoDaughters); - UNICODE(InvisibleWithDaughters); - - UNICODE(j); - UNICODE(J); - - UNICODE(k); - UNICODE(K); - - UNICODE(l); - UNICODE(L); - UNICODE(label); - UNICODE(ladder); - UNICODE(layer); - UNICODE(layers); - UNICODE(lcdd); - UNICODE(lccdd); - UNICODE(length); - UNICODE(limit); - UNICODE(limits); - UNICODE(limitset); - UNICODE(limitsetref); - UNICODE(line_style); - UNICODE(lineStyle); - UNICODE(local); - UNICODE(lunit); - - UNICODE(m); - UNICODE(M); - UNICODE(material); - UNICODE(materialref); - UNICODE(materials); - UNICODE(member); - UNICODE(MeV); - UNICODE(mm); - UNICODE(module); - UNICODE(modules); - UNICODE(module_component); - UNICODE(module_envelope); - UNICODE(moduleHeight); - UNICODE(modulePitch); - UNICODE(modulePosX); - UNICODE(modulePosY); - UNICODE(moduleWidth); - - UNICODE(n); - UNICODE(N); - UNICODE(NIL); - UNICODE(name); - UNICODE(nmodules); - UNICODE(nModules); - UNICODE(nonprojective_cylinder); - UNICODE(nPads); - UNICODE(nphi); - UNICODE(ntheta); - UNICODE(number); - UNICODE(numsides); - UNICODE(nz); - - UNICODE(o); - UNICODE(O); - UNICODE(offset); - UNICODE(overlap); - UNICODE(outer); - UNICODE(outer_field); - UNICODE(outer_r); - UNICODE(outer_radius); - UNICODE(outer_z); - UNICODE(outgoing_r); - UNICODE(outst); - - UNICODE(p); - UNICODE(P); - UNICODE(padPitch); - UNICODE(pads); - UNICODE(para); - UNICODE(paraboloid); - UNICODE(param); - UNICODE(params); - UNICODE(particles); - UNICODE(phi); - UNICODE(phi0); - UNICODE(phi1); - UNICODE(phi_tilt); - UNICODE(phiBins); - UNICODE(phi_size_max); - UNICODE(physvol); - UNICODE(physvolid); - UNICODE(polyhedra); - UNICODE(polycone); - UNICODE(position); - UNICODE(positionref); - UNICODE(projective_cylinder); - UNICODE(projective_zplane); - UNICODE(properties); - UNICODE(psi); - - UNICODE(q); - UNICODE(Q); - - UNICODE(r); - UNICODE(R); - UNICODE(r_size); - UNICODE(r0); - UNICODE(rad); - UNICODE(radian); - UNICODE(radius); - UNICODE(radiator); - UNICODE(rbg); - UNICODE(rc); - UNICODE(readout); - UNICODE(readouts); - UNICODE(ref); - UNICODE(reflect); - UNICODE(reflect_rot); - UNICODE(region); - UNICODE(regions); - UNICODE(regionref); - UNICODE(repeat); - UNICODE(rhi); - UNICODE(ring); - UNICODE(rlo); - UNICODE(rmax); - UNICODE(rmax1); - UNICODE(rmax2); - UNICODE(rmin); - UNICODE(rmin1); - UNICODE(rmin2); - UNICODE(RL); - UNICODE(row); - UNICODE(rpc); - UNICODE(RowID); - UNICODE(rowHeight); - UNICODE(rowPitch); - UNICODE(rphi_layout); - UNICODE(rotation); - UNICODE(rotationref); - UNICODE(rtor); - - UNICODE(s); - UNICODE(S); - UNICODE(scintillator); - UNICODE(sd); - UNICODE(sdref); - UNICODE(second); - UNICODE(segmentation); - UNICODE(sensitive); - UNICODE(sensitive_detector); - UNICODE(sensitive_detectors); - UNICODE(sensor); - UNICODE(sequence); - UNICODE(setup); - UNICODE(signed); - UNICODE(solidref); - UNICODE(sphere); - UNICODE(show_daughters); - UNICODE(showDaughters); - UNICODE(slice); - UNICODE(slices); - UNICODE(solid); - UNICODE(solids); - UNICODE(spacer); - UNICODE(status); - UNICODE(start); - UNICODE(start_x); - UNICODE(start_y); - UNICODE(start_z); - UNICODE(startphi); - UNICODE(starttheta); - UNICODE(stave); - UNICODE(staves); - UNICODE(store_secondaries); - UNICODE(strength); - UNICODE(structure); - UNICODE(subtraction); - UNICODE(support); - UNICODE(system); - - UNICODE(t); - UNICODE(T); - UNICODE(theta); - UNICODE(thetaBins); - UNICODE(thickness); - UNICODE(threshold); - UNICODE(title); - UNICODE(tube); - UNICODE(tubes); - UNICODE(torus); - UNICODE(tracker); - UNICODE(tracking_cylinder); - UNICODE(tracking_volume); - UNICODE(trap); - UNICODE(trd); - UNICODE(true); - UNICODE(tubs); - UNICODE(type); - - UNICODE(u); - UNICODE(U); - UNICODE(union); - UNICODE(unit); - UNICODE(useForHitPosition); - UNICODE(url); - - UNICODE(v); - UNICODE(V); - UNICODE(v1x); - UNICODE(v1y); - UNICODE(v2x); - UNICODE(v2y); - UNICODE(v3x); - UNICODE(v3y); - UNICODE(v4x); - UNICODE(v4y); - UNICODE(v5x); - UNICODE(v5y); - UNICODE(v6x); - UNICODE(v6y); - UNICODE(v7x); - UNICODE(v7y); - UNICODE(v8x); - UNICODE(v8y); - UNICODE(Vacuum); - UNICODE(value); - UNICODE(verbose); - UNICODE(version); - UNICODE(vis); - UNICODE(visible); - UNICODE(visref); - UNICODE(volume); - UNICODE(volumeref); - - UNICODE(w); - UNICODE(W); - UNICODE(wedge); - UNICODE(width); - UNICODE(world); - UNICODE(world_box); - UNICODE(world_volume); - - UNICODE(x); - UNICODE(X); - UNICODE(x_offset); - UNICODE(x0); - UNICODE(x1); - UNICODE(X1); - UNICODE(x2); - UNICODE(X2); - UNICODE(x3); - UNICODE(x4); - UNICODE(xhalf); - UNICODE(xmin); - UNICODE(xmax); - - UNICODE(y); - UNICODE(Y); - UNICODE(y0); - UNICODE(y1); - UNICODE(Y1); - UNICODE(y2); - UNICODE(Y2); - UNICODE(y3); - UNICODE(y4); - UNICODE(yhalf); - UNICODE(ymin); - UNICODE(ymax); - UNICODE(y_offset); - - UNICODE(z); - UNICODE(Z); - UNICODE(z_layout); - UNICODE(z_length); - UNICODE(z_offset); - UNICODE(z0); - UNICODE(z1); - UNICODE(z2); - UNICODE(z3); - UNICODE(z4); - UNICODE(zhalf); - UNICODE(zmin); - UNICODE(zmax); - UNICODE(zplane); - UNICODE(zstart); - - -}} + UNICODE(0); + UNICODE(1); + UNICODE(2); + UNICODE(3); + UNICODE(4); + UNICODE(5); + UNICODE(6); + UNICODE(7); + UNICODE(8); + UNICODE(9); + + UNICODE (a); + UNICODE (A); + UNICODE (Air); + UNICODE (angle); + UNICODE (alignment); + UNICODE (alignments); + UNICODE (alpha); + UNICODE (alpha1); + UNICODE (alpha2); + UNICODE (alpha3); + UNICODE (alpha4); + UNICODE (arb8); + UNICODE (assembly); + UNICODE (atom); + UNICODE (attributes); + UNICODE (aunit); + UNICODE (author); + + UNICODE (b); + UNICODE (B); + UNICODE (barrel); + UNICODE (barrel_envelope); + UNICODE (beampipe); + UNICODE (beta); + UNICODE (box); + + UNICODE (c); + UNICODE (C); + UNICODE (calorimeter); + UNICODE (cartesian_grid_xy); + UNICODE (chamber); + UNICODE (chambers); + UNICODE (check); + UNICODE (checksum); + UNICODE (cm); + UNICODE (color); + UNICODE (combine_hits); + UNICODE (combineHits); + UNICODE (comment); + UNICODE (component); + UNICODE (composite); + UNICODE (cone); + UNICODE (constant); + UNICODE (crossing_angle); + UNICODE (cut); + + UNICODE (d); + UNICODE (D); + UNICODE (define); + UNICODE (delta); + UNICODE (deltaphi); + UNICODE (deltatheta); + UNICODE (depth); + UNICODE (desnity); + UNICODE (detector); + UNICODE (detectors); + UNICODE (dim_r); + UNICODE (dim_x); + UNICODE (dim_y); + UNICODE (dim_z); + UNICODE (dimensions); + UNICODE (dipole_coeff); + UNICODE (disk); + UNICODE (disks); + UNICODE (display); + UNICODE (dr); + UNICODE (drawing_style); + UNICODE (drawingStyle); + UNICODE (dx); + UNICODE (dy); + UNICODE (dz); + + UNICODE (e); + UNICODE (E); + UNICODE (ecut); + UNICODE (element); + UNICODE (eltube); + UNICODE (end); + UNICODE (end_module); + UNICODE (end_modules); + UNICODE (endcap); + UNICODE (endphi); + UNICODE (epsilon); + UNICODE (eunit); + UNICODE (end_x); + UNICODE (end_y); + UNICODE (end_z); + + UNICODE (f); + UNICODE (F); + UNICODE(false); + UNICODE (field); + UNICODE (fields); + UNICODE (field_name); + UNICODE (file); + UNICODE (first); + UNICODE (firstposition); + UNICODE (firstrotation); + UNICODE (formula); + UNICODE (fraction); + UNICODE (funit); + + UNICODE (g); + UNICODE (G); + UNICODE (gamma); + UNICODE (gap); + UNICODE (gas); + UNICODE (generator); + UNICODE (gdml); + UNICODE (gdmlFile); + UNICODE (glass); + UNICODE (global); + UNICODE (global_grid_xy); + UNICODE (grid_size_x); + UNICODE (grid_size_y); + UNICODE (grid_size_z); + UNICODE (grid_size_phi); + UNICODE (grid_xyz); + UNICODE (gridSizePhi); + UNICODE (gridSizeX); + UNICODE (gridSizeY); + UNICODE (gridSizeZ); + + UNICODE (h); + UNICODE (H); + UNICODE (half_x); + UNICODE (half_y); + UNICODE (half_z); + UNICODE (header); + UNICODE (height); + UNICODE (hits_collection); + UNICODE (hype); + + UNICODE (i); + UNICODE (I); + UNICODE (id); + UNICODE (iddict); + UNICODE (identity_rot); + UNICODE (identity_pos); + UNICODE (idfield); + UNICODE (idspec); + UNICODE (idspecref); + UNICODE (includes); + UNICODE (incoming_r); + UNICODE (info); + UNICODE (inner); + UNICODE (inner_field); + UNICODE (inner_r); + UNICODE (inner_radius); + UNICODE (inner_z); + UNICODE (insideTrackingVolume); + UNICODE (intersection); + UNICODE (InvisibleNoDaughters); + UNICODE (InvisibleWithDaughters); + + UNICODE (j); + UNICODE (J); + + UNICODE (k); + UNICODE (K); + + UNICODE (l); + UNICODE (L); + UNICODE (label); + UNICODE (ladder); + UNICODE (layer); + UNICODE (layers); + UNICODE (lcdd); + UNICODE (lccdd); + UNICODE (length); + UNICODE (limit); + UNICODE (limits); + UNICODE (limitset); + UNICODE (limitsetref); + UNICODE (line_style); + UNICODE (lineStyle); + UNICODE (local); + UNICODE (lunit); + + UNICODE (m); + UNICODE (M); + UNICODE (material); + UNICODE (materialref); + UNICODE (materials); + UNICODE (member); + UNICODE (MeV); + UNICODE (mm); + UNICODE (module); + UNICODE (modules); + UNICODE (module_component); + UNICODE (module_envelope); + UNICODE (moduleHeight); + UNICODE (modulePitch); + UNICODE (modulePosX); + UNICODE (modulePosY); + UNICODE (moduleWidth); + + UNICODE (n); + UNICODE (N); + UNICODE (NIL); + UNICODE (name); + UNICODE (nmodules); + UNICODE (nModules); + UNICODE (nonprojective_cylinder); + UNICODE (nPads); + UNICODE (nphi); + UNICODE (ntheta); + UNICODE (number); + UNICODE (numsides); + UNICODE (nz); + + UNICODE (o); + UNICODE (O); + UNICODE (offset); + UNICODE (overlap); + UNICODE (outer); + UNICODE (outer_field); + UNICODE (outer_r); + UNICODE (outer_radius); + UNICODE (outer_z); + UNICODE (outgoing_r); + UNICODE (outst); + + UNICODE (p); + UNICODE (P); + UNICODE (padPitch); + UNICODE (pads); + UNICODE (para); + UNICODE (paraboloid); + UNICODE (param); + UNICODE (params); + UNICODE (particles); + UNICODE (phi); + UNICODE (phi0); + UNICODE (phi1); + UNICODE (phi_tilt); + UNICODE (phiBins); + UNICODE (phi_size_max); + UNICODE (physvol); + UNICODE (physvolid); + UNICODE (polyhedra); + UNICODE (polycone); + UNICODE (position); + UNICODE (positionref); + UNICODE (projective_cylinder); + UNICODE (projective_zplane); + UNICODE (properties); + UNICODE (psi); + + UNICODE (q); + UNICODE (Q); + + UNICODE (r); + UNICODE (R); + UNICODE (r_size); + UNICODE (r0); + UNICODE (rad); + UNICODE (radian); + UNICODE (radius); + UNICODE (radiator); + UNICODE (rbg); + UNICODE (rc); + UNICODE (readout); + UNICODE (readouts); + UNICODE (ref); + UNICODE (reflect); + UNICODE (reflect_rot); + UNICODE (region); + UNICODE (regions); + UNICODE (regionref); + UNICODE (repeat); + UNICODE (rhi); + UNICODE (ring); + UNICODE (rlo); + UNICODE (rmax); + UNICODE (rmax1); + UNICODE (rmax2); + UNICODE (rmin); + UNICODE (rmin1); + UNICODE (rmin2); + UNICODE (RL); + UNICODE (row); + UNICODE (rpc); + UNICODE (RowID); + UNICODE (rowHeight); + UNICODE (rowPitch); + UNICODE (rphi_layout); + UNICODE (rotation); + UNICODE (rotationref); + UNICODE (rtor); + + UNICODE (s); + UNICODE (S); + UNICODE (scintillator); + UNICODE (sd); + UNICODE (sdref); + UNICODE (second); + UNICODE (segmentation); + UNICODE (sensitive); + UNICODE (sensitive_detector); + UNICODE (sensitive_detectors); + UNICODE (sensor); + UNICODE (sequence); + UNICODE (setup); + UNICODE(signed); + UNICODE (solidref); + UNICODE (sphere); + UNICODE (show_daughters); + UNICODE (showDaughters); + UNICODE (slice); + UNICODE (slices); + UNICODE (solid); + UNICODE (solids); + UNICODE (spacer); + UNICODE (status); + UNICODE (start); + UNICODE (start_x); + UNICODE (start_y); + UNICODE (start_z); + UNICODE (startphi); + UNICODE (starttheta); + UNICODE (stave); + UNICODE (staves); + UNICODE (store_secondaries); + UNICODE (strength); + UNICODE (structure); + UNICODE (subtraction); + UNICODE (support); + UNICODE (system); + + UNICODE (t); + UNICODE (T); + UNICODE (theta); + UNICODE (thetaBins); + UNICODE (thickness); + UNICODE (threshold); + UNICODE (title); + UNICODE (tube); + UNICODE (tubes); + UNICODE (torus); + UNICODE (tracker); + UNICODE (tracking_cylinder); + UNICODE (tracking_volume); + UNICODE (trap); + UNICODE (trd); + UNICODE(true); + UNICODE (tubs); + UNICODE (type); + + UNICODE (u); + UNICODE (U); + UNICODE(union); + UNICODE (unit); + UNICODE (useForHitPosition); + UNICODE (url); + + UNICODE (v); + UNICODE (V); + UNICODE (v1x); + UNICODE (v1y); + UNICODE (v2x); + UNICODE (v2y); + UNICODE (v3x); + UNICODE (v3y); + UNICODE (v4x); + UNICODE (v4y); + UNICODE (v5x); + UNICODE (v5y); + UNICODE (v6x); + UNICODE (v6y); + UNICODE (v7x); + UNICODE (v7y); + UNICODE (v8x); + UNICODE (v8y); + UNICODE (Vacuum); + UNICODE (value); + UNICODE (verbose); + UNICODE (version); + UNICODE (vis); + UNICODE (visible); + UNICODE (visref); + UNICODE (volume); + UNICODE (volumeref); + + UNICODE (w); + UNICODE (W); + UNICODE (wedge); + UNICODE (width); + UNICODE (world); + UNICODE (world_box); + UNICODE (world_volume); + + UNICODE (x); + UNICODE (X); + UNICODE (x_offset); + UNICODE (x0); + UNICODE (x1); + UNICODE (X1); + UNICODE (x2); + UNICODE (X2); + UNICODE (x3); + UNICODE (x4); + UNICODE (xhalf); + UNICODE (xmin); + UNICODE (xmax); + + UNICODE (y); + UNICODE (Y); + UNICODE (y0); + UNICODE (y1); + UNICODE (Y1); + UNICODE (y2); + UNICODE (Y2); + UNICODE (y3); + UNICODE (y4); + UNICODE (yhalf); + UNICODE (ymin); + UNICODE (ymax); + UNICODE (y_offset); + + UNICODE (z); + UNICODE (Z); + UNICODE (z_layout); + UNICODE (z_length); + UNICODE (z_offset); + UNICODE (z0); + UNICODE (z1); + UNICODE (z2); + UNICODE (z3); + UNICODE (z4); + UNICODE (zhalf); + UNICODE (zmin); + UNICODE (zmax); + UNICODE (zplane); + UNICODE (zstart); + + } +} diff --git a/DDCore/include/XML/XMLDetector.h b/DDCore/include/XML/XMLDetector.h index be8e13b8e..d5ce308d9 100644 --- a/DDCore/include/XML/XMLDetector.h +++ b/DDCore/include/XML/XMLDetector.h @@ -18,45 +18,53 @@ namespace DD4hep { /* - * XML namespace declaration - */ - namespace XML { + * XML namespace declaration + */ + namespace XML { /** @class DetElement::Component XMLDetector.h XML/XMLDetector.h - * + * * Helper class to access any field in a xml tag. * Specialized for attributes of a detector sub-element. - * + * * @author M.Frank * @version 1.0 */ - struct Component : public Dimension { + struct Component: public Dimension { /// Constructor from Handle - Component(Handle_t e) : Dimension(e) {} + Component(Handle_t e) + : Dimension(e) { + } /// Constructor from Element - Component(const Element& e) : Dimension(e) {} + Component(const Element& e) + : Dimension(e) { + } /// Check if component is sensitive - bool isSensitive() const; + bool isSensitive() const; /// Access material attribute as STL string - std::string materialStr() const; + std::string materialStr() const; }; /** @class DetElement XMLDetector.h XML/XMLDetector.h - * + * * Helper class to access any field in a xml tag. * Specialized for some of the attributes of a detector element. - * + * * @author M.Frank * @version 1.0 */ - struct DetElement : public Dimension { + struct DetElement: public Dimension { /// Constructor from Handle - DetElement(Handle_t e) : Dimension(e) {} + DetElement(Handle_t e) + : Dimension(e) { + } /// Access underlying XML handle object - Handle_t handle() const { return m_element; } - + Handle_t handle() const { + return m_element; + } + /// Access parameters: id - int id() const; + int id() const; /// Access material attribute as STL string. If not present empty return empty string std::string materialStr() const; /// Check if element describes a tracking detector @@ -68,8 +76,10 @@ namespace DD4hep { /// Helper to check a condition (for debugging) void check(bool condition, const std::string& msg) const; /// Access attribute by type - template <typename T> T attr(const XmlChar* tag) const { return m_element.attr<T>(tag); } + template <typename T> T attr(const XmlChar* tag) const { + return m_element.attr < T > (tag); + } }; } -} /* End namespace DD4hep */ +} /* End namespace DD4hep */ #endif /* DD4HEP_XMLDETECTOR_H */ diff --git a/DDCore/include/XML/XMLDimension.h b/DDCore/include/XML/XMLDimension.h index 586f46951..2bd29d423 100644 --- a/DDCore/include/XML/XMLDimension.h +++ b/DDCore/include/XML/XMLDimension.h @@ -18,14 +18,13 @@ namespace DD4hep { /* - * XML namespace declaration - */ - namespace XML { - + * XML namespace declaration + */ + namespace XML { /** @class Dimension XMLDetector.h XML/XMLDetector.h - * - * Helper class to access any field in a xml tag in a + * + * Helper class to access any field in a xml tag in a * very easy way. * - You may assign any xml handle to a dimension object * - Any attribute of this xml element may then be accessed @@ -33,30 +32,36 @@ namespace DD4hep { * reflected by the Dimmension object's member functions. * - If an attribute is requested and not present, a exception * is thrown. - * - Functions, which accept a default value do NOT throw + * - Functions, which accept a default value do NOT throw * an exception if the attribute is not present. These * rather return the default value. - * - If a often used function is not present - the + * - If a often used function is not present - the * implementation thereof is simple. - * + * * @author M.Frank * @version 1.0 */ - struct Dimension : public Element { + struct Dimension: public Element { /// Default constructor - Dimension() : Element(Handle_t(0)) {} + Dimension() + : Element(Handle_t(0)) { + } /// Constructor from Handle - Dimension(Handle_t e) : Element(e) {} + Dimension(Handle_t e) + : Element(e) { + } /// Constructor from Element - Dimension(const Element& e) : Element(e) {} + Dimension(const Element& e) + : Element(e) { + } /// Access parameters: id - int id() const; + int id() const; /// Access parameters: id, if not present returns default - int id(int default_value) const; + int id(int default_value) const; /// Access parameters: type - int type() const; + int type() const; /// Access rotation constants: combineHits bool combineHits() const; @@ -98,26 +103,26 @@ namespace DD4hep { double deltaphi() const; /// Access parameters: b - double b() const; + double b() const; /// Access parameters: B - double B() const; + double B() const; /// Access parameters: g - double g() const; + double g() const; /// Access parameters: G - double G() const; + double G() const; /// Access parameters: r - double r() const; + double r() const; /// Access parameters: r, if not present returns default - double r(double default_value) const; + double r(double default_value) const; /// Access parameters: R - double R() const; + double R() const; /// Access parameters: dr - double dr() const; + double dr() const; /// Access parameters: r0 - double r0() const; + double r0() const; /// Access parameters: dr, if not present returns default - double dr(double default_value) const; + double dr(double default_value) const; /// Access min/max parameters: rmin double rmin() const; /// Access min/max parameters: rmax @@ -156,7 +161,7 @@ namespace DD4hep { /// Access parameters: dx double dx() const; /// Access parameters: dx, if not present returns default - double dx(double default_value) const; + double dx(double default_value) const; /// Access min/max parameters: xmax double xmin() const; /// Access min/max parameters: xmax @@ -181,7 +186,7 @@ namespace DD4hep { /// Access parameters: dy double dy() const; /// Access parameters: dz, if not present returns default - double dy(double default_value) const; + double dy(double default_value) const; /// Access min/max parameters: ymax double ymin() const; /// Access min/max parameters: ymax @@ -206,7 +211,7 @@ namespace DD4hep { /// Access parameters: dz double dz() const; /// Access parameters: dz, if not present returns default - double dz(double default_value) const; + double dz(double default_value) const; /// Access min/max parameters: zmax double zmin() const; /// Access min/max parameters: zmax @@ -240,13 +245,13 @@ namespace DD4hep { /// Access attribute values: phi_size_max double phi_size_max() const; /// Access attribute values: reflect - bool reflect() const; + bool reflect() const; /// Access attribute values: reflect - bool reflect(bool default_value) const; + bool reflect(bool default_value) const; /// Access attribute values: crossing_angle double crossing_angle() const; /// Access attribute values: repeat - int repeat() const; + int repeat() const; /// Access attribute values: outgoing_r double outgoing_r() const; @@ -257,14 +262,14 @@ namespace DD4hep { /// Access attribute values: offset double offset(double default_value) const; /// Access attribute values: number - int number() const; + int number() const; /// Access attribute values: nmodules - int nmodules() const; + int nmodules() const; /// Access attribute values: nModules - int nModules() const; + int nModules() const; /// Access attribute values: RowID - int RowID() const; + int RowID() const; /// Access attribute values: moduleHeight double moduleHeight() const; /// Access attribute values: moduleWidth @@ -277,7 +282,7 @@ namespace DD4hep { double modulePosY() const; /// Access attribute values: nPads - int nPads() const; + int nPads() const; /// Access attribute values: rowPitch double rowPitch() const; /// Access attribute values: padPitch @@ -288,24 +293,24 @@ namespace DD4hep { std::string padType() const; /// Access attribute values: numsides - int numsides() const; + int numsides() const; /// Access attribute values: phi_tilt double phi_tilt() const; /// Access attribute values: nphi - int nphi() const; + int nphi() const; /// Access attribute values: rc - double rc() const; - + double rc() const; + /// Access attribute values: zstart double zstart() const; /// Access attribute values: nz - int nz() const; + int nz() const; /// Access attribute values: start - double start() const; + double start() const; /// Access attribute values: end - double end() const; + double end() const; /// Access attribute values: inner_field double inner_field() const; /// Access attribute values: outer_field @@ -315,39 +320,39 @@ namespace DD4hep { bool visible() const; /// Access attribute values: show_daughters bool show_daughters() const; - + /// Access child element with tag "dimensions" as Dimension object - Dimension dimensions(bool throw_if_not_present=true) const; + Dimension dimensions(bool throw_if_not_present = true) const; /// Child access: position - Dimension position(bool throw_if_not_present=true) const; + Dimension position(bool throw_if_not_present = true) const; /// Child access: rotation - Dimension rotation(bool throw_if_not_present=true) const; + Dimension rotation(bool throw_if_not_present = true) const; /// Child access: trd - Dimension trd(bool throw_if_not_present=true) const; + Dimension trd(bool throw_if_not_present = true) const; /// Child access: tubs - Dimension tubs(bool throw_if_not_present=true) const; + Dimension tubs(bool throw_if_not_present = true) const; /// Child access: staves - Dimension staves(bool throw_if_not_present=true) const; + Dimension staves(bool throw_if_not_present = true) const; /// Child access: beampipe - Dimension beampipe(bool throw_if_not_present=true) const; + Dimension beampipe(bool throw_if_not_present = true) const; /// Access name attribute as STL string - std::string nameStr() const; + std::string nameStr() const; /// Access ref attribute as a string - std::string refStr() const; + std::string refStr() const; /// Access type attribute as STL string - std::string typeStr() const; + std::string typeStr() const; /// Access module attribute as STL string - std::string moduleStr() const; + std::string moduleStr() const; /// Access readout attribute as STL string - std::string readoutStr() const; + std::string readoutStr() const; /// Access vis attribute as STL string. If not present empty return empty string - std::string visStr() const; + std::string visStr() const; /// Access region attribute as STL string. If not present empty return empty string - std::string regionStr() const; + std::string regionStr() const; /// Access limits attribute as STL string. If not present empty return empty string - std::string limitsStr() const; + std::string limitsStr() const; }; - } /* End namespace XML */ -} /* End namespace DD4hep */ + } /* End namespace XML */ +} /* End namespace DD4hep */ #endif /* DD4HEP_XMLDIMENSION_H */ diff --git a/DDCore/include/XML/XMLElements.h b/DDCore/include/XML/XMLElements.h index ca65b0816..45af4e37b 100644 --- a/DDCore/include/XML/XMLElements.h +++ b/DDCore/include/XML/XMLElements.h @@ -20,10 +20,10 @@ #include "DD4hep/Primitives.h" #ifndef RAD_2_DEGREE - #define RAD_2_DEGREE 57.295779513082320876798154814105 +#define RAD_2_DEGREE 57.295779513082320876798154814105 #endif #ifndef M_PI - #define M_PI 3.14159265358979323846 +#define M_PI 3.14159265358979323846 #endif /* @@ -31,9 +31,9 @@ */ namespace DD4hep { - namespace XML { + namespace XML { - typedef const XmlAttr* Attribute; + typedef const XmlAttr* Attribute; /** XmlString XMLElements.h XML/XMLElements.h * @@ -45,18 +45,18 @@ namespace DD4hep { * @author M.Frank * @version 1.0 */ - class XmlString { + class XmlString { public: /// Replicate string: internally allocates new string, which must be free'ed with release static XmlChar* replicate(const XmlChar* c); /// Transcode string static XmlChar* transcode(const char* c); /// Release string - static void release(char** p); + static void release(char** p); #ifndef __TIXML__ static char* transcode(const XmlChar* c); /// Release string - static void release(XmlChar** p); + static void release(XmlChar** p); #endif }; @@ -72,10 +72,10 @@ namespace DD4hep { */ struct XmlException { std::string msg; - XmlException() : msg() { } - XmlException(const std::string& m) : msg(m) { } - XmlException(const XmlException& e) : msg(e.msg) { } - virtual ~XmlException() { } + XmlException() : msg() {} + XmlException(const std::string& m) : msg(m) {} + XmlException(const XmlException& e) : msg(e.msg) {} + virtual ~XmlException() {} }; #endif @@ -83,21 +83,21 @@ namespace DD4hep { * * Definition of a "list" of xml elements hanging of the parent. * The list allows iterations, which can be restarted. - * Please not: Copies are not entirely free, since the - * string tag need to be replicated using strdup/free + * Please not: Copies are not entirely free, since the + * string tag need to be replicated using strdup/free * (or when using xerces the corresponding unicode routines). * * @author M.Frank * @version 1.0 */ struct NodeList { - XmlChar* m_tag; - XmlElement* m_node; + XmlChar* m_tag; + XmlElement* m_node; #ifndef __TIXML__ - XmlNodeList* m_ptr; - mutable XmlSize_t m_index; + XmlNodeList* m_ptr; + mutable XmlSize_t m_index; #else - mutable XmlElement* m_ptr; + mutable XmlElement* m_ptr; #endif /// Copy constructor @@ -109,14 +109,14 @@ namespace DD4hep { /// Reset the nodelist - e.g. restart iteration from beginning XmlElement* reset(); /// Advance to next element - XmlElement* next() const; + XmlElement* next() const; /// Go back to previous element - XmlElement* previous() const; + XmlElement* previous() const; /// Assignment operator NodeList& operator=(const NodeList& l); }; - typedef const std::string& CSTR; + typedef const std::string& CSTR; /// Dump DOM tree of a document void dumpTree(XmlDocument* doc); @@ -130,32 +130,32 @@ namespace DD4hep { /// Do-nothing version. Present for completeness and argument interchangeability std::string _toString(const std::string& s); /// Format unsigned long integer to string with atrbitrary format - std::string _toString(unsigned long i, const char* fmt="%ul"); + std::string _toString(unsigned long i, const char* fmt = "%ul"); /// Format unsigned integer (32 bits) to string with atrbitrary format - std::string _toString(unsigned int i, const char* fmt="%u"); + std::string _toString(unsigned int i, const char* fmt = "%u"); /// Format signed integer (32 bits) to string with atrbitrary format - std::string _toString(int i, const char* fmt="%d"); + std::string _toString(int i, const char* fmt = "%d"); /// Format single procision float number (32 bits) to string with atrbitrary format - std::string _toString(float d, const char* fmt="%f"); + std::string _toString(float d, const char* fmt = "%f"); /// Format double procision float number (64 bits) to string with atrbitrary format - std::string _toString(double d, const char* fmt="%f"); + std::string _toString(double d, const char* fmt = "%f"); /// Helper function to populate the evaluator dictionary - void _toDictionary(const XmlChar* name, const XmlChar* value); + void _toDictionary(const XmlChar* name, const XmlChar* value); /// Conversion function from raw unicode string to bool - bool _toBool(const XmlChar* value); + bool _toBool(const XmlChar* value); /// Conversion function from raw unicode string to int - int _toInt(const XmlChar* value); + int _toInt(const XmlChar* value); /// Conversion function from raw unicode string to long - long _toLong(const XmlChar* value); + long _toLong(const XmlChar* value); /// Conversion function from raw unicode string to float - float _toFloat(const XmlChar* value); + float _toFloat(const XmlChar* value); /// Conversion function from raw unicode string to double - double _toDouble(const XmlChar* value); + double _toDouble(const XmlChar* value); /** @class Strng_t XMLElements.h XML/XMLElements.h - * + * * Helper class to encapsulate a unicode string. * Simple conversion from ascii strings to unicode strings. * Useful when using XercesC - dummy implementation for TiXml. @@ -163,25 +163,38 @@ namespace DD4hep { * @author M.Frank * @version 1.0 */ - struct Strng_t { + struct Strng_t { /// Pointer to unicode string XmlChar* m_xml; #ifndef __TIXML__ /// Initializing constructor from unicode string - Strng_t(const XmlChar* c) { m_xml=XmlString::replicate(c); } + Strng_t(const XmlChar* c) { + m_xml = XmlString::replicate(c); + } /// Assignment opertor from unicode string Strng_t& operator=(const XmlChar* s); #endif /// Initializing constructor from ascii string - Strng_t(const char* c) { m_xml=XmlString::transcode(c); } + Strng_t(const char* c) { + m_xml = XmlString::transcode(c); + } /// Initializing constructor from STL string - Strng_t(const std::string& c) { m_xml=XmlString::transcode(c.c_str()); } + Strng_t(const std::string& c) { + m_xml = XmlString::transcode(c.c_str()); + } /// Default destructor - release unicode string - ~Strng_t() { if (m_xml) XmlString::release(&m_xml); } + ~Strng_t() { + if (m_xml) + XmlString::release(&m_xml); + } /// Auto-conversion to unicode string - operator const XmlChar*() const { return m_xml; } + operator const XmlChar*() const { + return m_xml; + } /// Accessor to unicode string - const XmlChar* ptr() const { return m_xml; } + const XmlChar* ptr() const { + return m_xml; + } /// Assignment opertor from ascii string Strng_t& operator=(const char* s); /// Assignment opertor from helper string @@ -189,58 +202,66 @@ namespace DD4hep { /// Assignment opertor from STL string Strng_t& operator=(const std::string& s); }; - + /// Unicode string concatenation of a normal ASCII string from right side - Strng_t operator+(const Strng_t& a, const char* b); + Strng_t operator+(const Strng_t& a, const char* b); /// Unicode string concatenation of a encapsulated and an STL string from right side - Strng_t operator+(const Strng_t& a, const std::string& b); + Strng_t operator+(const Strng_t& a, const std::string& b); /// Unicode string concatenation of a encapsulated and an encapsulated string from right side - Strng_t operator+(const Strng_t& a, const Strng_t& b); + Strng_t operator+(const Strng_t& a, const Strng_t& b); /// Unicode string concatenation of a normal ASCII string from left side - Strng_t operator+(const char* a, const Strng_t& b); + Strng_t operator+(const char* a, const Strng_t& b); /// Unicode string concatenation of a STL string and an encapsulated string from the left. Strng_t operator+(const std::string& a, const Strng_t& b); #ifndef __TIXML__ /// Unicode string concatenation of a encapsulated and raw unicode string from right side - Strng_t operator+(const Strng_t& a, const XmlChar* b); + Strng_t operator+(const Strng_t& a, const XmlChar* b); /// Unicode string concatenation of a encapsulated and raw unicode string from left side - Strng_t operator+(const XmlChar* a, const Strng_t& b); + Strng_t operator+(const XmlChar* a, const Strng_t& b); /// Unicode string concatenation of a raw unicode and an STL string from the right - Strng_t operator+(const XmlChar* a, const std::string& b); + Strng_t operator+(const XmlChar* a, const std::string& b); /// Unicode string concatenation of a raw unicode and an STL string from the left Strng_t operator+(const std::string& a, const XmlChar* b); #endif - /** @class Tag_t XMLElements.h XML/XMLElements.h - * - * Helper class to easily convert between + * + * Helper class to easily convert between * -- unicode * -- std::string * -- const char*. * Internally a copy representation as an std::string is kept. - * + * * @author M.Frank * @version 1.0 */ - struct Tag_t : public Strng_t { + struct Tag_t: public Strng_t { /// STL string buffer std::string m_str; /// Constructor from normal ASCII string - Tag_t(const char* s) : Strng_t(s), m_str(s) { } + Tag_t(const char* s) + : Strng_t(s), m_str(s) { + } #ifndef __TIXML__ /// Constructor from unicode string - Tag_t(const XmlChar* s) : Strng_t(s), m_str(_toString(s)) { } + Tag_t(const XmlChar* s) + : Strng_t(s), m_str(_toString(s)) { + } #endif /// Constructor from internal XML string - Tag_t(const Strng_t& s) : Strng_t(s), m_str(_toString(s)) { } + Tag_t(const Strng_t& s) + : Strng_t(s), m_str(_toString(s)) { + } /// Constructor from STL string - Tag_t(const std::string& s) : Strng_t(s), m_str(s) { } + Tag_t(const std::string& s) + : Strng_t(s), m_str(s) { + } /// Destructor - ~Tag_t() { } + ~Tag_t() { + } /// Assignment of a normal ASCII string Tag_t& operator=(const char* s); @@ -252,51 +273,67 @@ namespace DD4hep { Tag_t& operator=(const std::string& s); /// Automatic conversion to STL string - operator const std::string& () const { return m_str; } + operator const std::string&() const { + return m_str; + } /// Access writable STL string - const std::string& str() const { return m_str; } + const std::string& str() const { + return m_str; + } /// Access data buffer of STL string - const char* c_str() const { return m_str.c_str(); } + const char* c_str() const { + return m_str.c_str(); + } }; - + /// Tag/string concatenation with a normal ASCII string from right side - Tag_t operator+(const Tag_t& a, const char* b); + Tag_t operator+(const Tag_t& a, const char* b); /// Tag/string concatenation with a normal ASCII string from left side - Tag_t operator+(const char* a, const Tag_t& b); + Tag_t operator+(const char* a, const Tag_t& b); /// Tag/string concatenation with a unicode string from right side - Tag_t operator+(const Tag_t& a, const XmlChar* b); + Tag_t operator+(const Tag_t& a, const XmlChar* b); /// Tag/string concatenation with a internal Xml string from right side - Tag_t operator+(const Tag_t& a, const Strng_t& b); + Tag_t operator+(const Tag_t& a, const Strng_t& b); /// Tag/string concatenation with a STL string from right side - Tag_t operator+(const Tag_t& a, const std::string& b); + Tag_t operator+(const Tag_t& a, const std::string& b); /// Equality operator between tag object and STL string - inline bool operator==(const std::string& c, const Tag_t& b) { return c == b.m_str; } + inline bool operator==(const std::string& c, const Tag_t& b) { + return c == b.m_str; + } /** @class Handle_t XMLElements.h XML/XMLElements.h - * + * * Helper class to easily access the properties of single XmlElements. * * Note: The assignmant operator as well as the copy constructor * do not have to be implemented, they are aut-generated by the compiler! - * + * * @author M.Frank * @version 1.0 */ - struct Handle_t { + struct Handle_t { // Abbreviation for internal use - typedef XmlElement* Elt_t; + typedef XmlElement* Elt_t; /// The pointer to the XmlElement mutable Elt_t m_node; /// Initializing constructor - Handle_t(Elt_t e=0) : m_node(e) {} + Handle_t(Elt_t e = 0) + : m_node(e) { + } /// Direct access to the XmlElement using the operator-> - Elt_t operator->() const { return m_node; } + Elt_t operator->() const { + return m_node; + } /// Direct access to the XmlElement by dereferencing - operator Elt_t() const { return m_node; } + operator Elt_t() const { + return m_node; + } /// Direct access to the XmlElement by function - Elt_t ptr() const { return m_node; } + Elt_t ptr() const { + return m_node; + } /// Clone the DOMelement - with the option of a deep copy Handle_t clone(XmlDocument* new_doc) const; @@ -307,11 +344,17 @@ namespace DD4hep { /// Unicode text access to the element's value const XmlChar* rawValue() const; /// Text access to the element's tag - std::string tag() const { return _toString(rawTag()); } + std::string tag() const { + return _toString(rawTag()); + } /// Text access to the element's text - std::string text() const { return _toString(rawText()); } + std::string text() const { + return _toString(rawText()); + } /// Text access to the element's value - std::string value() const { return _toString(rawValue()); } + std::string value() const { + return _toString(rawValue()); + } /// Set the element's value void setValue(const XmlChar* text) const; /// Set the element's value @@ -321,53 +364,59 @@ namespace DD4hep { /// Set the element's text void setText(const std::string& text) const; - /*** DOM Attribute handling + /*** DOM Attribute handling */ /// Access attribute name (throws exception if not present) - const XmlChar* attr_name(const Attribute attr) const; + const XmlChar* attr_name(const Attribute attr) const; /// Access attribute value by the attribute (throws exception if not present) - const XmlChar* attr_value(const Attribute attr) const; + const XmlChar* attr_value(const Attribute attr) const; /// Access attribute value by the attribute's unicode name (throws exception if not present) - const XmlChar* attr_value(const XmlChar* attr) const; + const XmlChar* attr_value(const XmlChar* attr) const; /// Access attribute value by the attribute's unicode name (no exception thrown if not present) - const XmlChar* attr_value_nothrow(const XmlChar* attr) const; + const XmlChar* attr_value_nothrow(const XmlChar* attr) const; /// Access attribute pointer by the attribute's unicode name (throws exception if not present) - Attribute attr_ptr(const XmlChar* attr) const; + Attribute attr_ptr(const XmlChar* attr) const; /// Access attribute pointer by the attribute's unicode name (no exception thrown if not present) - Attribute attr_nothrow(const XmlChar* tag) const; + Attribute attr_nothrow(const XmlChar* tag) const; /// Check for the existence of a named attribute bool hasAttr(const XmlChar* t) const; /// Retrieve a collection of all attributes of this DOM element - std::vector<Attribute> attributes() const; + std::vector<Attribute> attributes() const; /// Access typed attribute value by the XmlAttr - template <class T> T attr(const Attribute a) const { return this->attr<T>(this->attr_name(a)); } + template <class T> T attr(const Attribute a) const { + return this->attr<T>(this->attr_name(a)); + } /// Remove all attributes of this element void removeAttrs() const; /// Set attributes as in argument handle void setAttrs(Handle_t e) const; /// Access typed attribute value by it's unicode name - template <class T> T attr(const XmlChar* name) const; + template <class T> T attr(const XmlChar* name) const; /// Generic attribute setter with unicode value Attribute setAttr(const XmlChar* t, const XmlChar* v) const; /// Generic attribute setter with XmlAttr value Attribute setAttr(const XmlChar* t, const Attribute v) const; /// Generic attribute setter with integer value - Attribute setAttr(const XmlChar* t, int val) const; + Attribute setAttr(const XmlChar* t, int val) const; /// Generic attribute setter with boolen value - Attribute setAttr(const XmlChar* t, bool val) const; + Attribute setAttr(const XmlChar* t, bool val) const; /// Generic attribute setter with floating point value - Attribute setAttr(const XmlChar* t, float val) const; + Attribute setAttr(const XmlChar* t, float val) const; /// Generic attribute setter with double precision floating point value - Attribute setAttr(const XmlChar* t, double val) const; + Attribute setAttr(const XmlChar* t, double val) const; /// Generic attribute setter with string value - Attribute setAttr(const XmlChar* t, const std::string& val) const; + Attribute setAttr(const XmlChar* t, const std::string& val) const; #ifndef __TIXML__ /// Check for the existence of a named attribute - bool hasAttr(const char* t) const { return hasAttr(Strng_t(t)); } - /// Access typed attribute value by it's name - template <class T> T attr(const char* name) const { return this->attr<T>(Strng_t(name)); } + bool hasAttr(const char* t) const { + return hasAttr(Strng_t(t)); + } + /// Access typed attribute value by it's name + template <class T> T attr(const char* name) const { + return this->attr<T>(Strng_t(name)); + } /// Generic attribute setter with text value Attribute setAttr(const XmlChar* t, const char* v) const; #endif @@ -377,80 +426,86 @@ namespace DD4hep { /// Add reference child as a new child node. The obj must have the "name" attribute! Handle_t setRef(const XmlChar* tag, const std::string& ref); - /*** DOM Element child handling + /*** DOM Element child handling */ /// Check the existence of a child with a given tag name bool hasChild(const XmlChar* tag) const; /// Access a single child by it's tag name (unicode) - Handle_t child(const XmlChar* tag, bool throw_exception=true) const; + Handle_t child(const XmlChar* tag, bool throw_exception = true) const; /// Access a group of children identified by the same tag name NodeList children(const XmlChar* tag) const; /// Access the number of children of this DOM element with a given tag name size_t numChildren(const XmlChar* tag, bool throw_exception) const; /// Remove a single child node identified by it's handle from the tree of the element - Handle_t remove(Handle_t e) const; + Handle_t remove(Handle_t e) const; /// Remove children with a given tag name from the DOM node - void removeChildren(const XmlChar* tag) const; + void removeChildren(const XmlChar* tag) const; /// Append a DOM element to the current node void append(Handle_t e) const; /// Access the element's parent element Handle_t parent() const; /// Checksum (sub-)tree of a xml document/tree. Default will pick up the adler32 checksum. - unsigned int checksum(unsigned int param,unsigned int (fcn)(unsigned int param,const XmlChar*, size_t)=0) const; + unsigned int checksum(unsigned int param, unsigned int (fcn)(unsigned int param, const XmlChar*, size_t)=0) const; }; #define INLINE inline typedef const XmlChar* cpXmlChar; - template <> INLINE Attribute Handle_t::attr<Attribute>(const XmlChar* tag) const - { return attr_ptr(tag); } + template <> INLINE Attribute Handle_t::attr<Attribute>(const XmlChar* tag) const { + return attr_ptr(tag); + } - template<> INLINE cpXmlChar Handle_t::attr<cpXmlChar>(const XmlChar* tag) const - { return attr_value(tag); } + template <> INLINE cpXmlChar Handle_t::attr<cpXmlChar>(const XmlChar* tag) const { + return attr_value(tag); + } - template<> INLINE bool Handle_t::attr<bool>(const XmlChar* tag) const - { return _toBool(attr_value(tag)); } + template <> INLINE bool Handle_t::attr<bool>(const XmlChar* tag) const { + return _toBool(attr_value(tag)); + } - template<> INLINE int Handle_t::attr<int>(const XmlChar* tag) const - { return _toInt(attr_value(tag)); } + template <> INLINE int Handle_t::attr<int>(const XmlChar* tag) const { + return _toInt(attr_value(tag)); + } - template<> INLINE float Handle_t::attr<float>(const XmlChar* tag) const - { return _toFloat(attr_value(tag)); } + template <> INLINE float Handle_t::attr<float>(const XmlChar* tag) const { + return _toFloat(attr_value(tag)); + } - template<> INLINE double Handle_t::attr<double>(const XmlChar* tag) const - { return _toDouble(attr_value(tag)); } + template <> INLINE double Handle_t::attr<double>(const XmlChar* tag) const { + return _toDouble(attr_value(tag)); + } - template<> INLINE std::string Handle_t::attr<std::string>(const XmlChar* tag) const - { return _toString(attr_value(tag)); } + template <> INLINE std::string Handle_t::attr<std::string>(const XmlChar* tag) const { + return _toString(attr_value(tag)); + } #if 0 - template<> INLINE bool Handle_t::attr<bool>(const Attribute tag) const - { return _toBool(attr_value(tag)); } + template<> INLINE bool Handle_t::attr<bool>(const Attribute tag) const + { return _toBool(attr_value(tag));} - template<> INLINE int Handle_t::attr<int>(const Attribute tag) const - { return _toInt(attr_value(tag)); } + template<> INLINE int Handle_t::attr<int>(const Attribute tag) const + { return _toInt(attr_value(tag));} - template<> INLINE float Handle_t::attr<float>(const Attribute tag) const - { return _toFloat(attr_value(tag)); } + template<> INLINE float Handle_t::attr<float>(const Attribute tag) const + { return _toFloat(attr_value(tag));} - template<> INLINE double Handle_t::attr<double>(const Attribute tag) const - { return _toDouble(attr_value(tag)); } + template<> INLINE double Handle_t::attr<double>(const Attribute tag) const + { return _toDouble(attr_value(tag));} - template<> INLINE std::string Handle_t::attr<std::string>(const Attribute tag) const - { return _toString(attr_value(tag)); } + template<> INLINE std::string Handle_t::attr<std::string>(const Attribute tag) const + { return _toString(attr_value(tag));} #endif - /** @class Collection_t XmlElements.h XML/XMLElements.h - * + * * Helper class to easily access collections of XmlNodes (or XmlElements) - * - * Typical + * + * Typical * @author M.Frank * @version 1.0 */ - struct Collection_t : public Handle_t { + struct Collection_t: public Handle_t { /// Reference to the list of child nodes - NodeList m_children; + NodeList m_children; #ifndef __TIXML__ /// Constructor over XmlElements with a given tag name Collection_t(Handle_t node, const XmlChar* tag); @@ -462,101 +517,112 @@ namespace DD4hep { /// Reset the collection object to restart the iteration Collection_t& reset(); /// Access the collection size. Avoid this call -- sloooow! - size_t size() const; + size_t size() const; /// Operator to advance the collection (pre increment) - void operator++() const; + void operator++() const; /// Operator to advance the collection (post increment) - void operator++(int) const; + void operator++(int) const; /// Operator to advance the collection (pre decrement) - void operator--() const; + void operator--() const; /// Operator to advance the collection (post decrement) - void operator--(int) const; + void operator--(int) const; /// Access to current element - Elt_t current() const { return m_node; } + Elt_t current() const { + return m_node; + } /// Helper function to throw an exception void throw_loop_exception(const std::exception& e) const; /// Loop processor using function object - template <class T> void for_each(T oper) const { - try { - for(const Collection_t& c=*this; c; ++c) - oper(*this); - } - catch(const std::exception& e) { - throw_loop_exception(e); - } + template <class T> void for_each(T oper) const { + try { + for (const Collection_t& c = *this; c; ++c) + oper(*this); + } + catch (const std::exception& e) { + throw_loop_exception(e); + } } /// Loop processor using function object - template <class T> void for_each(const XmlChar* tag_name, T oper) const { - try { - for(const Collection_t& c=*this; c; ++c) - Collection_t(c.m_node, tag_name).for_each(oper); - } - catch(const std::exception& e) { - throw_loop_exception(e); - } + template <class T> void for_each(const XmlChar* tag_name, T oper) const { + try { + for (const Collection_t& c = *this; c; ++c) + Collection_t(c.m_node, tag_name).for_each(oper); + } + catch (const std::exception& e) { + throw_loop_exception(e); + } } }; - /** @class Document XMLElements.h XML/XMLElements.h - * + * * User class encapsulating a DOM document. * Nothing special - normal handle around pointer. - * + * * @author M.Frank * @version 1.0 */ - struct Document { + struct Document { typedef XmlDocument* DOC; DOC m_doc; /// Constructor - Document(DOC d) : m_doc(d) {} + Document(DOC d) + : m_doc(d) { + } /// Auto-conversion to DOM document - operator DOC() const { return m_doc; } + operator DOC() const { + return m_doc; + } /// Accessot to DOM document behaviour using arrow operator - DOC operator->() const { return m_doc; } + DOC operator->() const { + return m_doc; + } /// Accessot to DOM document behaviour - DOC ptr() const { return m_doc; } + DOC ptr() const { + return m_doc; + } /// Access the ROOT eleemnt of the DOM document - Handle_t root() const; + Handle_t root() const; /// Create DOM element - Handle_t createElt(const XmlChar* tag) const; + Handle_t createElt(const XmlChar* tag) const; /// Clone a DOM element / sub-tree - Handle_t clone(Handle_t source) const; + Handle_t clone(Handle_t source) const; }; /** @class DocumentHolder XMLElements.h XML/XMLElements.h - * + * * User class encapsulating a DOM document. * Nothing special - normal handle around pointer. - * Contrary to the Document class, on destruction the + * Contrary to the Document class, on destruction the * XML document shall be destroyed and the corresponding * resources released. - * + * * @author M.Frank * @version 1.0 */ - struct DocumentHolder : public Document { + struct DocumentHolder: public Document { /// Constructor - DocumentHolder(DOC d) : Document(d) {} + DocumentHolder(DOC d) + : Document(d) { + } /// Standard destructor - releases the document virtual ~DocumentHolder(); }; /** @class Element XMLElements.h XML/XMLElements.h - * - * User class encapsulating a DOM element + * + * User class encapsulating a DOM element * using the Handle helper. - * This is the main class we interact with when + * This is the main class we interact with when * analysing the xml documents for constructing * sub-detectors etc. - * + * * @author M.Frank * @version 1.0 */ - struct Element { + struct Element { /// Simplification type declarations typedef Handle_t::Elt_t Elt_t; @@ -564,90 +630,136 @@ namespace DD4hep { Handle_t m_element; /// Constructor from XmlElement handle - Element(const Handle_t& e) : m_element(e) { } + Element(const Handle_t& e) + : m_element(e) { + } /// Constructor from DOM document entity Element(const Document& document, const XmlChar* type); /// Access the hosting document handle of this DOM element Document document() const; /// operator bool: check handle validity - operator bool() const { return 0 != m_element.ptr(); } + operator bool() const { + return 0 != m_element.ptr(); + } /// operator NOT: check handle validity - bool operator!() const { return 0 == m_element.ptr(); } + bool operator!() const { + return 0 == m_element.ptr(); + } /// Automatic conversion to DOM element handle - operator Handle_t () const { return m_element; } + operator Handle_t() const { + return m_element; + } /// Automatic conversion to XmlElement pointer - operator Elt_t() const { return m_element; } + operator Elt_t() const { + return m_element; + } /// Access to XmlElement pointer - Elt_t ptr() const { return m_element; } + Elt_t ptr() const { + return m_element; + } /// Access the tag name of this DOM element - std::string tag() const { return m_element.tag(); } + std::string tag() const { + return m_element.tag(); + } /// Access the tag name of this DOM element - const XmlChar* tagName() const { return m_element.rawTag(); } + const XmlChar* tagName() const { + return m_element.rawTag(); + } /// Append a new element to the existing tree - void append(Handle_t handle) const { m_element.append(handle); } + void append(Handle_t handle) const { + m_element.append(handle); + } /// Clone the DOMelement - Handle_t clone(const Document& new_doc) const { return new_doc.clone(m_element); } + Handle_t clone(const Document& new_doc) const { + return new_doc.clone(m_element); + } /// Check for the existence of a named attribute - bool hasAttr(const XmlChar* name) const { return m_element.hasAttr(name); } + bool hasAttr(const XmlChar* name) const { + return m_element.hasAttr(name); + } /// Access attribute with implicit return type conversion - template <class T> T attr(const XmlChar* tag) const { return m_element.attr<T>(tag); } + template <class T> T attr(const XmlChar* tag) const { + return m_element.attr<T>(tag); + } /// Access attribute name (throws exception if not present) - const XmlChar* attr_name(const Attribute attr) const { return m_element.attr_name(attr); } + const XmlChar* attr_name(const Attribute attr) const { + return m_element.attr_name(attr); + } /// Access attribute value by the attribute (throws exception if not present) - const XmlChar* attr_value(const Attribute attr) const { return m_element.attr_value(attr); } + const XmlChar* attr_value(const Attribute attr) const { + return m_element.attr_value(attr); + } /// Access the number of children of this DOM element with a given tag name - size_t numChildren(const XmlChar* tag,bool exc=true) const{ return m_element.numChildren(tag,exc); } + size_t numChildren(const XmlChar* tag, bool exc = true) const { + return m_element.numChildren(tag, exc); + } /// Remove own attributes and copy all attributes from handle 'e' - void setAttrs(Handle_t e) const { return m_element.setAttrs(e); } + void setAttrs(Handle_t e) const { + return m_element.setAttrs(e); + } /// Remove all attributes of this element - void removeAttrs() const { m_element.removeAttrs(); } + void removeAttrs() const { + m_element.removeAttrs(); + } /// Retrieve a collection of all attributes of this DOM element - std::vector<Attribute> attributes() const { return m_element.attributes(); } + std::vector<Attribute> attributes() const { + return m_element.attributes(); + } /// Access single attribute by it's name - Attribute getAttr(const XmlChar* name) const; + Attribute getAttr(const XmlChar* name) const; /// Set single attribute - template <class T> - Attribute setAttr(const XmlChar* nam,const T& val) const { return m_element.setAttr(nam,val); } + template <class T> + Attribute setAttr(const XmlChar* nam, const T& val) const { + return m_element.setAttr(nam, val); + } /// Set element value - template <class T> void setValue(const T& val) const { m_element.setValue(val); } + template <class T> void setValue(const T& val) const { + m_element.setValue(val); + } /// Clone the DOM element tree Handle_t clone(Handle_t h) const; /// Add a new child to the DOM node - Handle_t addChild(const XmlChar* tag) const; + Handle_t addChild(const XmlChar* tag) const; /// Check if a child with the required tag exists - if not create it and add it to the current node - Handle_t setChild(const XmlChar* tag) const; + Handle_t setChild(const XmlChar* tag) const; /// Access child by tag name. Thow an exception if required in case the child is not present - Handle_t child(const Strng_t& tag, bool except=true) const{ return m_element.child(tag,except); } + Handle_t child(const Strng_t& tag, bool except = true) const { + return m_element.child(tag, except); + } /// Remove a child node identified by its handle - Handle_t remove(Handle_t node) const { return m_element.remove(node); } + Handle_t remove(Handle_t node) const { + return m_element.remove(node); + } /// Check the existence of a child with a given tag name - bool hasChild(const XmlChar* tag) const { return m_element.hasChild(tag); } + bool hasChild(const XmlChar* tag) const { + return m_element.hasChild(tag); + } /// Set the reference attribute to the node (adds attribute ref="ref-name") - Attribute setRef(const XmlChar* tag, const XmlChar* refname) const; + Attribute setRef(const XmlChar* tag, const XmlChar* refname) const; /// Set the reference attribute to the node (adds attribute ref="ref-name") - Attribute setRef(const XmlChar* tag, const std::string& refname) const; + Attribute setRef(const XmlChar* tag, const std::string& refname) const; /// Access the value of the reference attribute of the node (attribute ref="ref-name") - const XmlChar* getRef(const XmlChar* tag) const; + const XmlChar* getRef(const XmlChar* tag) const; /// Add comment node to the element void addComment(const char* text) const; }; /** @class RefElement XMLElements.h XML/XMLElements.h - * + * * User class encapsulating a DOM element which can * be referenced. Like the Element, but the "name" - * attribute is required. The reference then has the + * attribute is required. The reference then has the * corresponding "ref" attribute. The value of "name" * and "ref" must match to establish the reference. - * + * * @author M.Frank * @version 1.0 */ - struct RefElement : public Element { + struct RefElement: public Element { /// Attribute holding thre name - Attribute m_name; + Attribute m_name; /// Construction from existing object handle RefElement(const Handle_t& e); /// Copy constructor @@ -666,5 +778,5 @@ namespace DD4hep { #undef INLINE } -} /* End namespace DD4hep */ +} /* End namespace DD4hep */ #endif /* DD4HEP_XMLELEMENTS_H */ diff --git a/DDCore/include/XML/XMLTags.h b/DDCore/include/XML/XMLTags.h index ce7e7c432..3a2d5d0d4 100644 --- a/DDCore/include/XML/XMLTags.h +++ b/DDCore/include/XML/XMLTags.h @@ -20,5 +20,4 @@ #define _U(a) DD4hep::XML::Unicode_##a #define _Unicode(a) DD4hep::XML::Strng_t(#a) - #endif // DD4hep_XML_TAGS_H diff --git a/DDCore/include/XML/config.h b/DDCore/include/XML/config.h index 598ea0e9d..01768796b 100644 --- a/DDCore/include/XML/config.h +++ b/DDCore/include/XML/config.h @@ -9,7 +9,6 @@ #ifndef DD4HEP_XML_CONFIG_H #define DD4HEP_XML_CONFIG_H - #if defined(DD4HEP_USE_TINYXML) #define __TIXML__ #endif @@ -20,19 +19,21 @@ * * @author M.Frank */ -namespace DD4hep { namespace XML { +namespace DD4hep { + namespace XML { class XmlElement; class XmlDocument; class XmlNodeList; class XmlNode; class XmlAttr; - typedef std::size_t XmlSize_t; + typedef std::size_t XmlSize_t; #ifdef __TIXML__ - typedef char XmlChar; + typedef char XmlChar; #else typedef unsigned short XmlChar; #endif -}} + } +} #ifdef __TIXML__ #define XML_IMPLEMENTATION_TYPE " TinyXML DOM mini-parser " diff --git a/DDCore/include/XML/tinyxml.h b/DDCore/include/XML/tinyxml.h index 4dc88f3b0..1b21c402f 100644 --- a/DDCore/include/XML/tinyxml.h +++ b/DDCore/include/XML/tinyxml.h @@ -1,35 +1,34 @@ /* -www.sourceforge.net/projects/tinyxml -Original code (2.0 and earlier )copyright (c) 2000-2006 Lee Thomason (www.grinninglizard.com) + www.sourceforge.net/projects/tinyxml + Original code (2.0 and earlier )copyright (c) 2000-2006 Lee Thomason (www.grinninglizard.com) -This software is provided 'as-is', without any express or implied -warranty. In no event will the authors be held liable for any -damages arising from the use of this software. + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any + damages arising from the use of this software. -Permission is granted to anyone to use this software for any -purpose, including commercial applications, and to alter it and -redistribute it freely, subject to the following restrictions: + Permission is granted to anyone to use this software for any + purpose, including commercial applications, and to alter it and + redistribute it freely, subject to the following restrictions: -1. The origin of this software must not be misrepresented; you must -not claim that you wrote the original software. If you use this -software in a product, an acknowledgment in the product documentation -would be appreciated but is not required. + 1. The origin of this software must not be misrepresented; you must + not claim that you wrote the original software. If you use this + software in a product, an acknowledgment in the product documentation + would be appreciated but is not required. -2. Altered source versions must be plainly marked as such, and -must not be misrepresented as being the original software. + 2. Altered source versions must be plainly marked as such, and + must not be misrepresented as being the original software. -3. This notice may not be removed or altered from any source -distribution. + 3. This notice may not be removed or altered from any source + distribution. -F.Gaede, DESY : added #define TIXML_USE_STL for use with marlin -*/ + F.Gaede, DESY : added #define TIXML_USE_STL for use with marlin + */ #ifndef TIXML_USE_STL #define TIXML_USE_STL #endif - #ifndef TINYXML_INCLUDED #define TINYXML_INCLUDED @@ -51,13 +50,13 @@ F.Gaede, DESY : added #define TIXML_USE_STL for use with marlin #endif #ifdef TIXML_USE_STL - #include <string> - #include <iostream> - #include <sstream> - #define TIXML_STRING std::string +#include <string> +#include <iostream> +#include <sstream> +#define TIXML_STRING std::string #else - #include "tinystr.h" - #define TIXML_STRING TiXmlString +#include "tinystr.h" +#define TIXML_STRING TiXmlString #endif // Deprecated library function hell. Compilers want to use the @@ -67,22 +66,22 @@ F.Gaede, DESY : added #define TIXML_USE_STL for use with marlin #define TIXML_SAFE #ifdef TIXML_SAFE - #if defined(_MSC_VER) && (_MSC_VER >= 1400 ) - // Microsoft visual studio, version 2005 and higher. - #define TIXML_SNPRINTF _snprintf_s - #define TIXML_SNSCANF _snscanf_s - #elif defined(_MSC_VER) && (_MSC_VER >= 1200 ) - // Microsoft visual studio, version 6 and higher. - //#pragma message( "Using _sn* functions." ) - #define TIXML_SNPRINTF _snprintf - #define TIXML_SNSCANF _snscanf - #elif defined(__GNUC__) && (__GNUC__ >= 3 ) - // GCC version 3 and higher.s - //#warning( "Using sn* functions." ) - #define TIXML_SNPRINTF snprintf - #define TIXML_SNSCANF snscanf - #endif -#endif +#if defined(_MSC_VER) && (_MSC_VER >= 1400 ) +// Microsoft visual studio, version 2005 and higher. +#define TIXML_SNPRINTF _snprintf_s +#define TIXML_SNSCANF _snscanf_s +#elif defined(_MSC_VER) && (_MSC_VER >= 1200 ) +// Microsoft visual studio, version 6 and higher. +//#pragma message( "Using _sn* functions." ) +#define TIXML_SNPRINTF _snprintf +#define TIXML_SNSCANF _snscanf +#elif defined(__GNUC__) && (__GNUC__ >= 3 ) +// GCC version 3 and higher.s +//#warning( "Using sn* functions." ) +#define TIXML_SNPRINTF snprintf +#define TIXML_SNSCANF snscanf +#endif +#endif class TiXmlDocument; class TiXmlElement; @@ -97,1713 +96,1925 @@ const int TIXML_MAJOR_VERSION = 2; const int TIXML_MINOR_VERSION = 5; const int TIXML_PATCH_VERSION = 2; -/* Internal structure for tracking location of items - in the XML file. -*/ -struct TiXmlCursor -{ - TiXmlCursor() { Clear(); } - void Clear() { row = col = -1; } - - int row; // 0 based. - int col; // 0 based. +/* Internal structure for tracking location of items + in the XML file. + */ +struct TiXmlCursor { + TiXmlCursor() { + Clear(); + } + void Clear() { + row = col = -1; + } + + int row; // 0 based. + int col; // 0 based. }; - /** - If you call the Accept() method, it requires being passed a TiXmlVisitor - class to handle callbacks. For nodes that contain other nodes (Document, Element) - you will get called with a VisitEnter/VisitExit pair. Nodes that are always leaves - are simple called with Visit(). + If you call the Accept() method, it requires being passed a TiXmlVisitor + class to handle callbacks. For nodes that contain other nodes (Document, Element) + you will get called with a VisitEnter/VisitExit pair. Nodes that are always leaves + are simple called with Visit(). - If you return 'true' from a Visit method, recursive parsing will continue. If you return - false, <b>no children of this node or its sibilings</b> will be Visited. + If you return 'true' from a Visit method, recursive parsing will continue. If you return + false, <b>no children of this node or its sibilings</b> will be Visited. - All flavors of Visit methods have a default implementation that returns 'true' (continue - visiting). You need to only override methods that are interesting to you. + All flavors of Visit methods have a default implementation that returns 'true' (continue + visiting). You need to only override methods that are interesting to you. - Generally Accept() is called on the TiXmlDocument, although all nodes suppert Visiting. + Generally Accept() is called on the TiXmlDocument, although all nodes suppert Visiting. - You should never change the document from a callback. + You should never change the document from a callback. - @sa TiXmlNode::Accept() -*/ -class TiXmlVisitor -{ + @sa TiXmlNode::Accept() + */ +class TiXmlVisitor { public: - virtual ~TiXmlVisitor() {} - - /// Visit a document. - virtual bool VisitEnter( const TiXmlDocument& /* doc */) { return true; } - /// Visit a document. - virtual bool VisitExit( const TiXmlDocument& /* doc */) { return true; } - - /// Visit an element. - virtual bool VisitEnter( const TiXmlElement& /* element */, const TiXmlAttribute* /* firstAttribute */ ) { return true; } - /// Visit an element. - virtual bool VisitExit( const TiXmlElement& /* element */ ) { return true; } - - /// Visit a declaration - virtual bool Visit( const TiXmlDeclaration& /* declaration */ ) { return true; } - /// Visit a text node - virtual bool Visit( const TiXmlText& /* text */ ) { return true; } - /// Visit a comment node - virtual bool Visit( const TiXmlComment& /* comment */ ) { return true; } - /// Visit an unknow node - virtual bool Visit( const TiXmlUnknown& /* unknown */ ) { return true; } + virtual ~TiXmlVisitor() { + } + + /// Visit a document. + virtual bool VisitEnter(const TiXmlDocument& /* doc */) { + return true; + } + /// Visit a document. + virtual bool VisitExit(const TiXmlDocument& /* doc */) { + return true; + } + + /// Visit an element. + virtual bool VisitEnter(const TiXmlElement& /* element */, const TiXmlAttribute* /* firstAttribute */) { + return true; + } + /// Visit an element. + virtual bool VisitExit(const TiXmlElement& /* element */) { + return true; + } + + /// Visit a declaration + virtual bool Visit(const TiXmlDeclaration& /* declaration */) { + return true; + } + /// Visit a text node + virtual bool Visit(const TiXmlText& /* text */) { + return true; + } + /// Visit a comment node + virtual bool Visit(const TiXmlComment& /* comment */) { + return true; + } + /// Visit an unknow node + virtual bool Visit(const TiXmlUnknown& /* unknown */) { + return true; + } }; // Only used by Attribute::Query functions -enum -{ - TIXML_SUCCESS, - TIXML_NO_ATTRIBUTE, - TIXML_WRONG_TYPE +enum { + TIXML_SUCCESS, TIXML_NO_ATTRIBUTE, TIXML_WRONG_TYPE }; - // Used by the parsing routines. -enum TiXmlEncoding -{ - TIXML_ENCODING_UNKNOWN, - TIXML_ENCODING_UTF8, - TIXML_ENCODING_LEGACY +enum TiXmlEncoding { + TIXML_ENCODING_UNKNOWN, TIXML_ENCODING_UTF8, TIXML_ENCODING_LEGACY }; const TiXmlEncoding TIXML_DEFAULT_ENCODING = TIXML_ENCODING_UNKNOWN; /** TiXmlBase is a base class for every class in TinyXml. - It does little except to establish that TinyXml classes - can be printed and provide some utility functions. - - In XML, the document and elements can contain - other elements and other types of nodes. - - @verbatim - A Document can contain: Element (container or leaf) - Comment (leaf) - Unknown (leaf) - Declaration( leaf ) - - An Element can contain: Element (container or leaf) - Text (leaf) - Attributes (not on tree) - Comment (leaf) - Unknown (leaf) - - A Decleration contains: Attributes (not on tree) - @endverbatim -*/ -class TiXmlBase -{ - friend class TiXmlNode; - friend class TiXmlElement; - friend class TiXmlDocument; + It does little except to establish that TinyXml classes + can be printed and provide some utility functions. + + In XML, the document and elements can contain + other elements and other types of nodes. + + @verbatim + A Document can contain: Element (container or leaf) + Comment (leaf) + Unknown (leaf) + Declaration( leaf ) + + An Element can contain: Element (container or leaf) + Text (leaf) + Attributes (not on tree) + Comment (leaf) + Unknown (leaf) + + A Decleration contains: Attributes (not on tree) + @endverbatim + */ +class TiXmlBase { + friend class TiXmlNode; + friend class TiXmlElement; + friend class TiXmlDocument; public: - TiXmlBase() : userData(0) {} - virtual ~TiXmlBase() {} - - /** All TinyXml classes can print themselves to a filestream - or the string class (TiXmlString in non-STL mode, std::string - in STL mode.) Either or both cfile and str can be null. - - This is a formatted print, and will insert - tabs and newlines. - - (For an unformatted stream, use the << operator.) - */ - virtual void Print( FILE* cfile, int depth ) const = 0; - - /** The world does not agree on whether white space should be kept or - not. In order to make everyone happy, these global, static functions - are provided to set whether or not TinyXml will condense all white space - into a single space or not. The default is to condense. Note changing this - value is not thread safe. - */ - static void SetCondenseWhiteSpace( bool condense ) { condenseWhiteSpace = condense; } - - /// Return the current white space setting. - static bool IsWhiteSpaceCondensed() { return condenseWhiteSpace; } - - /** Return the position, in the original source file, of this node or attribute. - The row and column are 1-based. (That is the first row and first column is - 1,1). If the returns values are 0 or less, then the parser does not have - a row and column value. - - Generally, the row and column value will be set when the TiXmlDocument::Load(), - TiXmlDocument::LoadFile(), or any TiXmlNode::Parse() is called. It will NOT be set - when the DOM was created from operator>>. - - The values reflect the initial load. Once the DOM is modified programmatically - (by adding or changing nodes and attributes) the new values will NOT update to - reflect changes in the document. - - There is a minor performance cost to computing the row and column. Computation - can be disabled if TiXmlDocument::SetTabSize() is called with 0 as the value. - - @sa TiXmlDocument::SetTabSize() - */ - int Row() const { return location.row + 1; } - int Column() const { return location.col + 1; } ///< See Row() - - void SetUserData( void* user ) { userData = user; } ///< Set a pointer to arbitrary user data. - void* GetUserData() { return userData; } ///< Get a pointer to arbitrary user data. - const void* GetUserData() const { return userData; } ///< Get a pointer to arbitrary user data. - - // Table that returs, for a given lead byte, the total number of bytes - // in the UTF-8 sequence. - static const int utf8ByteTable[256]; - - virtual const char* Parse( const char* p, - TiXmlParsingData* data, - TiXmlEncoding encoding /*= TIXML_ENCODING_UNKNOWN */ ) = 0; - - enum - { - TIXML_NO_ERROR = 0, - TIXML_ERROR, - TIXML_ERROR_OPENING_FILE, - TIXML_ERROR_OUT_OF_MEMORY, - TIXML_ERROR_PARSING_ELEMENT, - TIXML_ERROR_FAILED_TO_READ_ELEMENT_NAME, - TIXML_ERROR_READING_ELEMENT_VALUE, - TIXML_ERROR_READING_ATTRIBUTES, - TIXML_ERROR_PARSING_EMPTY, - TIXML_ERROR_READING_END_TAG, - TIXML_ERROR_PARSING_UNKNOWN, - TIXML_ERROR_PARSING_COMMENT, - TIXML_ERROR_PARSING_DECLARATION, - TIXML_ERROR_DOCUMENT_EMPTY, - TIXML_ERROR_EMBEDDED_NULL, - TIXML_ERROR_PARSING_CDATA, - TIXML_ERROR_DOCUMENT_TOP_ONLY, - - TIXML_ERROR_STRING_COUNT - }; + TiXmlBase() + : userData(0) { + } + virtual ~TiXmlBase() { + } + + /** All TinyXml classes can print themselves to a filestream + or the string class (TiXmlString in non-STL mode, std::string + in STL mode.) Either or both cfile and str can be null. + + This is a formatted print, and will insert + tabs and newlines. + + (For an unformatted stream, use the << operator.) + */ + virtual void Print(FILE* cfile, int depth) const = 0; + + /** The world does not agree on whether white space should be kept or + not. In order to make everyone happy, these global, static functions + are provided to set whether or not TinyXml will condense all white space + into a single space or not. The default is to condense. Note changing this + value is not thread safe. + */ + static void SetCondenseWhiteSpace(bool condense) { + condenseWhiteSpace = condense; + } + + /// Return the current white space setting. + static bool IsWhiteSpaceCondensed() { + return condenseWhiteSpace; + } + + /** Return the position, in the original source file, of this node or attribute. + The row and column are 1-based. (That is the first row and first column is + 1,1). If the returns values are 0 or less, then the parser does not have + a row and column value. + + Generally, the row and column value will be set when the TiXmlDocument::Load(), + TiXmlDocument::LoadFile(), or any TiXmlNode::Parse() is called. It will NOT be set + when the DOM was created from operator>>. + + The values reflect the initial load. Once the DOM is modified programmatically + (by adding or changing nodes and attributes) the new values will NOT update to + reflect changes in the document. + + There is a minor performance cost to computing the row and column. Computation + can be disabled if TiXmlDocument::SetTabSize() is called with 0 as the value. + + @sa TiXmlDocument::SetTabSize() + */ + int Row() const { + return location.row + 1; + } + int Column() const { + return location.col + 1; + } ///< See Row() + + void SetUserData(void* user) { + userData = user; + } ///< Set a pointer to arbitrary user data. + void* GetUserData() { + return userData; + } ///< Get a pointer to arbitrary user data. + const void* GetUserData() const { + return userData; + } ///< Get a pointer to arbitrary user data. + + // Table that returs, for a given lead byte, the total number of bytes + // in the UTF-8 sequence. + static const int utf8ByteTable[256]; + + virtual const char* Parse(const char* p, TiXmlParsingData* data, TiXmlEncoding encoding /*= TIXML_ENCODING_UNKNOWN */) = 0; + + enum { + TIXML_NO_ERROR = 0, + TIXML_ERROR, + TIXML_ERROR_OPENING_FILE, + TIXML_ERROR_OUT_OF_MEMORY, + TIXML_ERROR_PARSING_ELEMENT, + TIXML_ERROR_FAILED_TO_READ_ELEMENT_NAME, + TIXML_ERROR_READING_ELEMENT_VALUE, + TIXML_ERROR_READING_ATTRIBUTES, + TIXML_ERROR_PARSING_EMPTY, + TIXML_ERROR_READING_END_TAG, + TIXML_ERROR_PARSING_UNKNOWN, + TIXML_ERROR_PARSING_COMMENT, + TIXML_ERROR_PARSING_DECLARATION, + TIXML_ERROR_DOCUMENT_EMPTY, + TIXML_ERROR_EMBEDDED_NULL, + TIXML_ERROR_PARSING_CDATA, + TIXML_ERROR_DOCUMENT_TOP_ONLY, + + TIXML_ERROR_STRING_COUNT + }; protected: - static const char* SkipWhiteSpace( const char*, TiXmlEncoding encoding ); - inline static bool IsWhiteSpace( char c ) - { - return ( isspace( (unsigned char) c ) || c == '\n' || c == '\r' ); - } - inline static bool IsWhiteSpace( int c ) - { - if ( c < 256 ) - return IsWhiteSpace( (char) c ); - return false; // Again, only truly correct for English/Latin...but usually works. - } - - #ifdef TIXML_USE_STL - static bool StreamWhiteSpace( std::istream * in, TIXML_STRING * tag ); - static bool StreamTo( std::istream * in, int character, TIXML_STRING * tag ); - #endif - - /* Reads an XML name into the string provided. Returns - a pointer just past the last character of the name, - or 0 if the function has an error. - */ - static const char* ReadName( const char* p, TIXML_STRING* name, TiXmlEncoding encoding ); - - /* Reads text. Returns a pointer past the given end tag. - Wickedly complex options, but it keeps the (sensitive) code in one place. - */ - static const char* ReadText( const char* in, // where to start - TIXML_STRING* text, // the string read - bool ignoreWhiteSpace, // whether to keep the white space - const char* endTag, // what ends this text - bool ignoreCase, // whether to ignore case in the end tag - TiXmlEncoding encoding ); // the current encoding - - // If an entity has been found, transform it into a character. - static const char* GetEntity( const char* in, char* value, int* length, TiXmlEncoding encoding ); - - // Get a character, while interpreting entities. - // The length can be from 0 to 4 bytes. - inline static const char* GetChar( const char* p, char* _value, int* length, TiXmlEncoding encoding ) - { - assert( p ); - if ( encoding == TIXML_ENCODING_UTF8 ) - { - *length = utf8ByteTable[ *((const unsigned char*)p) ]; - assert( *length >= 0 && *length < 5 ); - } - else - { - *length = 1; - } - - if ( *length == 1 ) - { - if ( *p == '&' ) - return GetEntity( p, _value, length, encoding ); - *_value = *p; - return p+1; - } - else if ( *length ) - { - //strncpy( _value, p, *length ); // lots of compilers don't like this function (unsafe), - // and the null terminator isn't needed - for( int i=0; p[i] && i<*length; ++i ) { - _value[i] = p[i]; - } - return p + (*length); - } - else - { - // Not valid text. - return 0; - } - } - - // Puts a string to a stream, expanding entities as it goes. - // Note this should not contian the '<', '>', etc, or they will be transformed into entities! - static void PutString( const TIXML_STRING& str, TIXML_STRING* out ); - - // Return true if the next characters in the stream are any of the endTag sequences. - // Ignore case only works for english, and should only be relied on when comparing - // to English words: StringEqual( p, "version", true ) is fine. - static bool StringEqual( const char* p, - const char* endTag, - bool ignoreCase, - TiXmlEncoding encoding ); - - static const char* errorString[ TIXML_ERROR_STRING_COUNT ]; - - TiXmlCursor location; - - /// Field containing a generic user pointer - void* userData; - - // None of these methods are reliable for any language except English. - // Good for approximation, not great for accuracy. - static int IsAlpha( unsigned char anyByte, TiXmlEncoding encoding ); - static int IsAlphaNum( unsigned char anyByte, TiXmlEncoding encoding ); - inline static int ToLower( int v, TiXmlEncoding encoding ) - { - if ( encoding == TIXML_ENCODING_UTF8 ) - { - if ( v < 128 ) return tolower( v ); - return v; - } - else - { - return tolower( v ); - } - } - static void ConvertUTF32ToUTF8( unsigned long input, char* output, int* length ); + static const char* SkipWhiteSpace(const char*, TiXmlEncoding encoding); + inline static bool IsWhiteSpace(char c) { + return (isspace((unsigned char) c) || c == '\n' || c == '\r'); + } + inline static bool IsWhiteSpace(int c) { + if (c < 256) + return IsWhiteSpace((char) c); + return false; // Again, only truly correct for English/Latin...but usually works. + } + +#ifdef TIXML_USE_STL + static bool StreamWhiteSpace(std::istream * in, TIXML_STRING * tag); + static bool StreamTo(std::istream * in, int character, TIXML_STRING * tag); +#endif + + /* Reads an XML name into the string provided. Returns + a pointer just past the last character of the name, + or 0 if the function has an error. + */ + static const char* ReadName(const char* p, TIXML_STRING* name, TiXmlEncoding encoding); + + /* Reads text. Returns a pointer past the given end tag. + Wickedly complex options, but it keeps the (sensitive) code in one place. + */ + static const char* ReadText(const char* in, // where to start + TIXML_STRING* text, // the string read + bool ignoreWhiteSpace, // whether to keep the white space + const char* endTag, // what ends this text + bool ignoreCase, // whether to ignore case in the end tag + TiXmlEncoding encoding); // the current encoding + + // If an entity has been found, transform it into a character. + static const char* GetEntity(const char* in, char* value, int* length, TiXmlEncoding encoding); + + // Get a character, while interpreting entities. + // The length can be from 0 to 4 bytes. + inline static const char* GetChar(const char* p, char* _value, int* length, TiXmlEncoding encoding) { + assert( p); + if (encoding == TIXML_ENCODING_UTF8) { + *length = utf8ByteTable[*((const unsigned char*) p)]; + assert( *length >= 0 && *length < 5); + } + else { + *length = 1; + } + + if (*length == 1) { + if (*p == '&') + return GetEntity(p, _value, length, encoding); + *_value = *p; + return p + 1; + } + else if (*length) { + //strncpy( _value, p, *length ); // lots of compilers don't like this function (unsafe), + // and the null terminator isn't needed + for (int i = 0; p[i] && i < *length; ++i) { + _value[i] = p[i]; + } + return p + (*length); + } + else { + // Not valid text. + return 0; + } + } + + // Puts a string to a stream, expanding entities as it goes. + // Note this should not contian the '<', '>', etc, or they will be transformed into entities! + static void PutString(const TIXML_STRING& str, TIXML_STRING* out); + + // Return true if the next characters in the stream are any of the endTag sequences. + // Ignore case only works for english, and should only be relied on when comparing + // to English words: StringEqual( p, "version", true ) is fine. + static bool StringEqual(const char* p, const char* endTag, bool ignoreCase, TiXmlEncoding encoding); + + static const char* errorString[TIXML_ERROR_STRING_COUNT]; + + TiXmlCursor location; + + /// Field containing a generic user pointer + void* userData; + + // None of these methods are reliable for any language except English. + // Good for approximation, not great for accuracy. + static int IsAlpha(unsigned char anyByte, TiXmlEncoding encoding); + static int IsAlphaNum(unsigned char anyByte, TiXmlEncoding encoding); + inline static int ToLower(int v, TiXmlEncoding encoding) { + if (encoding == TIXML_ENCODING_UTF8) { + if (v < 128) + return tolower(v); + return v; + } + else { + return tolower(v); + } + } + static void ConvertUTF32ToUTF8(unsigned long input, char* output, int* length); private: - TiXmlBase( const TiXmlBase& ); // not implemented. - void operator=( const TiXmlBase& base ); // not allowed. - - struct Entity - { - const char* str; - unsigned int strLength; - char chr; - }; - enum - { - NUM_ENTITY = 5, - MAX_ENTITY_LENGTH = 6 - - }; - static Entity entity[ NUM_ENTITY ]; - static bool condenseWhiteSpace; + TiXmlBase(const TiXmlBase&); // not implemented. + void operator=(const TiXmlBase& base); // not allowed. + + struct Entity { + const char* str; + unsigned int strLength; + char chr; + }; + enum { + NUM_ENTITY = 5, MAX_ENTITY_LENGTH = 6 + + }; + static Entity entity[NUM_ENTITY]; + static bool condenseWhiteSpace; }; - /** The parent class for everything in the Document Object Model. - (Except for attributes). - Nodes have siblings, a parent, and children. A node can be - in a document, or stand on its own. The type of a TiXmlNode - can be queried, and it can be cast to its more defined type. -*/ -class TiXmlNode : public TiXmlBase -{ - friend class TiXmlDocument; - friend class TiXmlElement; + (Except for attributes). + Nodes have siblings, a parent, and children. A node can be + in a document, or stand on its own. The type of a TiXmlNode + can be queried, and it can be cast to its more defined type. + */ +class TiXmlNode: public TiXmlBase { + friend class TiXmlDocument; + friend class TiXmlElement; public: - #ifdef TIXML_USE_STL - - /** An input stream operator, for every class. Tolerant of newlines and - formatting, but doesn't expect them. - */ - friend std::istream& operator >> (std::istream& in, TiXmlNode& base); - - /** An output stream operator, for every class. Note that this outputs - without any newlines or formatting, as opposed to Print(), which - includes tabs and new lines. - - The operator<< and operator>> are not completely symmetric. Writing - a node to a stream is very well defined. You'll get a nice stream - of output, without any extra whitespace or newlines. - - But reading is not as well defined. (As it always is.) If you create - a TiXmlElement (for example) and read that from an input stream, - the text needs to define an element or junk will result. This is - true of all input streams, but it's worth keeping in mind. - - A TiXmlDocument will read nodes until it reads a root element, and - all the children of that root element. - */ - friend std::ostream& operator<< (std::ostream& out, const TiXmlNode& base); - - /// Appends the XML node or attribute to a std::string. - friend std::string& operator<< (std::string& out, const TiXmlNode& base ); - - #endif - - /** The types of XML nodes supported by TinyXml. (All the - unsupported types are picked up by UNKNOWN.) - */ - enum NodeType - { - DOCUMENT, - ELEMENT, - COMMENT, - UNKNOWN, - TEXT, - DECLARATION, - TYPECOUNT - }; - - virtual ~TiXmlNode(); - - /** The meaning of 'value' changes for the specific type of - TiXmlNode. - @verbatim - Document: filename of the xml file - Element: name of the element - Comment: the comment text - Unknown: the tag contents - Text: the text string - @endverbatim - - The subclasses will wrap this function. - */ - const char *Value() const { return value.c_str (); } - - #ifdef TIXML_USE_STL - /** Return Value() as a std::string. If you only use STL, - this is more efficient than calling Value(). - Only available in STL mode. - */ - const std::string& ValueStr() const { return value; } - #endif - - /** Changes the value of the node. Defined as: - @verbatim - Document: filename of the xml file - Element: name of the element - Comment: the comment text - Unknown: the tag contents - Text: the text string - @endverbatim - */ - void SetValue(const char * _value) { value = _value;} - - #ifdef TIXML_USE_STL - /// STL std::string form. - void SetValue( const std::string& _value ) { value = _value; } - #endif - - /// Delete all the children of this node. Does not affect 'this'. - void Clear(); - - /// One step up the DOM. - TiXmlNode* Parent() { return parent; } - const TiXmlNode* Parent() const { return parent; } - - const TiXmlNode* FirstChild() const { return firstChild; } ///< The first child of this node. Will be null if there are no children. - TiXmlNode* FirstChild() { return firstChild; } - const TiXmlNode* FirstChild( const char * value ) const; ///< The first child of this node with the matching 'value'. Will be null if none found. - /// The first child of this node with the matching 'value'. Will be null if none found. - TiXmlNode* FirstChild( const char * _value ) { - // Call through to the const version - safe since nothing is changed. Exiting syntax: cast this to a const (always safe) - // call the method, cast the return back to non-const. - return const_cast< TiXmlNode* > ((const_cast< const TiXmlNode* >(this))->FirstChild( _value )); - } - const TiXmlNode* LastChild() const { return lastChild; } /// The last child of this node. Will be null if there are no children. - TiXmlNode* LastChild() { return lastChild; } - - const TiXmlNode* LastChild( const char * value ) const; /// The last child of this node matching 'value'. Will be null if there are no children. - TiXmlNode* LastChild( const char * _value ) { - return const_cast< TiXmlNode* > ((const_cast< const TiXmlNode* >(this))->LastChild( _value )); - } - - #ifdef TIXML_USE_STL - const TiXmlNode* FirstChild( const std::string& _value ) const { return FirstChild (_value.c_str ()); } ///< STL std::string form. - TiXmlNode* FirstChild( const std::string& _value ) { return FirstChild (_value.c_str ()); } ///< STL std::string form. - const TiXmlNode* LastChild( const std::string& _value ) const { return LastChild (_value.c_str ()); } ///< STL std::string form. - TiXmlNode* LastChild( const std::string& _value ) { return LastChild (_value.c_str ()); } ///< STL std::string form. - #endif - - /** An alternate way to walk the children of a node. - One way to iterate over nodes is: - @verbatim - for( child = parent->FirstChild(); child; child = child->NextSibling() ) - @endverbatim - - IterateChildren does the same thing with the syntax: - @verbatim - child = 0; - while( child = parent->IterateChildren( child ) ) - @endverbatim - - IterateChildren takes the previous child as input and finds - the next one. If the previous child is null, it returns the - first. IterateChildren will return null when done. - */ - const TiXmlNode* IterateChildren( const TiXmlNode* previous ) const; - TiXmlNode* IterateChildren( const TiXmlNode* previous ) { - return const_cast< TiXmlNode* >( (const_cast< const TiXmlNode* >(this))->IterateChildren( previous ) ); - } - - /// This flavor of IterateChildren searches for children with a particular 'value' - const TiXmlNode* IterateChildren( const char * value, const TiXmlNode* previous ) const; - TiXmlNode* IterateChildren( const char * _value, const TiXmlNode* previous ) { - return const_cast< TiXmlNode* >( (const_cast< const TiXmlNode* >(this))->IterateChildren( _value, previous ) ); - } - - #ifdef TIXML_USE_STL - const TiXmlNode* IterateChildren( const std::string& _value, const TiXmlNode* previous ) const { return IterateChildren (_value.c_str (), previous); } ///< STL std::string form. - TiXmlNode* IterateChildren( const std::string& _value, const TiXmlNode* previous ) { return IterateChildren (_value.c_str (), previous); } ///< STL std::string form. - #endif - - /** Add a new node related to this. Adds a child past the LastChild. - Returns a pointer to the new object or NULL if an error occured. - */ - TiXmlNode* InsertEndChild( const TiXmlNode& addThis ); - - - /** Add a new node related to this. Adds a child past the LastChild. - - NOTE: the node to be added is passed by pointer, and will be - henceforth owned (and deleted) by tinyXml. This method is efficient - and avoids an extra copy, but should be used with care as it - uses a different memory model than the other insert functions. - - @sa InsertEndChild - */ - TiXmlNode* LinkEndChild( TiXmlNode* addThis ); - - /** Add a new node related to this. Adds a child before the specified child. - Returns a pointer to the new object or NULL if an error occured. - */ - TiXmlNode* InsertBeforeChild( TiXmlNode* beforeThis, const TiXmlNode& addThis ); - - /** Add a new node related to this. Adds a child after the specified child. - Returns a pointer to the new object or NULL if an error occured. - */ - TiXmlNode* InsertAfterChild( TiXmlNode* afterThis, const TiXmlNode& addThis ); - - /** Replace a child of this node. - Returns a pointer to the new object or NULL if an error occured. - */ - TiXmlNode* ReplaceChild( TiXmlNode* replaceThis, const TiXmlNode& withThis ); - - /// Delete a child of this node. - bool RemoveChild( TiXmlNode* removeThis ); - - /// Navigate to a sibling node. - const TiXmlNode* PreviousSibling() const { return prev; } - TiXmlNode* PreviousSibling() { return prev; } - - /// Navigate to a sibling node. - const TiXmlNode* PreviousSibling( const char * ) const; - TiXmlNode* PreviousSibling( const char *_prev ) { - return const_cast< TiXmlNode* >( (const_cast< const TiXmlNode* >(this))->PreviousSibling( _prev ) ); - } - - #ifdef TIXML_USE_STL - const TiXmlNode* PreviousSibling( const std::string& _value ) const { return PreviousSibling (_value.c_str ()); } ///< STL std::string form. - TiXmlNode* PreviousSibling( const std::string& _value ) { return PreviousSibling (_value.c_str ()); } ///< STL std::string form. - const TiXmlNode* NextSibling( const std::string& _value) const { return NextSibling (_value.c_str ()); } ///< STL std::string form. - TiXmlNode* NextSibling( const std::string& _value) { return NextSibling (_value.c_str ()); } ///< STL std::string form. - #endif - - /// Navigate to a sibling node. - const TiXmlNode* NextSibling() const { return next; } - TiXmlNode* NextSibling() { return next; } - - /// Navigate to a sibling node with the given 'value'. - const TiXmlNode* NextSibling( const char * ) const; - TiXmlNode* NextSibling( const char* _next ) { - return const_cast< TiXmlNode* >( (const_cast< const TiXmlNode* >(this))->NextSibling( _next ) ); - } - - /** Convenience function to get through elements. - Calls NextSibling and ToElement. Will skip all non-Element - nodes. Returns 0 if there is not another element. - */ - const TiXmlElement* NextSiblingElement() const; - TiXmlElement* NextSiblingElement() { - return const_cast< TiXmlElement* >( (const_cast< const TiXmlNode* >(this))->NextSiblingElement() ); - } - - /** Convenience function to get through elements. - Calls NextSibling and ToElement. Will skip all non-Element - nodes. Returns 0 if there is not another element. - */ - const TiXmlElement* NextSiblingElement( const char * ) const; - TiXmlElement* NextSiblingElement( const char *_next ) { - return const_cast< TiXmlElement* >( (const_cast< const TiXmlNode* >(this))->NextSiblingElement( _next ) ); - } - - /** Convenience function to get through elements. - Calls PreviousSibling and ToElement. Will skip all non-Element - nodes. Returns 0 if there is not another element. - */ - const TiXmlElement* PreviousSiblingElement() const; - TiXmlElement* PreviousSiblingElement() { - return const_cast< TiXmlElement* >( (const_cast< const TiXmlNode* >(this))->PreviousSiblingElement() ); - } - - /** Convenience function to get through elements. - Calls PreviousSibling and ToElement. Will skip all non-Element - nodes. Returns 0 if there is not another element. - */ - const TiXmlElement* PreviousSiblingElement( const char * ) const; - TiXmlElement* PreviousSiblingElement( const char *_next ) { - return const_cast< TiXmlElement* >( (const_cast< const TiXmlNode* >(this))->PreviousSiblingElement( _next ) ); - } - - #ifdef TIXML_USE_STL - const TiXmlElement* NextSiblingElement( const std::string& _value) const { return NextSiblingElement (_value.c_str ()); } ///< STL std::string form. - TiXmlElement* NextSiblingElement( const std::string& _value) { return NextSiblingElement (_value.c_str ()); } ///< STL std::string form. - #endif - - /// Convenience function to get through elements. - const TiXmlElement* FirstChildElement() const; - TiXmlElement* FirstChildElement() { - return const_cast< TiXmlElement* >( (const_cast< const TiXmlNode* >(this))->FirstChildElement() ); - } - - /// Convenience function to get through elements. - const TiXmlElement* FirstChildElement( const char * _value ) const; - TiXmlElement* FirstChildElement( const char * _value ) { - return const_cast< TiXmlElement* >( (const_cast< const TiXmlNode* >(this))->FirstChildElement( _value ) ); - } - - #ifdef TIXML_USE_STL - const TiXmlElement* FirstChildElement( const std::string& _value ) const { return FirstChildElement (_value.c_str ()); } ///< STL std::string form. - TiXmlElement* FirstChildElement( const std::string& _value ) { return FirstChildElement (_value.c_str ()); } ///< STL std::string form. - #endif - - /** Query the type (as an enumerated value, above) of this node. - The possible types are: DOCUMENT, ELEMENT, COMMENT, - UNKNOWN, TEXT, and DECLARATION. - */ - int Type() const { return type; } - - /** Return a pointer to the Document this node lives in. - Returns null if not in a document. - */ - const TiXmlDocument* GetDocument() const; - TiXmlDocument* GetDocument() { - return const_cast< TiXmlDocument* >( (const_cast< const TiXmlNode* >(this))->GetDocument() ); - } - - /// Returns true if this node has no children. - bool NoChildren() const { return !firstChild; } - - virtual const TiXmlDocument* ToDocument() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. - virtual const TiXmlElement* ToElement() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. - virtual const TiXmlComment* ToComment() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. - virtual const TiXmlUnknown* ToUnknown() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. - virtual const TiXmlText* ToText() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. - virtual const TiXmlDeclaration* ToDeclaration() const { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. - - virtual TiXmlDocument* ToDocument() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. - virtual TiXmlElement* ToElement() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. - virtual TiXmlComment* ToComment() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. - virtual TiXmlUnknown* ToUnknown() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. - virtual TiXmlText* ToText() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. - virtual TiXmlDeclaration* ToDeclaration() { return 0; } ///< Cast to a more defined type. Will return null if not of the requested type. - - /** Create an exact duplicate of this node and return it. The memory must be deleted - by the caller. - */ - virtual TiXmlNode* Clone() const = 0; - - /** Accept a hierchical visit the nodes in the TinyXML DOM. Every node in the - XML tree will be conditionally visited and the host will be called back - via the TiXmlVisitor interface. - - This is essentially a SAX interface for TinyXML. (Note however it doesn't re-parse - the XML for the callbacks, so the performance of TinyXML is unchanged by using this - interface versus any other.) - - The interface has been based on ideas from: - - - http://www.saxproject.org/ - - http://c2.com/cgi/wiki?HierarchicalVisitorPattern - - Which are both good references for "visiting". - - An example of using Accept(): - @verbatim - TiXmlPrinter printer; - tinyxmlDoc.Accept( &printer ); - const char* xmlcstr = printer.CStr(); - @endverbatim - */ - virtual bool Accept( TiXmlVisitor* visitor ) const = 0; +#ifdef TIXML_USE_STL -protected: - TiXmlNode( NodeType _type ); + /** An input stream operator, for every class. Tolerant of newlines and + formatting, but doesn't expect them. + */ + friend std::istream& operator >>(std::istream& in, TiXmlNode& base); - // Copy to the allocated object. Shared functionality between Clone, Copy constructor, - // and the assignment operator. - void CopyTo( TiXmlNode* target ) const; + /** An output stream operator, for every class. Note that this outputs + without any newlines or formatting, as opposed to Print(), which + includes tabs and new lines. - #ifdef TIXML_USE_STL - // The real work of the input operator. - virtual void StreamIn( std::istream* in, TIXML_STRING* tag ) = 0; - #endif + The operator<< and operator>> are not completely symmetric. Writing + a node to a stream is very well defined. You'll get a nice stream + of output, without any extra whitespace or newlines. - // Figure out what is at *p, and parse it. Returns null if it is not an xml node. - TiXmlNode* Identify( const char* start, TiXmlEncoding encoding ); + But reading is not as well defined. (As it always is.) If you create + a TiXmlElement (for example) and read that from an input stream, + the text needs to define an element or junk will result. This is + true of all input streams, but it's worth keeping in mind. - TiXmlNode* parent; - NodeType type; + A TiXmlDocument will read nodes until it reads a root element, and + all the children of that root element. + */ + friend std::ostream& operator<<(std::ostream& out, const TiXmlNode& base); - TiXmlNode* firstChild; - TiXmlNode* lastChild; + /// Appends the XML node or attribute to a std::string. + friend std::string& operator<<(std::string& out, const TiXmlNode& base); - TIXML_STRING value; +#endif - TiXmlNode* prev; - TiXmlNode* next; + /** The types of XML nodes supported by TinyXml. (All the + unsupported types are picked up by UNKNOWN.) + */ + enum NodeType { + DOCUMENT, ELEMENT, COMMENT, UNKNOWN, TEXT, DECLARATION, TYPECOUNT + }; + + virtual ~TiXmlNode(); + + /** The meaning of 'value' changes for the specific type of + TiXmlNode. + @verbatim + Document: filename of the xml file + Element: name of the element + Comment: the comment text + Unknown: the tag contents + Text: the text string + @endverbatim + + The subclasses will wrap this function. + */ + const char *Value() const { + return value.c_str(); + } -private: - TiXmlNode( const TiXmlNode& ); // not implemented. - void operator=( const TiXmlNode& base ); // not allowed. -}; +#ifdef TIXML_USE_STL + /** Return Value() as a std::string. If you only use STL, + this is more efficient than calling Value(). + Only available in STL mode. + */ + const std::string& ValueStr() const { + return value; + } +#endif + /** Changes the value of the node. Defined as: + @verbatim + Document: filename of the xml file + Element: name of the element + Comment: the comment text + Unknown: the tag contents + Text: the text string + @endverbatim + */ + void SetValue(const char * _value) { + value = _value; + } -/** An attribute is a name-value pair. Elements have an arbitrary - number of attributes, each with a unique name. +#ifdef TIXML_USE_STL + /// STL std::string form. + void SetValue(const std::string& _value) { + value = _value; + } +#endif - @note The attributes are not TiXmlNodes, since they are not - part of the tinyXML document object model. There are other - suggested ways to look at this problem. -*/ -class TiXmlAttribute : public TiXmlBase -{ - friend class TiXmlAttributeSet; + /// Delete all the children of this node. Does not affect 'this'. + void Clear(); + + /// One step up the DOM. + TiXmlNode* Parent() { + return parent; + } + const TiXmlNode* Parent() const { + return parent; + } + + const TiXmlNode* FirstChild() const { + return firstChild; + } ///< The first child of this node. Will be null if there are no children. + TiXmlNode* FirstChild() { + return firstChild; + } + const TiXmlNode* FirstChild(const char * value) const; ///< The first child of this node with the matching 'value'. Will be null if none found. + /// The first child of this node with the matching 'value'. Will be null if none found. + TiXmlNode* FirstChild(const char * _value) { + // Call through to the const version - safe since nothing is changed. Exiting syntax: cast this to a const (always safe) + // call the method, cast the return back to non-const. + return const_cast<TiXmlNode*>((const_cast<const TiXmlNode*>(this))->FirstChild(_value)); + } + const TiXmlNode* LastChild() const { + return lastChild; + } /// The last child of this node. Will be null if there are no children. + TiXmlNode* LastChild() { + return lastChild; + } + + const TiXmlNode* LastChild(const char * value) const; /// The last child of this node matching 'value'. Will be null if there are no children. + TiXmlNode* LastChild(const char * _value) { + return const_cast<TiXmlNode*>((const_cast<const TiXmlNode*>(this))->LastChild(_value)); + } -public: - /// Construct an empty attribute. - TiXmlAttribute() : TiXmlBase() - { - document = 0; - prev = next = 0; - } - - #ifdef TIXML_USE_STL - /// std::string constructor. - TiXmlAttribute( const std::string& _name, const std::string& _value ) - { - name = _name; - value = _value; - document = 0; - prev = next = 0; - } - #endif - - /// Construct an attribute with a name and value. - TiXmlAttribute( const char * _name, const char * _value ) - { - name = _name; - value = _value; - document = 0; - prev = next = 0; - } - - const char* Name() const { return name.c_str(); } ///< Return the name of this attribute. - const char* Value() const { return value.c_str(); } ///< Return the value of this attribute. - #ifdef TIXML_USE_STL - const std::string& ValueStr() const { return value; } ///< Return the value of this attribute. - #endif - int IntValue() const; ///< Return the value of this attribute, converted to an integer. - double DoubleValue() const; ///< Return the value of this attribute, converted to a double. - - // Get the tinyxml string representation - const TIXML_STRING& NameTStr() const { return name; } - - /** QueryIntValue examines the value string. It is an alternative to the - IntValue() method with richer error checking. - If the value is an integer, it is stored in 'value' and - the call returns TIXML_SUCCESS. If it is not - an integer, it returns TIXML_WRONG_TYPE. - - A specialized but useful call. Note that for success it returns 0, - which is the opposite of almost all other TinyXml calls. - */ - int QueryIntValue( int* _value ) const; - /// QueryDoubleValue examines the value string. See QueryIntValue(). - int QueryDoubleValue( double* _value ) const; - - void SetName( const char* _name ) { name = _name; } ///< Set the name of this attribute. - void SetValue( const char* _value ) { value = _value; } ///< Set the value. - - void SetIntValue( int _value ); ///< Set the value from an integer. - void SetDoubleValue( double _value ); ///< Set the value from a double. - - #ifdef TIXML_USE_STL - /// STL std::string form. - void SetName( const std::string& _name ) { name = _name; } - /// STL std::string form. - void SetValue( const std::string& _value ) { value = _value; } - #endif - - /// Get the next sibling attribute in the DOM. Returns null at end. - const TiXmlAttribute* Next() const; - TiXmlAttribute* Next() { - return const_cast< TiXmlAttribute* >( (const_cast< const TiXmlAttribute* >(this))->Next() ); - } - - /// Get the previous sibling attribute in the DOM. Returns null at beginning. - const TiXmlAttribute* Previous() const; - TiXmlAttribute* Previous() { - return const_cast< TiXmlAttribute* >( (const_cast< const TiXmlAttribute* >(this))->Previous() ); - } - - bool operator==( const TiXmlAttribute& rhs ) const { return rhs.name == name; } - bool operator<( const TiXmlAttribute& rhs ) const { return name < rhs.name; } - bool operator>( const TiXmlAttribute& rhs ) const { return name > rhs.name; } - - /* Attribute parsing starts: first letter of the name - returns: the next char after the value end quote - */ - virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); - - // Prints this Attribute to a FILE stream. - virtual void Print( FILE* cfile, int depth ) const { - Print( cfile, depth, 0 ); - } - void Print( FILE* cfile, int depth, TIXML_STRING* str ) const; - - // [internal use] - // Set the document pointer so the attribute can report errors. - void SetDocument( TiXmlDocument* doc ) { document = doc; } - -private: - TiXmlAttribute( const TiXmlAttribute& ); // not implemented. - void operator=( const TiXmlAttribute& base ); // not allowed. - - TiXmlDocument* document; // A pointer back to a document, for error reporting. - TIXML_STRING name; - TIXML_STRING value; - TiXmlAttribute* prev; - TiXmlAttribute* next; -}; +#ifdef TIXML_USE_STL + const TiXmlNode* FirstChild(const std::string& _value) const { + return FirstChild(_value.c_str()); + } ///< STL std::string form. + TiXmlNode* FirstChild(const std::string& _value) { + return FirstChild(_value.c_str()); + } ///< STL std::string form. + const TiXmlNode* LastChild(const std::string& _value) const { + return LastChild(_value.c_str()); + } ///< STL std::string form. + TiXmlNode* LastChild(const std::string& _value) { + return LastChild(_value.c_str()); + } ///< STL std::string form. +#endif + /** An alternate way to walk the children of a node. + One way to iterate over nodes is: + @verbatim + for( child = parent->FirstChild(); child; child = child->NextSibling() ) + @endverbatim + + IterateChildren does the same thing with the syntax: + @verbatim + child = 0; + while( child = parent->IterateChildren( child ) ) + @endverbatim + + IterateChildren takes the previous child as input and finds + the next one. If the previous child is null, it returns the + first. IterateChildren will return null when done. + */ + const TiXmlNode* IterateChildren(const TiXmlNode* previous) const; + TiXmlNode* IterateChildren(const TiXmlNode* previous) { + return const_cast<TiXmlNode*>((const_cast<const TiXmlNode*>(this))->IterateChildren(previous)); + } + + /// This flavor of IterateChildren searches for children with a particular 'value' + const TiXmlNode* IterateChildren(const char * value, const TiXmlNode* previous) const; + TiXmlNode* IterateChildren(const char * _value, const TiXmlNode* previous) { + return const_cast<TiXmlNode*>((const_cast<const TiXmlNode*>(this))->IterateChildren(_value, previous)); + } -/* A class used to manage a group of attributes. - It is only used internally, both by the ELEMENT and the DECLARATION. - - The set can be changed transparent to the Element and Declaration - classes that use it, but NOT transparent to the Attribute - which has to implement a next() and previous() method. Which makes - it a bit problematic and prevents the use of STL. - - This version is implemented with circular lists because: - - I like circular lists - - it demonstrates some independence from the (typical) doubly linked list. -*/ -class TiXmlAttributeSet -{ -public: - TiXmlAttributeSet(); - ~TiXmlAttributeSet(); +#ifdef TIXML_USE_STL + const TiXmlNode* IterateChildren(const std::string& _value, const TiXmlNode* previous) const { + return IterateChildren(_value.c_str(), previous); + } ///< STL std::string form. + TiXmlNode* IterateChildren(const std::string& _value, const TiXmlNode* previous) { + return IterateChildren(_value.c_str(), previous); + } ///< STL std::string form. +#endif - void Add( TiXmlAttribute* attribute ); - void Remove( TiXmlAttribute* attribute ); + /** Add a new node related to this. Adds a child past the LastChild. + Returns a pointer to the new object or NULL if an error occured. + */ + TiXmlNode* InsertEndChild(const TiXmlNode& addThis); + + /** Add a new node related to this. Adds a child past the LastChild. + + NOTE: the node to be added is passed by pointer, and will be + henceforth owned (and deleted) by tinyXml. This method is efficient + and avoids an extra copy, but should be used with care as it + uses a different memory model than the other insert functions. + + @sa InsertEndChild + */ + TiXmlNode* LinkEndChild(TiXmlNode* addThis); + + /** Add a new node related to this. Adds a child before the specified child. + Returns a pointer to the new object or NULL if an error occured. + */ + TiXmlNode* InsertBeforeChild(TiXmlNode* beforeThis, const TiXmlNode& addThis); + + /** Add a new node related to this. Adds a child after the specified child. + Returns a pointer to the new object or NULL if an error occured. + */ + TiXmlNode* InsertAfterChild(TiXmlNode* afterThis, const TiXmlNode& addThis); + + /** Replace a child of this node. + Returns a pointer to the new object or NULL if an error occured. + */ + TiXmlNode* ReplaceChild(TiXmlNode* replaceThis, const TiXmlNode& withThis); + + /// Delete a child of this node. + bool RemoveChild(TiXmlNode* removeThis); + + /// Navigate to a sibling node. + const TiXmlNode* PreviousSibling() const { + return prev; + } + TiXmlNode* PreviousSibling() { + return prev; + } + + /// Navigate to a sibling node. + const TiXmlNode* PreviousSibling(const char *) const; + TiXmlNode* PreviousSibling(const char *_prev) { + return const_cast<TiXmlNode*>((const_cast<const TiXmlNode*>(this))->PreviousSibling(_prev)); + } - const TiXmlAttribute* First() const { return ( sentinel.next == &sentinel ) ? 0 : sentinel.next; } - TiXmlAttribute* First() { return ( sentinel.next == &sentinel ) ? 0 : sentinel.next; } - const TiXmlAttribute* Last() const { return ( sentinel.prev == &sentinel ) ? 0 : sentinel.prev; } - TiXmlAttribute* Last() { return ( sentinel.prev == &sentinel ) ? 0 : sentinel.prev; } +#ifdef TIXML_USE_STL + const TiXmlNode* PreviousSibling(const std::string& _value) const { + return PreviousSibling(_value.c_str()); + } ///< STL std::string form. + TiXmlNode* PreviousSibling(const std::string& _value) { + return PreviousSibling(_value.c_str()); + } ///< STL std::string form. + const TiXmlNode* NextSibling(const std::string& _value) const { + return NextSibling(_value.c_str()); + } ///< STL std::string form. + TiXmlNode* NextSibling(const std::string& _value) { + return NextSibling(_value.c_str()); + } ///< STL std::string form. +#endif - const TiXmlAttribute* Find( const char* _name ) const; - TiXmlAttribute* Find( const char* _name ) { - return const_cast< TiXmlAttribute* >( (const_cast< const TiXmlAttributeSet* >(this))->Find( _name ) ); - } - #ifdef TIXML_USE_STL - const TiXmlAttribute* Find( const std::string& _name ) const; - TiXmlAttribute* Find( const std::string& _name ) { - return const_cast< TiXmlAttribute* >( (const_cast< const TiXmlAttributeSet* >(this))->Find( _name ) ); - } + /// Navigate to a sibling node. + const TiXmlNode* NextSibling() const { + return next; + } + TiXmlNode* NextSibling() { + return next; + } + + /// Navigate to a sibling node with the given 'value'. + const TiXmlNode* NextSibling(const char *) const; + TiXmlNode* NextSibling(const char* _next) { + return const_cast<TiXmlNode*>((const_cast<const TiXmlNode*>(this))->NextSibling(_next)); + } + + /** Convenience function to get through elements. + Calls NextSibling and ToElement. Will skip all non-Element + nodes. Returns 0 if there is not another element. + */ + const TiXmlElement* NextSiblingElement() const; + TiXmlElement* NextSiblingElement() { + return const_cast<TiXmlElement*>((const_cast<const TiXmlNode*>(this))->NextSiblingElement()); + } + + /** Convenience function to get through elements. + Calls NextSibling and ToElement. Will skip all non-Element + nodes. Returns 0 if there is not another element. + */ + const TiXmlElement* NextSiblingElement(const char *) const; + TiXmlElement* NextSiblingElement(const char *_next) { + return const_cast<TiXmlElement*>((const_cast<const TiXmlNode*>(this))->NextSiblingElement(_next)); + } + + /** Convenience function to get through elements. + Calls PreviousSibling and ToElement. Will skip all non-Element + nodes. Returns 0 if there is not another element. + */ + const TiXmlElement* PreviousSiblingElement() const; + TiXmlElement* PreviousSiblingElement() { + return const_cast<TiXmlElement*>((const_cast<const TiXmlNode*>(this))->PreviousSiblingElement()); + } + + /** Convenience function to get through elements. + Calls PreviousSibling and ToElement. Will skip all non-Element + nodes. Returns 0 if there is not another element. + */ + const TiXmlElement* PreviousSiblingElement(const char *) const; + TiXmlElement* PreviousSiblingElement(const char *_next) { + return const_cast<TiXmlElement*>((const_cast<const TiXmlNode*>(this))->PreviousSiblingElement(_next)); + } - #endif +#ifdef TIXML_USE_STL + const TiXmlElement* NextSiblingElement(const std::string& _value) const { + return NextSiblingElement(_value.c_str()); + } ///< STL std::string form. + TiXmlElement* NextSiblingElement(const std::string& _value) { + return NextSiblingElement(_value.c_str()); + } ///< STL std::string form. +#endif -private: - //*ME: Because of hidden/disabled copy-construktor in TiXmlAttribute (sentinel-element), - //*ME: this class must be also use a hidden/disabled copy-constructor !!! - TiXmlAttributeSet( const TiXmlAttributeSet& ); // not allowed - void operator=( const TiXmlAttributeSet& ); // not allowed (as TiXmlAttribute) + /// Convenience function to get through elements. + const TiXmlElement* FirstChildElement() const; + TiXmlElement* FirstChildElement() { + return const_cast<TiXmlElement*>((const_cast<const TiXmlNode*>(this))->FirstChildElement()); + } - TiXmlAttribute sentinel; -}; + /// Convenience function to get through elements. + const TiXmlElement* FirstChildElement(const char * _value) const; + TiXmlElement* FirstChildElement(const char * _value) { + return const_cast<TiXmlElement*>((const_cast<const TiXmlNode*>(this))->FirstChildElement(_value)); + } +#ifdef TIXML_USE_STL + const TiXmlElement* FirstChildElement(const std::string& _value) const { + return FirstChildElement(_value.c_str()); + } ///< STL std::string form. + TiXmlElement* FirstChildElement(const std::string& _value) { + return FirstChildElement(_value.c_str()); + } ///< STL std::string form. +#endif -/** The element is a container class. It has a value, the element name, - and can contain other elements, text, comments, and unknowns. - Elements also contain an arbitrary number of attributes. -*/ -class TiXmlElement : public TiXmlNode -{ -public: - /// Construct an element. - TiXmlElement (const char * in_value); - - #ifdef TIXML_USE_STL - /// std::string constructor. - TiXmlElement( const std::string& _value ); - #endif - - TiXmlElement( const TiXmlElement& ); - - void operator=( const TiXmlElement& base ); - - virtual ~TiXmlElement(); - - /** Given an attribute name, Attribute() returns the attribute - with that name, or null if none exists. - */ - const TiXmlAttribute* AttributeNode( const char* name ) const { - return attributeSet.Find( name ); - } - - /** Given an attribute name, Attribute() returns the attribute value - with that name, or null if none exists. - */ - const char* Attribute( const char* name ) const; - - /** Clear all attribute nodes of this node. - */ - void ClearAttributes(); - - /** Given an attribute name, Attribute() returns the value - for the attribute of that name, or null if none exists. - If the attribute exists and can be converted to an integer, - the integer value will be put in the return 'i', if 'i' - is non-null. - */ - const char* Attribute( const char* name, int* i ) const; - - /** Given an attribute name, Attribute() returns the value - for the attribute of that name, or null if none exists. - If the attribute exists and can be converted to an double, - the double value will be put in the return 'd', if 'd' - is non-null. - */ - const char* Attribute( const char* name, double* d ) const; - - /** QueryIntAttribute examines the attribute - it is an alternative to the - Attribute() method with richer error checking. - If the attribute is an integer, it is stored in 'value' and - the call returns TIXML_SUCCESS. If it is not - an integer, it returns TIXML_WRONG_TYPE. If the attribute - does not exist, then TIXML_NO_ATTRIBUTE is returned. - */ - int QueryIntAttribute( const char* name, int* _value ) const; - /// QueryDoubleAttribute examines the attribute - see QueryIntAttribute(). - int QueryDoubleAttribute( const char* name, double* _value ) const; - /// QueryFloatAttribute examines the attribute - see QueryIntAttribute(). - int QueryFloatAttribute( const char* name, float* _value ) const { - double d; - int result = QueryDoubleAttribute( name, &d ); - if ( result == TIXML_SUCCESS ) { - *_value = (float)d; - } - return result; - } - #ifdef TIXML_USE_STL - /** Template form of the attribute query which will try to read the - attribute into the specified type. Very easy, very powerful, but - be careful to make sure to call this with the correct type. - - @return TIXML_SUCCESS, TIXML_WRONG_TYPE, or TIXML_NO_ATTRIBUTE - */ - template< typename T > int QueryValueAttribute( const std::string& name, T* outValue ) const - { - const TiXmlAttribute* node = attributeSet.Find( name ); - if ( !node ) - return TIXML_NO_ATTRIBUTE; - - std::stringstream sstream( node->ValueStr() ); - sstream >> *outValue; - if ( !sstream.fail() ) - return TIXML_SUCCESS; - return TIXML_WRONG_TYPE; - } - #endif - - /** Sets an attribute of name to a given value. The attribute - will be created if it does not exist, or changed if it does. - */ - void SetAttribute( const char* name, const char * _value ); - - #ifdef TIXML_USE_STL - const std::string* Attribute( const std::string& name ) const; - const std::string* Attribute( const std::string& name, int* i ) const; - const std::string* Attribute( const std::string& name, double* d ) const; - int QueryIntAttribute( const std::string& name, int* _value ) const; - int QueryDoubleAttribute( const std::string& name, double* _value ) const; - - /// STL std::string form. - void SetAttribute( const std::string& name, const std::string& _value ); - ///< STL std::string form. - void SetAttribute( const std::string& name, int _value ); - #endif - - /** Sets an attribute of name to a given value. The attribute - will be created if it does not exist, or changed if it does. - */ - void SetAttribute( const char * name, int value ); - - /** Sets an attribute of name to a given value. The attribute - will be created if it does not exist, or changed if it does. - */ - void SetDoubleAttribute( const char * name, double value ); - - /** Deletes an attribute with the given name. - */ - void RemoveAttribute( const char * name ); - #ifdef TIXML_USE_STL - void RemoveAttribute( const std::string& name ) { RemoveAttribute (name.c_str ()); } ///< STL std::string form. - #endif - - const TiXmlAttribute* FirstAttribute() const { return attributeSet.First(); } ///< Access the first attribute in this element. - TiXmlAttribute* FirstAttribute() { return attributeSet.First(); } - const TiXmlAttribute* LastAttribute() const { return attributeSet.Last(); } ///< Access the last attribute in this element. - TiXmlAttribute* LastAttribute() { return attributeSet.Last(); } - - /** Convenience function for easy access to the text inside an element. Although easy - and concise, GetText() is limited compared to getting the TiXmlText child - and accessing it directly. - - If the first child of 'this' is a TiXmlText, the GetText() - returns the character string of the Text node, else null is returned. - - This is a convenient method for getting the text of simple contained text: - @verbatim - <foo>This is text</foo> - const char* str = fooElement->GetText(); - @endverbatim - - 'str' will be a pointer to "This is text". - - Note that this function can be misleading. If the element foo was created from - this XML: - @verbatim - <foo><b>This is text</b></foo> - @endverbatim - - then the value of str would be null. The first child node isn't a text node, it is - another element. From this XML: - @verbatim - <foo>This is <b>text</b></foo> - @endverbatim - GetText() will return "This is ". - - WARNING: GetText() accesses a child node - don't become confused with the - similarly named TiXmlHandle::Text() and TiXmlNode::ToText() which are - safe type casts on the referenced node. - */ - const char* GetText() const; - - /// Creates a new Element and returns it - the returned element is a copy. - virtual TiXmlNode* Clone() const; - // Print the Element to a FILE stream. - virtual void Print( FILE* cfile, int depth ) const; - - /* Attribtue parsing starts: next char past '<' - returns: next char past '>' - */ - virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); - - virtual const TiXmlElement* ToElement() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type. - virtual TiXmlElement* ToElement() { return this; } ///< Cast to a more defined type. Will return null not of the requested type. - - /** Walk the XML tree visiting this node and all of its children. - */ - virtual bool Accept( TiXmlVisitor* visitor ) const; + /** Query the type (as an enumerated value, above) of this node. + The possible types are: DOCUMENT, ELEMENT, COMMENT, + UNKNOWN, TEXT, and DECLARATION. + */ + int Type() const { + return type; + } + + /** Return a pointer to the Document this node lives in. + Returns null if not in a document. + */ + const TiXmlDocument* GetDocument() const; + TiXmlDocument* GetDocument() { + return const_cast<TiXmlDocument*>((const_cast<const TiXmlNode*>(this))->GetDocument()); + } + + /// Returns true if this node has no children. + bool NoChildren() const { + return !firstChild; + } + + virtual const TiXmlDocument* ToDocument() const { + return 0; + } ///< Cast to a more defined type. Will return null if not of the requested type. + virtual const TiXmlElement* ToElement() const { + return 0; + } ///< Cast to a more defined type. Will return null if not of the requested type. + virtual const TiXmlComment* ToComment() const { + return 0; + } ///< Cast to a more defined type. Will return null if not of the requested type. + virtual const TiXmlUnknown* ToUnknown() const { + return 0; + } ///< Cast to a more defined type. Will return null if not of the requested type. + virtual const TiXmlText* ToText() const { + return 0; + } ///< Cast to a more defined type. Will return null if not of the requested type. + virtual const TiXmlDeclaration* ToDeclaration() const { + return 0; + } ///< Cast to a more defined type. Will return null if not of the requested type. + + virtual TiXmlDocument* ToDocument() { + return 0; + } ///< Cast to a more defined type. Will return null if not of the requested type. + virtual TiXmlElement* ToElement() { + return 0; + } ///< Cast to a more defined type. Will return null if not of the requested type. + virtual TiXmlComment* ToComment() { + return 0; + } ///< Cast to a more defined type. Will return null if not of the requested type. + virtual TiXmlUnknown* ToUnknown() { + return 0; + } ///< Cast to a more defined type. Will return null if not of the requested type. + virtual TiXmlText* ToText() { + return 0; + } ///< Cast to a more defined type. Will return null if not of the requested type. + virtual TiXmlDeclaration* ToDeclaration() { + return 0; + } ///< Cast to a more defined type. Will return null if not of the requested type. + + /** Create an exact duplicate of this node and return it. The memory must be deleted + by the caller. + */ + virtual TiXmlNode* Clone() const = 0; + + /** Accept a hierchical visit the nodes in the TinyXML DOM. Every node in the + XML tree will be conditionally visited and the host will be called back + via the TiXmlVisitor interface. + + This is essentially a SAX interface for TinyXML. (Note however it doesn't re-parse + the XML for the callbacks, so the performance of TinyXML is unchanged by using this + interface versus any other.) + + The interface has been based on ideas from: + + - http://www.saxproject.org/ + - http://c2.com/cgi/wiki?HierarchicalVisitorPattern + + Which are both good references for "visiting". + + An example of using Accept(): + @verbatim + TiXmlPrinter printer; + tinyxmlDoc.Accept( &printer ); + const char* xmlcstr = printer.CStr(); + @endverbatim + */ + virtual bool Accept(TiXmlVisitor* visitor) const = 0; protected: + TiXmlNode(NodeType _type); + + // Copy to the allocated object. Shared functionality between Clone, Copy constructor, + // and the assignment operator. + void CopyTo(TiXmlNode* target) const; - void CopyTo( TiXmlElement* target ) const; - void ClearThis(); // like clear, but initializes 'this' object as well +#ifdef TIXML_USE_STL + // The real work of the input operator. + virtual void StreamIn(std::istream* in, TIXML_STRING* tag) = 0; +#endif - // Used to be public [internal use] - #ifdef TIXML_USE_STL - virtual void StreamIn( std::istream * in, TIXML_STRING * tag ); - #endif - /* [internal use] - Reads the "value" of the element -- another element, or text. - This should terminate with the current end tag. - */ - const char* ReadValue( const char* in, TiXmlParsingData* prevData, TiXmlEncoding encoding ); + // Figure out what is at *p, and parse it. Returns null if it is not an xml node. + TiXmlNode* Identify(const char* start, TiXmlEncoding encoding); -private: + TiXmlNode* parent; + NodeType type; + + TiXmlNode* firstChild; + TiXmlNode* lastChild; + + TIXML_STRING value; - TiXmlAttributeSet attributeSet; + TiXmlNode* prev; + TiXmlNode* next; + +private: + TiXmlNode(const TiXmlNode&); // not implemented. + void operator=(const TiXmlNode& base); // not allowed. }; +/** An attribute is a name-value pair. Elements have an arbitrary + number of attributes, each with a unique name. + + @note The attributes are not TiXmlNodes, since they are not + part of the tinyXML document object model. There are other + suggested ways to look at this problem. + */ +class TiXmlAttribute: public TiXmlBase { + friend class TiXmlAttributeSet; -/** An XML comment. -*/ -class TiXmlComment : public TiXmlNode -{ public: - /// Constructs an empty comment. - TiXmlComment() : TiXmlNode( TiXmlNode::COMMENT ) {} - /// Construct a comment from text. - TiXmlComment( const char* _value ) : TiXmlNode( TiXmlNode::COMMENT ) { - SetValue( _value ); - } - TiXmlComment( const TiXmlComment& ); - void operator=( const TiXmlComment& base ); - - virtual ~TiXmlComment() {} - - /// Returns a copy of this Comment. - virtual TiXmlNode* Clone() const; - // Write this Comment to a FILE stream. - virtual void Print( FILE* cfile, int depth ) const; - - /* Attribtue parsing starts: at the ! of the !-- - returns: next char past '>' - */ - virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); - - virtual const TiXmlComment* ToComment() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type. - virtual TiXmlComment* ToComment() { return this; } ///< Cast to a more defined type. Will return null not of the requested type. - - /** Walk the XML tree visiting this node and all of its children. - */ - virtual bool Accept( TiXmlVisitor* visitor ) const; + /// Construct an empty attribute. + TiXmlAttribute() + : TiXmlBase() { + document = 0; + prev = next = 0; + } -protected: - void CopyTo( TiXmlComment* target ) const; +#ifdef TIXML_USE_STL + /// std::string constructor. + TiXmlAttribute(const std::string& _name, const std::string& _value) { + name = _name; + value = _value; + document = 0; + prev = next = 0; + } +#endif - // used to be public - #ifdef TIXML_USE_STL - virtual void StreamIn( std::istream * in, TIXML_STRING * tag ); - #endif -// virtual void StreamOut( TIXML_OSTREAM * out ) const; + /// Construct an attribute with a name and value. + TiXmlAttribute(const char * _name, const char * _value) { + name = _name; + value = _value; + document = 0; + prev = next = 0; + } + + const char* Name() const { + return name.c_str(); + } ///< Return the name of this attribute. + const char* Value() const { + return value.c_str(); + } ///< Return the value of this attribute. +#ifdef TIXML_USE_STL + const std::string& ValueStr() const { + return value; + } ///< Return the value of this attribute. +#endif + int IntValue() const; ///< Return the value of this attribute, converted to an integer. + double DoubleValue() const; ///< Return the value of this attribute, converted to a double. + + // Get the tinyxml string representation + const TIXML_STRING& NameTStr() const { + return name; + } + + /** QueryIntValue examines the value string. It is an alternative to the + IntValue() method with richer error checking. + If the value is an integer, it is stored in 'value' and + the call returns TIXML_SUCCESS. If it is not + an integer, it returns TIXML_WRONG_TYPE. + + A specialized but useful call. Note that for success it returns 0, + which is the opposite of almost all other TinyXml calls. + */ + int QueryIntValue(int* _value) const; + /// QueryDoubleValue examines the value string. See QueryIntValue(). + int QueryDoubleValue(double* _value) const; + + void SetName(const char* _name) { + name = _name; + } ///< Set the name of this attribute. + void SetValue(const char* _value) { + value = _value; + } ///< Set the value. + + void SetIntValue(int _value); ///< Set the value from an integer. + void SetDoubleValue(double _value); ///< Set the value from a double. + +#ifdef TIXML_USE_STL + /// STL std::string form. + void SetName(const std::string& _name) { + name = _name; + } + /// STL std::string form. + void SetValue(const std::string& _value) { + value = _value; + } +#endif + + /// Get the next sibling attribute in the DOM. Returns null at end. + const TiXmlAttribute* Next() const; + TiXmlAttribute* Next() { + return const_cast<TiXmlAttribute*>((const_cast<const TiXmlAttribute*>(this))->Next()); + } + + /// Get the previous sibling attribute in the DOM. Returns null at beginning. + const TiXmlAttribute* Previous() const; + TiXmlAttribute* Previous() { + return const_cast<TiXmlAttribute*>((const_cast<const TiXmlAttribute*>(this))->Previous()); + } + + bool operator==(const TiXmlAttribute& rhs) const { + return rhs.name == name; + } + bool operator<(const TiXmlAttribute& rhs) const { + return name < rhs.name; + } + bool operator>(const TiXmlAttribute& rhs) const { + return name > rhs.name; + } + + /* Attribute parsing starts: first letter of the name + returns: the next char after the value end quote + */ + virtual const char* Parse(const char* p, TiXmlParsingData* data, TiXmlEncoding encoding); + + // Prints this Attribute to a FILE stream. + virtual void Print(FILE* cfile, int depth) const { + Print(cfile, depth, 0); + } + void Print(FILE* cfile, int depth, TIXML_STRING* str) const; + + // [internal use] + // Set the document pointer so the attribute can report errors. + void SetDocument(TiXmlDocument* doc) { + document = doc; + } private: + TiXmlAttribute(const TiXmlAttribute&); // not implemented. + void operator=(const TiXmlAttribute& base); // not allowed. + TiXmlDocument* document; // A pointer back to a document, for error reporting. + TIXML_STRING name;TIXML_STRING value; + TiXmlAttribute* prev; + TiXmlAttribute* next; }; - -/** XML text. A text node can have 2 ways to output the next. "normal" output - and CDATA. It will default to the mode it was parsed from the XML file and - you generally want to leave it alone, but you can change the output mode with - SetCDATA() and query it with CDATA(). -*/ -class TiXmlText : public TiXmlNode -{ - friend class TiXmlElement; +/* A class used to manage a group of attributes. + It is only used internally, both by the ELEMENT and the DECLARATION. + + The set can be changed transparent to the Element and Declaration + classes that use it, but NOT transparent to the Attribute + which has to implement a next() and previous() method. Which makes + it a bit problematic and prevents the use of STL. + + This version is implemented with circular lists because: + - I like circular lists + - it demonstrates some independence from the (typical) doubly linked list. + */ +class TiXmlAttributeSet { public: - /** Constructor for text element. By default, it is treated as - normal, encoded text. If you want it be output as a CDATA text - element, set the parameter _cdata to 'true' - */ - TiXmlText (const char * initValue ) : TiXmlNode (TiXmlNode::TEXT) - { - SetValue( initValue ); - cdata = false; - } - virtual ~TiXmlText() {} - - #ifdef TIXML_USE_STL - /// Constructor. - TiXmlText( const std::string& initValue ) : TiXmlNode (TiXmlNode::TEXT) - { - SetValue( initValue ); - cdata = false; - } - #endif - - TiXmlText( const TiXmlText& copy ) : TiXmlNode( TiXmlNode::TEXT ) { copy.CopyTo( this ); } - void operator=( const TiXmlText& base ) { base.CopyTo( this ); } - - // Write this text object to a FILE stream. - virtual void Print( FILE* cfile, int depth ) const; - - /// Queries whether this represents text using a CDATA section. - bool CDATA() const { return cdata; } - /// Turns on or off a CDATA representation of text. - void SetCDATA( bool _cdata ) { cdata = _cdata; } - - virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); - - virtual const TiXmlText* ToText() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type. - virtual TiXmlText* ToText() { return this; } ///< Cast to a more defined type. Will return null not of the requested type. - - /** Walk the XML tree visiting this node and all of its children. - */ - virtual bool Accept( TiXmlVisitor* content ) const; - -protected : - /// [internal use] Creates a new Element and returns it. - virtual TiXmlNode* Clone() const; - void CopyTo( TiXmlText* target ) const; - - bool Blank() const; // returns true if all white space and new lines - // [internal use] - #ifdef TIXML_USE_STL - virtual void StreamIn( std::istream * in, TIXML_STRING * tag ); - #endif + TiXmlAttributeSet(); + ~TiXmlAttributeSet(); + + void Add(TiXmlAttribute* attribute); + void Remove(TiXmlAttribute* attribute); + + const TiXmlAttribute* First() const { + return (sentinel.next == &sentinel) ? 0 : sentinel.next; + } + TiXmlAttribute* First() { + return (sentinel.next == &sentinel) ? 0 : sentinel.next; + } + const TiXmlAttribute* Last() const { + return (sentinel.prev == &sentinel) ? 0 : sentinel.prev; + } + TiXmlAttribute* Last() { + return (sentinel.prev == &sentinel) ? 0 : sentinel.prev; + } + + const TiXmlAttribute* Find(const char* _name) const; + TiXmlAttribute* Find(const char* _name) { + return const_cast<TiXmlAttribute*>((const_cast<const TiXmlAttributeSet*>(this))->Find(_name)); + } +#ifdef TIXML_USE_STL + const TiXmlAttribute* Find(const std::string& _name) const; + TiXmlAttribute* Find(const std::string& _name) { + return const_cast<TiXmlAttribute*>((const_cast<const TiXmlAttributeSet*>(this))->Find(_name)); + } + +#endif private: - bool cdata; // true if this should be input and output as a CDATA style text element -}; + //*ME: Because of hidden/disabled copy-construktor in TiXmlAttribute (sentinel-element), + //*ME: this class must be also use a hidden/disabled copy-constructor !!! + TiXmlAttributeSet(const TiXmlAttributeSet&); // not allowed + void operator=(const TiXmlAttributeSet&); // not allowed (as TiXmlAttribute) + TiXmlAttribute sentinel; +}; -/** In correct XML the declaration is the first entry in the file. - @verbatim - <?xml version="1.0" standalone="yes"?> - @endverbatim - - TinyXml will happily read or write files without a declaration, - however. There are 3 possible attributes to the declaration: - version, encoding, and standalone. - - Note: In this version of the code, the attributes are - handled as special cases, not generic attributes, simply - because there can only be at most 3 and they are always the same. -*/ -class TiXmlDeclaration : public TiXmlNode -{ +/** The element is a container class. It has a value, the element name, + and can contain other elements, text, comments, and unknowns. + Elements also contain an arbitrary number of attributes. + */ +class TiXmlElement: public TiXmlNode { public: - /// Construct an empty declaration. - TiXmlDeclaration() : TiXmlNode( TiXmlNode::DECLARATION ) {} + /// Construct an element. + TiXmlElement(const char * in_value); + +#ifdef TIXML_USE_STL + /// std::string constructor. + TiXmlElement(const std::string& _value); +#endif + TiXmlElement(const TiXmlElement&); + + void operator=(const TiXmlElement& base); + + virtual ~TiXmlElement(); + + /** Given an attribute name, Attribute() returns the attribute + with that name, or null if none exists. + */ + const TiXmlAttribute* AttributeNode(const char* name) const { + return attributeSet.Find(name); + } + + /** Given an attribute name, Attribute() returns the attribute value + with that name, or null if none exists. + */ + const char* Attribute(const char* name) const; + + /** Clear all attribute nodes of this node. + */ + void ClearAttributes(); + + /** Given an attribute name, Attribute() returns the value + for the attribute of that name, or null if none exists. + If the attribute exists and can be converted to an integer, + the integer value will be put in the return 'i', if 'i' + is non-null. + */ + const char* Attribute(const char* name, int* i) const; + + /** Given an attribute name, Attribute() returns the value + for the attribute of that name, or null if none exists. + If the attribute exists and can be converted to an double, + the double value will be put in the return 'd', if 'd' + is non-null. + */ + const char* Attribute(const char* name, double* d) const; + + /** QueryIntAttribute examines the attribute - it is an alternative to the + Attribute() method with richer error checking. + If the attribute is an integer, it is stored in 'value' and + the call returns TIXML_SUCCESS. If it is not + an integer, it returns TIXML_WRONG_TYPE. If the attribute + does not exist, then TIXML_NO_ATTRIBUTE is returned. + */ + int QueryIntAttribute(const char* name, int* _value) const; + /// QueryDoubleAttribute examines the attribute - see QueryIntAttribute(). + int QueryDoubleAttribute(const char* name, double* _value) const; + /// QueryFloatAttribute examines the attribute - see QueryIntAttribute(). + int QueryFloatAttribute(const char* name, float* _value) const { + double d; + int result = QueryDoubleAttribute(name, &d); + if (result == TIXML_SUCCESS) { + *_value = (float) d; + } + return result; + } #ifdef TIXML_USE_STL - /// Constructor. - TiXmlDeclaration( const std::string& _version, - const std::string& _encoding, - const std::string& _standalone ); + /** Template form of the attribute query which will try to read the + attribute into the specified type. Very easy, very powerful, but + be careful to make sure to call this with the correct type. + + @return TIXML_SUCCESS, TIXML_WRONG_TYPE, or TIXML_NO_ATTRIBUTE + */ + template <typename T> int QueryValueAttribute(const std::string& name, T* outValue) const { + const TiXmlAttribute* node = attributeSet.Find(name); + if (!node) + return TIXML_NO_ATTRIBUTE; + + std::stringstream sstream(node->ValueStr()); + sstream >> *outValue; + if (!sstream.fail()) + return TIXML_SUCCESS; + return TIXML_WRONG_TYPE; + } #endif - /// Construct. - TiXmlDeclaration( const char* _version, - const char* _encoding, - const char* _standalone ); + /** Sets an attribute of name to a given value. The attribute + will be created if it does not exist, or changed if it does. + */ + void SetAttribute(const char* name, const char * _value); - TiXmlDeclaration( const TiXmlDeclaration& copy ); - void operator=( const TiXmlDeclaration& copy ); +#ifdef TIXML_USE_STL + const std::string* Attribute(const std::string& name) const; + const std::string* Attribute(const std::string& name, int* i) const; + const std::string* Attribute(const std::string& name, double* d) const; + int QueryIntAttribute(const std::string& name, int* _value) const; + int QueryDoubleAttribute(const std::string& name, double* _value) const; + + /// STL std::string form. + void SetAttribute(const std::string& name, const std::string& _value); + ///< STL std::string form. + void SetAttribute(const std::string& name, int _value); +#endif + + /** Sets an attribute of name to a given value. The attribute + will be created if it does not exist, or changed if it does. + */ + void SetAttribute(const char * name, int value); - virtual ~TiXmlDeclaration() {} + /** Sets an attribute of name to a given value. The attribute + will be created if it does not exist, or changed if it does. + */ + void SetDoubleAttribute(const char * name, double value); + + /** Deletes an attribute with the given name. + */ + void RemoveAttribute(const char * name); +#ifdef TIXML_USE_STL + void RemoveAttribute(const std::string& name) { + RemoveAttribute(name.c_str()); + } ///< STL std::string form. +#endif - /// Version. Will return an empty string if none was found. - const char *Version() const { return version.c_str (); } - /// Encoding. Will return an empty string if none was found. - const char *Encoding() const { return encoding.c_str (); } - /// Is this a standalone document? - const char *Standalone() const { return standalone.c_str (); } + const TiXmlAttribute* FirstAttribute() const { + return attributeSet.First(); + } ///< Access the first attribute in this element. + TiXmlAttribute* FirstAttribute() { + return attributeSet.First(); + } + const TiXmlAttribute* LastAttribute() const { + return attributeSet.Last(); + } ///< Access the last attribute in this element. + TiXmlAttribute* LastAttribute() { + return attributeSet.Last(); + } + + /** Convenience function for easy access to the text inside an element. Although easy + and concise, GetText() is limited compared to getting the TiXmlText child + and accessing it directly. + + If the first child of 'this' is a TiXmlText, the GetText() + returns the character string of the Text node, else null is returned. + + This is a convenient method for getting the text of simple contained text: + @verbatim + <foo>This is text</foo> + const char* str = fooElement->GetText(); + @endverbatim + + 'str' will be a pointer to "This is text". + + Note that this function can be misleading. If the element foo was created from + this XML: + @verbatim + <foo><b>This is text</b></foo> + @endverbatim + + then the value of str would be null. The first child node isn't a text node, it is + another element. From this XML: + @verbatim + <foo>This is <b>text</b></foo> + @endverbatim + GetText() will return "This is ". + + WARNING: GetText() accesses a child node - don't become confused with the + similarly named TiXmlHandle::Text() and TiXmlNode::ToText() which are + safe type casts on the referenced node. + */ + const char* GetText() const; + + /// Creates a new Element and returns it - the returned element is a copy. + virtual TiXmlNode* Clone() const; + // Print the Element to a FILE stream. + virtual void Print(FILE* cfile, int depth) const; + + /* Attribtue parsing starts: next char past '<' + returns: next char past '>' + */ + virtual const char* Parse(const char* p, TiXmlParsingData* data, TiXmlEncoding encoding); + + virtual const TiXmlElement* ToElement() const { + return this; + } ///< Cast to a more defined type. Will return null not of the requested type. + virtual TiXmlElement* ToElement() { + return this; + } ///< Cast to a more defined type. Will return null not of the requested type. + + /** Walk the XML tree visiting this node and all of its children. + */ + virtual bool Accept(TiXmlVisitor* visitor) const; - /// Creates a copy of this Declaration and returns it. - virtual TiXmlNode* Clone() const; - // Print this declaration to a FILE stream. - virtual void Print( FILE* cfile, int depth, TIXML_STRING* str ) const; - virtual void Print( FILE* cfile, int depth ) const { - Print( cfile, depth, 0 ); - } +protected: - virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); + void CopyTo(TiXmlElement* target) const; + void ClearThis(); // like clear, but initializes 'this' object as well - virtual const TiXmlDeclaration* ToDeclaration() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type. - virtual TiXmlDeclaration* ToDeclaration() { return this; } ///< Cast to a more defined type. Will return null not of the requested type. + // Used to be public [internal use] +#ifdef TIXML_USE_STL + virtual void StreamIn(std::istream * in, TIXML_STRING * tag); +#endif + /* [internal use] + Reads the "value" of the element -- another element, or text. + This should terminate with the current end tag. + */ + const char* ReadValue(const char* in, TiXmlParsingData* prevData, TiXmlEncoding encoding); - /** Walk the XML tree visiting this node and all of its children. - */ - virtual bool Accept( TiXmlVisitor* visitor ) const; +private: + + TiXmlAttributeSet attributeSet; +}; + +/** An XML comment. + */ +class TiXmlComment: public TiXmlNode { +public: + /// Constructs an empty comment. + TiXmlComment() + : TiXmlNode(TiXmlNode::COMMENT) { + } + /// Construct a comment from text. + TiXmlComment(const char* _value) + : TiXmlNode(TiXmlNode::COMMENT) { + SetValue(_value); + } + TiXmlComment(const TiXmlComment&); + void operator=(const TiXmlComment& base); + + virtual ~TiXmlComment() { + } + + /// Returns a copy of this Comment. + virtual TiXmlNode* Clone() const; + // Write this Comment to a FILE stream. + virtual void Print(FILE* cfile, int depth) const; + + /* Attribtue parsing starts: at the ! of the !-- + returns: next char past '>' + */ + virtual const char* Parse(const char* p, TiXmlParsingData* data, TiXmlEncoding encoding); + + virtual const TiXmlComment* ToComment() const { + return this; + } ///< Cast to a more defined type. Will return null not of the requested type. + virtual TiXmlComment* ToComment() { + return this; + } ///< Cast to a more defined type. Will return null not of the requested type. + + /** Walk the XML tree visiting this node and all of its children. + */ + virtual bool Accept(TiXmlVisitor* visitor) const; protected: - void CopyTo( TiXmlDeclaration* target ) const; - // used to be public - #ifdef TIXML_USE_STL - virtual void StreamIn( std::istream * in, TIXML_STRING * tag ); - #endif + void CopyTo(TiXmlComment* target) const; + + // used to be public +#ifdef TIXML_USE_STL + virtual void StreamIn(std::istream * in, TIXML_STRING * tag); +#endif +// virtual void StreamOut( TIXML_OSTREAM * out ) const; private: - TIXML_STRING version; - TIXML_STRING encoding; - TIXML_STRING standalone; }; +/** XML text. A text node can have 2 ways to output the next. "normal" output + and CDATA. It will default to the mode it was parsed from the XML file and + you generally want to leave it alone, but you can change the output mode with + SetCDATA() and query it with CDATA(). + */ +class TiXmlText: public TiXmlNode { + friend class TiXmlElement; +public: + /** Constructor for text element. By default, it is treated as + normal, encoded text. If you want it be output as a CDATA text + element, set the parameter _cdata to 'true' + */ + TiXmlText(const char * initValue) + : TiXmlNode(TiXmlNode::TEXT) { + SetValue(initValue); + cdata = false; + } + virtual ~TiXmlText() { + } -/** Any tag that tinyXml doesn't recognize is saved as an - unknown. It is a tag of text, but should not be modified. - It will be written back to the XML, unchanged, when the file - is saved. - - DTD tags get thrown into TiXmlUnknowns. -*/ -class TiXmlUnknown : public TiXmlNode -{ +#ifdef TIXML_USE_STL + /// Constructor. + TiXmlText(const std::string& initValue) + : TiXmlNode(TiXmlNode::TEXT) { + SetValue(initValue); + cdata = false; + } +#endif + + TiXmlText(const TiXmlText& copy) + : TiXmlNode(TiXmlNode::TEXT) { + copy.CopyTo(this); + } + void operator=(const TiXmlText& base) { + base.CopyTo(this); + } + + // Write this text object to a FILE stream. + virtual void Print(FILE* cfile, int depth) const; + + /// Queries whether this represents text using a CDATA section. + bool CDATA() const { + return cdata; + } + /// Turns on or off a CDATA representation of text. + void SetCDATA(bool _cdata) { + cdata = _cdata; + } + + virtual const char* Parse(const char* p, TiXmlParsingData* data, TiXmlEncoding encoding); + + virtual const TiXmlText* ToText() const { + return this; + } ///< Cast to a more defined type. Will return null not of the requested type. + virtual TiXmlText* ToText() { + return this; + } ///< Cast to a more defined type. Will return null not of the requested type. + + /** Walk the XML tree visiting this node and all of its children. + */ + virtual bool Accept(TiXmlVisitor* content) const; + +protected: + /// [internal use] Creates a new Element and returns it. + virtual TiXmlNode* Clone() const; + void CopyTo(TiXmlText* target) const; + + bool Blank() const; // returns true if all white space and new lines + // [internal use] +#ifdef TIXML_USE_STL + virtual void StreamIn(std::istream * in, TIXML_STRING * tag); +#endif + +private: + bool cdata; // true if this should be input and output as a CDATA style text element +}; + +/** In correct XML the declaration is the first entry in the file. + @verbatim + <?xml version="1.0" standalone="yes"?> + @endverbatim + + TinyXml will happily read or write files without a declaration, + however. There are 3 possible attributes to the declaration: + version, encoding, and standalone. + + Note: In this version of the code, the attributes are + handled as special cases, not generic attributes, simply + because there can only be at most 3 and they are always the same. + */ +class TiXmlDeclaration: public TiXmlNode { public: - TiXmlUnknown() : TiXmlNode( TiXmlNode::UNKNOWN ) {} - virtual ~TiXmlUnknown() {} + /// Construct an empty declaration. + TiXmlDeclaration() + : TiXmlNode(TiXmlNode::DECLARATION) { + } + +#ifdef TIXML_USE_STL + /// Constructor. + TiXmlDeclaration(const std::string& _version, const std::string& _encoding, const std::string& _standalone); +#endif - TiXmlUnknown( const TiXmlUnknown& copy ) : TiXmlNode( TiXmlNode::UNKNOWN ) { copy.CopyTo( this ); } - void operator=( const TiXmlUnknown& copy ) { copy.CopyTo( this ); } + /// Construct. + TiXmlDeclaration(const char* _version, const char* _encoding, const char* _standalone); + + TiXmlDeclaration(const TiXmlDeclaration& copy); + void operator=(const TiXmlDeclaration& copy); + + virtual ~TiXmlDeclaration() { + } + + /// Version. Will return an empty string if none was found. + const char *Version() const { + return version.c_str(); + } + /// Encoding. Will return an empty string if none was found. + const char *Encoding() const { + return encoding.c_str(); + } + /// Is this a standalone document? + const char *Standalone() const { + return standalone.c_str(); + } + + /// Creates a copy of this Declaration and returns it. + virtual TiXmlNode* Clone() const; + // Print this declaration to a FILE stream. + virtual void Print(FILE* cfile, int depth, TIXML_STRING* str) const; + virtual void Print(FILE* cfile, int depth) const { + Print(cfile, depth, 0); + } + + virtual const char* Parse(const char* p, TiXmlParsingData* data, TiXmlEncoding encoding); + + virtual const TiXmlDeclaration* ToDeclaration() const { + return this; + } ///< Cast to a more defined type. Will return null not of the requested type. + virtual TiXmlDeclaration* ToDeclaration() { + return this; + } ///< Cast to a more defined type. Will return null not of the requested type. + + /** Walk the XML tree visiting this node and all of its children. + */ + virtual bool Accept(TiXmlVisitor* visitor) const; - /// Creates a copy of this Unknown and returns it. - virtual TiXmlNode* Clone() const; - // Print this Unknown to a FILE stream. - virtual void Print( FILE* cfile, int depth ) const; +protected: + void CopyTo(TiXmlDeclaration* target) const; + // used to be public +#ifdef TIXML_USE_STL + virtual void StreamIn(std::istream * in, TIXML_STRING * tag); +#endif + +private: - virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding ); + TIXML_STRING version;TIXML_STRING encoding;TIXML_STRING standalone; +}; - virtual const TiXmlUnknown* ToUnknown() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type. - virtual TiXmlUnknown* ToUnknown() { return this; } ///< Cast to a more defined type. Will return null not of the requested type. +/** Any tag that tinyXml doesn't recognize is saved as an + unknown. It is a tag of text, but should not be modified. + It will be written back to the XML, unchanged, when the file + is saved. - /** Walk the XML tree visiting this node and all of its children. - */ - virtual bool Accept( TiXmlVisitor* content ) const; + DTD tags get thrown into TiXmlUnknowns. + */ +class TiXmlUnknown: public TiXmlNode { +public: + TiXmlUnknown() + : TiXmlNode(TiXmlNode::UNKNOWN) { + } + virtual ~TiXmlUnknown() { + } + + TiXmlUnknown(const TiXmlUnknown& copy) + : TiXmlNode(TiXmlNode::UNKNOWN) { + copy.CopyTo(this); + } + void operator=(const TiXmlUnknown& copy) { + copy.CopyTo(this); + } + + /// Creates a copy of this Unknown and returns it. + virtual TiXmlNode* Clone() const; + // Print this Unknown to a FILE stream. + virtual void Print(FILE* cfile, int depth) const; + + virtual const char* Parse(const char* p, TiXmlParsingData* data, TiXmlEncoding encoding); + + virtual const TiXmlUnknown* ToUnknown() const { + return this; + } ///< Cast to a more defined type. Will return null not of the requested type. + virtual TiXmlUnknown* ToUnknown() { + return this; + } ///< Cast to a more defined type. Will return null not of the requested type. + + /** Walk the XML tree visiting this node and all of its children. + */ + virtual bool Accept(TiXmlVisitor* content) const; protected: - void CopyTo( TiXmlUnknown* target ) const; + void CopyTo(TiXmlUnknown* target) const; - #ifdef TIXML_USE_STL - virtual void StreamIn( std::istream * in, TIXML_STRING * tag ); - #endif +#ifdef TIXML_USE_STL + virtual void StreamIn(std::istream * in, TIXML_STRING * tag); +#endif private: }; - /** Always the top level node. A document binds together all the - XML pieces. It can be saved, loaded, and printed to the screen. - The 'value' of a document node is the xml file name. -*/ -class TiXmlDocument : public TiXmlNode -{ + XML pieces. It can be saved, loaded, and printed to the screen. + The 'value' of a document node is the xml file name. + */ +class TiXmlDocument: public TiXmlNode { public: - /// Create an empty document, that has no name. - TiXmlDocument(); - /// Create a document with a name. The name of the document is also the filename of the xml. - TiXmlDocument( const char * documentName ); - - #ifdef TIXML_USE_STL - /// Constructor. - TiXmlDocument( const std::string& documentName ); - #endif - - TiXmlDocument( const TiXmlDocument& copy ); - void operator=( const TiXmlDocument& copy ); - - virtual ~TiXmlDocument() {} - - /** Load a file using the current document value. - Returns true if successful. Will delete any existing - document data before loading. - */ - bool LoadFile( TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING ); - /// Save a file using the current document value. Returns true if successful. - bool SaveFile() const; - /// Load a file using the given filename. Returns true if successful. - bool LoadFile( const char * filename, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING ); - /// Save a file using the given filename. Returns true if successful. - bool SaveFile( const char * filename ) const; - /** Load a file using the given FILE*. Returns true if successful. Note that this method - doesn't stream - the entire object pointed at by the FILE* - will be interpreted as an XML file. TinyXML doesn't stream in XML from the current - file location. Streaming may be added in the future. - */ - bool LoadFile( FILE*, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING ); - /// Save a file using the given FILE*. Returns true if successful. - bool SaveFile( FILE* ) const; - - #ifdef TIXML_USE_STL - bool LoadFile( const std::string& filename, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING ) ///< STL std::string version. - { + /// Create an empty document, that has no name. + TiXmlDocument(); + /// Create a document with a name. The name of the document is also the filename of the xml. + TiXmlDocument(const char * documentName); + +#ifdef TIXML_USE_STL + /// Constructor. + TiXmlDocument(const std::string& documentName); +#endif + + TiXmlDocument(const TiXmlDocument& copy); + void operator=(const TiXmlDocument& copy); + + virtual ~TiXmlDocument() { + } + + /** Load a file using the current document value. + Returns true if successful. Will delete any existing + document data before loading. + */ + bool LoadFile(TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING); + /// Save a file using the current document value. Returns true if successful. + bool SaveFile() const; + /// Load a file using the given filename. Returns true if successful. + bool LoadFile(const char * filename, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING); + /// Save a file using the given filename. Returns true if successful. + bool SaveFile(const char * filename) const; + /** Load a file using the given FILE*. Returns true if successful. Note that this method + doesn't stream - the entire object pointed at by the FILE* + will be interpreted as an XML file. TinyXML doesn't stream in XML from the current + file location. Streaming may be added in the future. + */ + bool LoadFile(FILE*, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING); + /// Save a file using the given FILE*. Returns true if successful. + bool SaveFile(FILE*) const; + +#ifdef TIXML_USE_STL + bool LoadFile(const std::string& filename, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING) ///< STL std::string version. + { // StringToBuffer f( filename ); // return ( f.buffer && LoadFile( f.buffer, encoding )); - return LoadFile( filename.c_str(), encoding ); - } - bool SaveFile( const std::string& filename ) const ///< STL std::string version. - { + return LoadFile(filename.c_str(), encoding); + } + bool SaveFile(const std::string& filename) const ///< STL std::string version. + { // StringToBuffer f( filename ); // return ( f.buffer && SaveFile( f.buffer )); - return SaveFile( filename.c_str() ); - } - #endif - - /** Parse the given null terminated block of xml data. Passing in an encoding to this - method (either TIXML_ENCODING_LEGACY or TIXML_ENCODING_UTF8 will force TinyXml - to use that encoding, regardless of what TinyXml might otherwise try to detect. - */ - virtual const char* Parse( const char* p, TiXmlParsingData* data = 0, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING ); - - /** Get the root element -- the only top level element -- of the document. - In well formed XML, there should only be one. TinyXml is tolerant of - multiple elements at the document level. - */ - const TiXmlElement* RootElement() const { return FirstChildElement(); } - TiXmlElement* RootElement() { return FirstChildElement(); } - - /** If an error occurs, Error will be set to true. Also, - - The ErrorId() will contain the integer identifier of the error (not generally useful) - - The ErrorDesc() method will return the name of the error. (very useful) - - The ErrorRow() and ErrorCol() will return the location of the error (if known) - */ - bool Error() const { return error; } - - /// Contains a textual (english) description of the error if one occurs. - const char * ErrorDesc() const { return errorDesc.c_str (); } - - /** Generally, you probably want the error string ( ErrorDesc() ). But if you - prefer the ErrorId, this function will fetch it. - */ - int ErrorId() const { return errorId; } - - /** Returns the location (if known) of the error. The first column is column 1, - and the first row is row 1. A value of 0 means the row and column wasn't applicable - (memory errors, for example, have no row/column) or the parser lost the error. (An - error in the error reporting, in that case.) - - @sa SetTabSize, Row, Column - */ - int ErrorRow() const { return errorLocation.row+1; } - int ErrorCol() const { return errorLocation.col+1; } ///< The column where the error occured. See ErrorRow() - - /** SetTabSize() allows the error reporting functions (ErrorRow() and ErrorCol()) - to report the correct values for row and column. It does not change the output - or input in any way. - - By calling this method, with a tab size - greater than 0, the row and column of each node and attribute is stored - when the file is loaded. Very useful for tracking the DOM back in to - the source file. - - The tab size is required for calculating the location of nodes. If not - set, the default of 4 is used. The tabsize is set per document. Setting - the tabsize to 0 disables row/column tracking. - - Note that row and column tracking is not supported when using operator>>. - - The tab size needs to be enabled before the parse or load. Correct usage: - @verbatim - TiXmlDocument doc; - doc.SetTabSize( 8 ); - doc.Load( "myfile.xml" ); - @endverbatim - - @sa Row, Column - */ - void SetTabSize( int _tabsize ) { tabsize = _tabsize; } - - int TabSize() const { return tabsize; } - - /** If you have handled the error, it can be reset with this call. The error - state is automatically cleared if you Parse a new XML block. - */ - void ClearError() { error = false; - errorId = 0; - errorDesc = ""; - errorLocation.row = errorLocation.col = 0; - //errorLocation.last = 0; - } - - /** Write the document to standard out using formatted printing ("pretty print"). */ - void Print() const { Print( stdout, 0 ); } - - /* Write the document to a string using formatted printing ("pretty print"). This - will allocate a character array (new char[]) and return it as a pointer. The - calling code pust call delete[] on the return char* to avoid a memory leak. - */ - //char* PrintToMemory() const; - - /// Print this Document to a FILE stream. - virtual void Print( FILE* cfile, int depth = 0 ) const; - // [internal use] - void SetError( int err, const char* errorLocation, TiXmlParsingData* prevData, TiXmlEncoding encoding ); - - virtual const TiXmlDocument* ToDocument() const { return this; } ///< Cast to a more defined type. Will return null not of the requested type. - virtual TiXmlDocument* ToDocument() { return this; } ///< Cast to a more defined type. Will return null not of the requested type. - - /** Walk the XML tree visiting this node and all of its children. - */ - virtual bool Accept( TiXmlVisitor* content ) const; - -protected : - // [internal use] - virtual TiXmlNode* Clone() const; - #ifdef TIXML_USE_STL - virtual void StreamIn( std::istream * in, TIXML_STRING * tag ); - #endif + return SaveFile(filename.c_str()); + } +#endif + + /** Parse the given null terminated block of xml data. Passing in an encoding to this + method (either TIXML_ENCODING_LEGACY or TIXML_ENCODING_UTF8 will force TinyXml + to use that encoding, regardless of what TinyXml might otherwise try to detect. + */ + virtual const char* Parse(const char* p, TiXmlParsingData* data = 0, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING); + + /** Get the root element -- the only top level element -- of the document. + In well formed XML, there should only be one. TinyXml is tolerant of + multiple elements at the document level. + */ + const TiXmlElement* RootElement() const { + return FirstChildElement(); + } + TiXmlElement* RootElement() { + return FirstChildElement(); + } + + /** If an error occurs, Error will be set to true. Also, + - The ErrorId() will contain the integer identifier of the error (not generally useful) + - The ErrorDesc() method will return the name of the error. (very useful) + - The ErrorRow() and ErrorCol() will return the location of the error (if known) + */ + bool Error() const { + return error; + } + + /// Contains a textual (english) description of the error if one occurs. + const char * ErrorDesc() const { + return errorDesc.c_str(); + } + + /** Generally, you probably want the error string ( ErrorDesc() ). But if you + prefer the ErrorId, this function will fetch it. + */ + int ErrorId() const { + return errorId; + } + + /** Returns the location (if known) of the error. The first column is column 1, + and the first row is row 1. A value of 0 means the row and column wasn't applicable + (memory errors, for example, have no row/column) or the parser lost the error. (An + error in the error reporting, in that case.) + + @sa SetTabSize, Row, Column + */ + int ErrorRow() const { + return errorLocation.row + 1; + } + int ErrorCol() const { + return errorLocation.col + 1; + } ///< The column where the error occured. See ErrorRow() + + /** SetTabSize() allows the error reporting functions (ErrorRow() and ErrorCol()) + to report the correct values for row and column. It does not change the output + or input in any way. + + By calling this method, with a tab size + greater than 0, the row and column of each node and attribute is stored + when the file is loaded. Very useful for tracking the DOM back in to + the source file. + + The tab size is required for calculating the location of nodes. If not + set, the default of 4 is used. The tabsize is set per document. Setting + the tabsize to 0 disables row/column tracking. + + Note that row and column tracking is not supported when using operator>>. + + The tab size needs to be enabled before the parse or load. Correct usage: + @verbatim + TiXmlDocument doc; + doc.SetTabSize( 8 ); + doc.Load( "myfile.xml" ); + @endverbatim + + @sa Row, Column + */ + void SetTabSize(int _tabsize) { + tabsize = _tabsize; + } + + int TabSize() const { + return tabsize; + } + + /** If you have handled the error, it can be reset with this call. The error + state is automatically cleared if you Parse a new XML block. + */ + void ClearError() { + error = false; + errorId = 0; + errorDesc = ""; + errorLocation.row = errorLocation.col = 0; + //errorLocation.last = 0; + } + + /** Write the document to standard out using formatted printing ("pretty print"). */ + void Print() const { + Print(stdout, 0); + } + + /* Write the document to a string using formatted printing ("pretty print"). This + will allocate a character array (new char[]) and return it as a pointer. The + calling code pust call delete[] on the return char* to avoid a memory leak. + */ + //char* PrintToMemory() const; + /// Print this Document to a FILE stream. + virtual void Print(FILE* cfile, int depth = 0) const; + // [internal use] + void SetError(int err, const char* errorLocation, TiXmlParsingData* prevData, TiXmlEncoding encoding); + + virtual const TiXmlDocument* ToDocument() const { + return this; + } ///< Cast to a more defined type. Will return null not of the requested type. + virtual TiXmlDocument* ToDocument() { + return this; + } ///< Cast to a more defined type. Will return null not of the requested type. + + /** Walk the XML tree visiting this node and all of its children. + */ + virtual bool Accept(TiXmlVisitor* content) const; + +protected: + // [internal use] + virtual TiXmlNode* Clone() const; +#ifdef TIXML_USE_STL + virtual void StreamIn(std::istream * in, TIXML_STRING * tag); +#endif private: - void CopyTo( TiXmlDocument* target ) const; - - bool error; - int errorId; - TIXML_STRING errorDesc; - int tabsize; - TiXmlCursor errorLocation; - bool useMicrosoftBOM; // the UTF-8 BOM were found when read. Note this, and try to write. -}; + void CopyTo(TiXmlDocument* target) const; + bool error; + int errorId;TIXML_STRING errorDesc; + int tabsize; + TiXmlCursor errorLocation; + bool useMicrosoftBOM; // the UTF-8 BOM were found when read. Note this, and try to write. +}; /** - A TiXmlHandle is a class that wraps a node pointer with null checks; this is - an incredibly useful thing. Note that TiXmlHandle is not part of the TinyXml - DOM structure. It is a separate utility class. - - Take an example: - @verbatim - <Document> - <Element attributeA = "valueA"> - <Child attributeB = "value1" /> - <Child attributeB = "value2" /> - </Element> - <Document> - @endverbatim - - Assuming you want the value of "attributeB" in the 2nd "Child" element, it's very - easy to write a *lot* of code that looks like: - - @verbatim - TiXmlElement* root = document.FirstChildElement( "Document" ); - if ( root ) - { - TiXmlElement* element = root->FirstChildElement( "Element" ); - if ( element ) - { - TiXmlElement* child = element->FirstChildElement( "Child" ); - if ( child ) - { - TiXmlElement* child2 = child->NextSiblingElement( "Child" ); - if ( child2 ) - { - // Finally do something useful. - @endverbatim - - And that doesn't even cover "else" cases. TiXmlHandle addresses the verbosity - of such code. A TiXmlHandle checks for null pointers so it is perfectly safe - and correct to use: - - @verbatim - TiXmlHandle docHandle( &document ); - TiXmlElement* child2 = docHandle.FirstChild( "Document" ).FirstChild( "Element" ).Child( "Child", 1 ).ToElement(); - if ( child2 ) - { - // do something useful - @endverbatim - - Which is MUCH more concise and useful. - - It is also safe to copy handles - internally they are nothing more than node pointers. - @verbatim - TiXmlHandle handleCopy = handle; - @endverbatim - - What they should not be used for is iteration: - - @verbatim - int i=0; - while ( true ) - { - TiXmlElement* child = docHandle.FirstChild( "Document" ).FirstChild( "Element" ).Child( "Child", i ).ToElement(); - if ( !child ) - break; - // do something - ++i; - } - @endverbatim - - It seems reasonable, but it is in fact two embedded while loops. The Child method is - a linear walk to find the element, so this code would iterate much more than it needs - to. Instead, prefer: - - @verbatim - TiXmlElement* child = docHandle.FirstChild( "Document" ).FirstChild( "Element" ).FirstChild( "Child" ).ToElement(); - - for( child; child; child=child->NextSiblingElement() ) - { - // do something - } - @endverbatim -*/ -class TiXmlHandle -{ + A TiXmlHandle is a class that wraps a node pointer with null checks; this is + an incredibly useful thing. Note that TiXmlHandle is not part of the TinyXml + DOM structure. It is a separate utility class. + + Take an example: + @verbatim + <Document> + <Element attributeA = "valueA"> + <Child attributeB = "value1" /> + <Child attributeB = "value2" /> + </Element> + <Document> + @endverbatim + + Assuming you want the value of "attributeB" in the 2nd "Child" element, it's very + easy to write a *lot* of code that looks like: + + @verbatim + TiXmlElement* root = document.FirstChildElement( "Document" ); + if ( root ) + { + TiXmlElement* element = root->FirstChildElement( "Element" ); + if ( element ) + { + TiXmlElement* child = element->FirstChildElement( "Child" ); + if ( child ) + { + TiXmlElement* child2 = child->NextSiblingElement( "Child" ); + if ( child2 ) + { + // Finally do something useful. + @endverbatim + + And that doesn't even cover "else" cases. TiXmlHandle addresses the verbosity + of such code. A TiXmlHandle checks for null pointers so it is perfectly safe + and correct to use: + + @verbatim + TiXmlHandle docHandle( &document ); + TiXmlElement* child2 = docHandle.FirstChild( "Document" ).FirstChild( "Element" ).Child( "Child", 1 ).ToElement(); + if ( child2 ) + { + // do something useful + @endverbatim + + Which is MUCH more concise and useful. + + It is also safe to copy handles - internally they are nothing more than node pointers. + @verbatim + TiXmlHandle handleCopy = handle; + @endverbatim + + What they should not be used for is iteration: + + @verbatim + int i=0; + while ( true ) + { + TiXmlElement* child = docHandle.FirstChild( "Document" ).FirstChild( "Element" ).Child( "Child", i ).ToElement(); + if ( !child ) + break; + // do something + ++i; + } + @endverbatim + + It seems reasonable, but it is in fact two embedded while loops. The Child method is + a linear walk to find the element, so this code would iterate much more than it needs + to. Instead, prefer: + + @verbatim + TiXmlElement* child = docHandle.FirstChild( "Document" ).FirstChild( "Element" ).FirstChild( "Child" ).ToElement(); + + for( child; child; child=child->NextSiblingElement() ) + { + // do something + } + @endverbatim + */ +class TiXmlHandle { public: - /// Create a handle from any node (at any depth of the tree.) This can be a null pointer. - TiXmlHandle( TiXmlNode* _node ) { this->node = _node; } - /// Copy constructor - TiXmlHandle( const TiXmlHandle& ref ) { this->node = ref.node; } - TiXmlHandle operator=( const TiXmlHandle& ref ) { this->node = ref.node; return *this; } - - /// Return a handle to the first child node. - TiXmlHandle FirstChild() const; - /// Return a handle to the first child node with the given name. - TiXmlHandle FirstChild( const char * value ) const; - /// Return a handle to the first child element. - TiXmlHandle FirstChildElement() const; - /// Return a handle to the first child element with the given name. - TiXmlHandle FirstChildElement( const char * value ) const; - - /** Return a handle to the "index" child with the given name. - The first child is 0, the second 1, etc. - */ - TiXmlHandle Child( const char* value, int index ) const; - /** Return a handle to the "index" child. - The first child is 0, the second 1, etc. - */ - TiXmlHandle Child( int index ) const; - /** Return a handle to the "index" child element with the given name. - The first child element is 0, the second 1, etc. Note that only TiXmlElements - are indexed: other types are not counted. - */ - TiXmlHandle ChildElement( const char* value, int index ) const; - /** Return a handle to the "index" child element. - The first child element is 0, the second 1, etc. Note that only TiXmlElements - are indexed: other types are not counted. - */ - TiXmlHandle ChildElement( int index ) const; - - #ifdef TIXML_USE_STL - TiXmlHandle FirstChild( const std::string& _value ) const { return FirstChild( _value.c_str() ); } - TiXmlHandle FirstChildElement( const std::string& _value ) const { return FirstChildElement( _value.c_str() ); } - - TiXmlHandle Child( const std::string& _value, int index ) const { return Child( _value.c_str(), index ); } - TiXmlHandle ChildElement( const std::string& _value, int index ) const { return ChildElement( _value.c_str(), index ); } - #endif - - /** Return the handle as a TiXmlNode. This may return null. - */ - TiXmlNode* ToNode() const { return node; } - /** Return the handle as a TiXmlElement. This may return null. - */ - TiXmlElement* ToElement() const { return ( ( node && node->ToElement() ) ? node->ToElement() : 0 ); } - /** Return the handle as a TiXmlText. This may return null. - */ - TiXmlText* ToText() const { return ( ( node && node->ToText() ) ? node->ToText() : 0 ); } - /** Return the handle as a TiXmlUnknown. This may return null. - */ - TiXmlUnknown* ToUnknown() const { return ( ( node && node->ToUnknown() ) ? node->ToUnknown() : 0 ); } - - /** @deprecated use ToNode. - Return the handle as a TiXmlNode. This may return null. - */ - TiXmlNode* Node() const { return ToNode(); } - /** @deprecated use ToElement. - Return the handle as a TiXmlElement. This may return null. - */ - TiXmlElement* Element() const { return ToElement(); } - /** @deprecated use ToText() - Return the handle as a TiXmlText. This may return null. - */ - TiXmlText* Text() const { return ToText(); } - /** @deprecated use ToUnknown() - Return the handle as a TiXmlUnknown. This may return null. - */ - TiXmlUnknown* Unknown() const { return ToUnknown(); } + /// Create a handle from any node (at any depth of the tree.) This can be a null pointer. + TiXmlHandle(TiXmlNode* _node) { + this->node = _node; + } + /// Copy constructor + TiXmlHandle(const TiXmlHandle& ref) { + this->node = ref.node; + } + TiXmlHandle operator=(const TiXmlHandle& ref) { + this->node = ref.node; + return *this; + } + + /// Return a handle to the first child node. + TiXmlHandle FirstChild() const; + /// Return a handle to the first child node with the given name. + TiXmlHandle FirstChild(const char * value) const; + /// Return a handle to the first child element. + TiXmlHandle FirstChildElement() const; + /// Return a handle to the first child element with the given name. + TiXmlHandle FirstChildElement(const char * value) const; + + /** Return a handle to the "index" child with the given name. + The first child is 0, the second 1, etc. + */ + TiXmlHandle Child(const char* value, int index) const; + /** Return a handle to the "index" child. + The first child is 0, the second 1, etc. + */ + TiXmlHandle Child(int index) const; + /** Return a handle to the "index" child element with the given name. + The first child element is 0, the second 1, etc. Note that only TiXmlElements + are indexed: other types are not counted. + */ + TiXmlHandle ChildElement(const char* value, int index) const; + /** Return a handle to the "index" child element. + The first child element is 0, the second 1, etc. Note that only TiXmlElements + are indexed: other types are not counted. + */ + TiXmlHandle ChildElement(int index) const; + +#ifdef TIXML_USE_STL + TiXmlHandle FirstChild(const std::string& _value) const { + return FirstChild(_value.c_str()); + } + TiXmlHandle FirstChildElement(const std::string& _value) const { + return FirstChildElement(_value.c_str()); + } + + TiXmlHandle Child(const std::string& _value, int index) const { + return Child(_value.c_str(), index); + } + TiXmlHandle ChildElement(const std::string& _value, int index) const { + return ChildElement(_value.c_str(), index); + } +#endif + + /** Return the handle as a TiXmlNode. This may return null. + */ + TiXmlNode* ToNode() const { + return node; + } + /** Return the handle as a TiXmlElement. This may return null. + */ + TiXmlElement* ToElement() const { + return ((node && node->ToElement()) ? node->ToElement() : 0); + } + /** Return the handle as a TiXmlText. This may return null. + */ + TiXmlText* ToText() const { + return ((node && node->ToText()) ? node->ToText() : 0); + } + /** Return the handle as a TiXmlUnknown. This may return null. + */ + TiXmlUnknown* ToUnknown() const { + return ((node && node->ToUnknown()) ? node->ToUnknown() : 0); + } + + /** @deprecated use ToNode. + Return the handle as a TiXmlNode. This may return null. + */ + TiXmlNode* Node() const { + return ToNode(); + } + /** @deprecated use ToElement. + Return the handle as a TiXmlElement. This may return null. + */ + TiXmlElement* Element() const { + return ToElement(); + } + /** @deprecated use ToText() + Return the handle as a TiXmlText. This may return null. + */ + TiXmlText* Text() const { + return ToText(); + } + /** @deprecated use ToUnknown() + Return the handle as a TiXmlUnknown. This may return null. + */ + TiXmlUnknown* Unknown() const { + return ToUnknown(); + } private: - TiXmlNode* node; + TiXmlNode* node; }; - /** Print to memory functionality. The TiXmlPrinter is useful when you need to: - -# Print to memory (especially in non-STL mode) - -# Control formatting (line endings, etc.) - - When constructed, the TiXmlPrinter is in its default "pretty printing" mode. - Before calling Accept() you can call methods to control the printing - of the XML document. After TiXmlNode::Accept() is called, the printed document can - be accessed via the CStr(), Str(), and Size() methods. - - TiXmlPrinter uses the Visitor API. - @verbatim - TiXmlPrinter printer; - printer.SetIndent( "\t" ); - - doc.Accept( &printer ); - fprintf( stdout, "%s", printer.CStr() ); - @endverbatim -*/ -class TiXmlPrinter : public TiXmlVisitor -{ + -# Print to memory (especially in non-STL mode) + -# Control formatting (line endings, etc.) + + When constructed, the TiXmlPrinter is in its default "pretty printing" mode. + Before calling Accept() you can call methods to control the printing + of the XML document. After TiXmlNode::Accept() is called, the printed document can + be accessed via the CStr(), Str(), and Size() methods. + + TiXmlPrinter uses the Visitor API. + @verbatim + TiXmlPrinter printer; + printer.SetIndent( "\t" ); + + doc.Accept( &printer ); + fprintf( stdout, "%s", printer.CStr() ); + @endverbatim + */ +class TiXmlPrinter: public TiXmlVisitor { public: - TiXmlPrinter() : depth( 0 ), simpleTextPrint( false ), - buffer(), indent( " " ), lineBreak( "\n" ) {} - - virtual bool VisitEnter( const TiXmlDocument& doc ); - virtual bool VisitExit( const TiXmlDocument& doc ); - - virtual bool VisitEnter( const TiXmlElement& element, const TiXmlAttribute* firstAttribute ); - virtual bool VisitExit( const TiXmlElement& element ); - - virtual bool Visit( const TiXmlDeclaration& declaration ); - virtual bool Visit( const TiXmlText& text ); - virtual bool Visit( const TiXmlComment& comment ); - virtual bool Visit( const TiXmlUnknown& unknown ); - - /** Set the indent characters for printing. By default 4 spaces - but tab (\t) is also useful, or null/empty string for no indentation. - */ - void SetIndent( const char* _indent ) { indent = _indent ? _indent : "" ; } - /// Query the indention string. - const char* Indent() { return indent.c_str(); } - /** Set the line breaking string. By default set to newline (\n). - Some operating systems prefer other characters, or can be - set to the null/empty string for no indenation. - */ - void SetLineBreak( const char* _lineBreak ) { lineBreak = _lineBreak ? _lineBreak : ""; } - /// Query the current line breaking string. - const char* LineBreak() { return lineBreak.c_str(); } - - /** Switch over to "stream printing" which is the most dense formatting without - linebreaks. Common when the XML is needed for network transmission. - */ - void SetStreamPrinting() { indent = ""; - lineBreak = ""; - } - /// Return the result. - const char* CStr() { return buffer.c_str(); } - /// Return the length of the result string. - size_t Size() { return buffer.size(); } - - #ifdef TIXML_USE_STL - /// Return the result. - const std::string& Str() { return buffer; } - #endif + TiXmlPrinter() + : depth(0), simpleTextPrint(false), buffer(), indent(" "), lineBreak("\n") { + } + + virtual bool VisitEnter(const TiXmlDocument& doc); + virtual bool VisitExit(const TiXmlDocument& doc); + + virtual bool VisitEnter(const TiXmlElement& element, const TiXmlAttribute* firstAttribute); + virtual bool VisitExit(const TiXmlElement& element); + + virtual bool Visit(const TiXmlDeclaration& declaration); + virtual bool Visit(const TiXmlText& text); + virtual bool Visit(const TiXmlComment& comment); + virtual bool Visit(const TiXmlUnknown& unknown); + + /** Set the indent characters for printing. By default 4 spaces + but tab (\t) is also useful, or null/empty string for no indentation. + */ + void SetIndent(const char* _indent) { + indent = _indent ? _indent : ""; + } + /// Query the indention string. + const char* Indent() { + return indent.c_str(); + } + /** Set the line breaking string. By default set to newline (\n). + Some operating systems prefer other characters, or can be + set to the null/empty string for no indenation. + */ + void SetLineBreak(const char* _lineBreak) { + lineBreak = _lineBreak ? _lineBreak : ""; + } + /// Query the current line breaking string. + const char* LineBreak() { + return lineBreak.c_str(); + } + + /** Switch over to "stream printing" which is the most dense formatting without + linebreaks. Common when the XML is needed for network transmission. + */ + void SetStreamPrinting() { + indent = ""; + lineBreak = ""; + } + /// Return the result. + const char* CStr() { + return buffer.c_str(); + } + /// Return the length of the result string. + size_t Size() { + return buffer.size(); + } + +#ifdef TIXML_USE_STL + /// Return the result. + const std::string& Str() { + return buffer; + } +#endif private: - void DoIndent() { - for( int i=0; i<depth; ++i ) - buffer += indent; - } - void DoLineBreak() { - buffer += lineBreak; - } - - int depth; - bool simpleTextPrint; - TIXML_STRING buffer; - TIXML_STRING indent; - TIXML_STRING lineBreak; + void DoIndent() { + for (int i = 0; i < depth; ++i) + buffer += indent; + } + void DoLineBreak() { + buffer += lineBreak; + } + + int depth; + bool simpleTextPrint;TIXML_STRING buffer;TIXML_STRING indent;TIXML_STRING lineBreak; }; - #ifdef _MSC_VER #pragma warning( pop ) #endif diff --git a/DDCore/src/Detector.cpp b/DDCore/src/Detector.cpp index 1559c1642..3e7888735 100644 --- a/DDCore/src/Detector.cpp +++ b/DDCore/src/Detector.cpp @@ -20,9 +20,9 @@ using namespace DD4hep::Geometry; namespace { struct ExtensionEntry { - void* (*copy)(const void*,DetElement); - void (*destruct)(void*); - int id; + void* (*copy)(const void*, DetElement); + void (*destruct)(void*); + int id; }; typedef map<const type_info*, ExtensionEntry> ExtensionMap; static int s_extensionID = 0; @@ -34,27 +34,28 @@ namespace { static ExtensionMap s_map; return s_map; } -}; +} +; static bool find_child(TGeoNode* parent, TGeoNode* child, vector<TGeoNode*>& path) { - if ( parent && child ) { - if ( parent == child ) { + if (parent && child) { + if (parent == child) { path.push_back(child); return true; } TIter next(parent->GetVolume()->GetNodes()); - for (TGeoNode *daughter=(TGeoNode*)next(); daughter; daughter=(TGeoNode*)next() ) { - if ( daughter == child ) { - path.push_back(daughter); - return true; + for (TGeoNode *daughter = (TGeoNode*) next(); daughter; daughter = (TGeoNode*) next()) { + if (daughter == child) { + path.push_back(daughter); + return true; } } next.Reset(); - for (TGeoNode *daughter=(TGeoNode*)next(); daughter; daughter=(TGeoNode*)next() ) { + for (TGeoNode *daughter = (TGeoNode*) next(); daughter; daughter = (TGeoNode*) next()) { bool res = find_child(daughter, child, path); - if ( res ) { - path.push_back(daughter); - return res; + if (res) { + path.push_back(daughter); + return res; } } } @@ -62,14 +63,14 @@ static bool find_child(TGeoNode* parent, TGeoNode* child, vector<TGeoNode*>& pat } static bool collect_detector_nodes(const vector<TGeoNode*>& det_nodes, vector<TGeoNode*>& nodes) { - if ( det_nodes.size() < 1 ) { + if (det_nodes.size() < 1) { return false; } - if ( det_nodes.size() < 2 ) { + if (det_nodes.size() < 2) { return true; } - for(size_t i=0, n=det_nodes.size(); i<n-1; ++i) { - if ( !find_child(det_nodes[i+1],det_nodes[i],nodes) ) { + for (size_t i = 0, n = det_nodes.size(); i < n - 1; ++i) { + if (!find_child(det_nodes[i + 1], det_nodes[i], nodes)) { return false; } } @@ -77,17 +78,18 @@ static bool collect_detector_nodes(const vector<TGeoNode*>& det_nodes, vector<TG } /// Create cached matrix to transform to positions to an upper level DetElement -static TGeoHMatrix* create_trafo(const vector<TGeoNode*>& det_nodes) { - if ( det_nodes.size() < 2 ) { +static TGeoHMatrix* create_trafo(const vector<TGeoNode*>& det_nodes) { + if (det_nodes.size() < 2) { return new TGeoHMatrix(*gGeoIdentity); } vector<TGeoNode*> nodes; - if ( !collect_detector_nodes(det_nodes,nodes) ) { - throw runtime_error("DD4hep: DetElement cannot connect "+string(det_nodes[0]->GetName())+ - " to child "+string(det_nodes[1]->GetName())); + if (!collect_detector_nodes(det_nodes, nodes)) { + throw runtime_error( + "DD4hep: DetElement cannot connect " + string(det_nodes[0]->GetName()) + " to child " + + string(det_nodes[1]->GetName())); } TGeoHMatrix* mat = new TGeoHMatrix(*gGeoIdentity); - for(vector<TGeoNode*>::const_iterator i=nodes.begin(); i!=nodes.end(); ++i) { + for (vector<TGeoNode*>::const_iterator i = nodes.begin(); i != nodes.end(); ++i) { TGeoMatrix* m = (*i)->GetMatrix(); mat->MultiplyLeft(m); } @@ -95,10 +97,10 @@ static TGeoHMatrix* create_trafo(const vector<TGeoNode*>& det_nodes) { } /// Top detector element -static DetElement _top(DetElement o, vector<TGeoNode*>& det_nodes) { +static DetElement _top(DetElement o, vector<TGeoNode*>& det_nodes) { DetElement par = o, pp = o; - while( par.isValid() ) { - if ( par.placement().isValid() ) { + while (par.isValid()) { + if (par.placement().isValid()) { det_nodes.push_back(par.placement().ptr()); pp = par; } @@ -108,35 +110,35 @@ static DetElement _top(DetElement o, vector<TGeoNode*>& det_nodes) { } /// Top detector element -static DetElement _par(DetElement o, DetElement top, vector<TGeoNode*>& det_nodes) { +static DetElement _par(DetElement o, DetElement top, vector<TGeoNode*>& det_nodes) { DetElement par = o, pp = o; - while( par.isValid() ) { - if ( par.placement().isValid() ) { + while (par.isValid()) { + if (par.placement().isValid()) { det_nodes.push_back(par.placement().ptr()); pp = par; } - if ( par.ptr() == top.ptr() ) break; + if (par.ptr() == top.ptr()) + break; par = par.parent(); } - if ( pp.ptr() == top.ptr() ) return pp; + if (pp.ptr() == top.ptr()) + return pp; return DetElement(); } /// Default constructor -DetElement::Object::Object() - : TNamed(), magic(magic_word()), id(0), combineHits(0),// readout(), - alignment(), placement(), parent(), children(), - worldTrafo(0), parentTrafo(0), referenceTrafo(0) -{ +DetElement::Object::Object() + : TNamed(), magic(magic_word()), id(0), combineHits(0), // readout(), + alignment(), placement(), parent(), children(), worldTrafo(0), parentTrafo(0), referenceTrafo(0) { InstanceCount::increment(this); } /// Internal object destructor: release extension object(s) DetElement::Object::~Object() { - for_each(children.begin(),children.end(),destroyHandles(children)); - deletePtr(worldTrafo); - deletePtr(parentTrafo); - deletePtr(referenceTrafo); + for_each(children.begin(), children.end(), destroyHandles(children)); + deletePtr (worldTrafo); + deletePtr (parentTrafo); + deletePtr (referenceTrafo); volume.clear(); //readout.clear(); alignment.clear(); @@ -144,13 +146,14 @@ DetElement::Object::~Object() { placement.clear(); parent.clear(); ExtensionMap& m = detelement_extensions(); - for(Extensions::iterator i = extensions.begin(); i!=extensions.end(); ++i) { + for (Extensions::iterator i = extensions.begin(); i != extensions.end(); ++i) { void* ptr = (*i).second; - if ( ptr ) { + if (ptr) { ExtensionMap::iterator j = m.find((*i).first); - if ( j != m.end() ) { - ExtensionEntry& e = (*j).second; - if ( e.destruct ) (*(e.destruct))(ptr); + if (j != m.end()) { + ExtensionEntry& e = (*j).second; + if (e.destruct) + (*(e.destruct))(ptr); } } } @@ -159,39 +162,39 @@ DetElement::Object::~Object() { } /// Deep object copy to replicate DetElement trees e.g. for reflection -DetElement::Object* DetElement::Object::clone(int new_id, int flag) const { +DetElement::Object* DetElement::Object::clone(int new_id, int flag) const { Object* obj = new Object(); const ExtensionMap& m = detelement_extensions(); Ref_t det(obj); - obj->id = new_id; - obj->combineHits = combineHits; + obj->id = new_id; + obj->combineHits = combineHits; //obj->readout = readout; - obj->volume = volume; - obj->alignment = Alignment(); - obj->conditions = Conditions(); - obj->parent = DetElement(); - obj->placement = ((flag©_PLACEMENT) == COPY_PLACEMENT) ? placement : PlacedVolume(); + obj->volume = volume; + obj->alignment = Alignment(); + obj->conditions = Conditions(); + obj->parent = DetElement(); + obj->placement = ((flag & COPY_PLACEMENT) == COPY_PLACEMENT) ? placement : PlacedVolume(); // This implicitly assumes that the children do not access the parent's extensions! obj->extensions.clear(); - for(DetElement::Extensions::const_iterator i=extensions.begin(); i != extensions.end(); ++i) { + for (DetElement::Extensions::const_iterator i = extensions.begin(); i != extensions.end(); ++i) { const type_info* info = (*i).first; ExtensionMap::const_iterator j = m.find(info); const ExtensionEntry& e = (*j).second; - obj->extensions[info] = (*(e.copy))((*i).second,det); + obj->extensions[info] = (*(e.copy))((*i).second, det); } obj->children.clear(); - for(DetElement::Children::const_iterator i=children.begin(); i != children.end(); ++i) { + for (DetElement::Children::const_iterator i = children.begin(); i != children.end(); ++i) { const TNamed* pc = (*i).second.ptr(); const DetElement::Object& d = (*i).second._data(); - DetElement child(d.clone(d.id,COPY_PLACEMENT),pc->GetName(),pc->GetTitle()); - pair<Children::iterator,bool> r = obj->children.insert(make_pair(child.name(),child)); - if ( r.second ) { + DetElement child(d.clone(d.id, COPY_PLACEMENT), pc->GetName(), pc->GetTitle()); + pair<Children::iterator, bool> r = obj->children.insert(make_pair(child.name(), child)); + if (r.second) { child._data().parent = det; } else { - throw runtime_error("DD4hep: DetElement::copy: Element "+string(child.name())+" is already present [Double-Insert]"); + throw runtime_error("DD4hep: DetElement::copy: Element " + string(child.name()) + " is already present [Double-Insert]"); } } return obj; @@ -209,18 +212,18 @@ DetElement::Object::operator Ref_t() { /// Create cached matrix to transform to world coordinates TGeoMatrix* DetElement::Object::worldTransformation() { - if ( !worldTrafo ) { + if (!worldTrafo) { vector<TGeoNode*> det_nodes; - _top(DetElement(asRef()),det_nodes); + _top(DetElement(asRef()), det_nodes); TGeoHMatrix* mat = create_trafo(det_nodes); worldTrafo = mat; - } + } return worldTrafo; } /// Create cached matrix to transform to parent coordinates TGeoMatrix* DetElement::Object::parentTransformation() { - if ( !parentTrafo ) { + if (!parentTrafo) { vector<TGeoNode*> det_nodes; det_nodes.push_back(placement.ptr()); det_nodes.push_back(DetElement(parent).placement().ptr()); @@ -231,21 +234,22 @@ TGeoMatrix* DetElement::Object::parentTransformation() { /// Create cached matrix to transform to reference coordinates TGeoMatrix* DetElement::Object::referenceTransformation() { - if ( !referenceTrafo ) { + if (!referenceTrafo) { vector<TGeoNode*> nodes; DetElement ref(reference); DetElement self(asRef()); - DetElement elt = _par(self,ref,nodes); - if ( elt.isValid() ) { + DetElement elt = _par(self, ref, nodes); + if (elt.isValid()) { referenceTrafo = create_trafo(nodes); } - else { + else { nodes.clear(); DetElement me(this->asRef()); - DetElement elt = _par(ref,me,nodes); - if ( !elt.isValid() ) { - throw runtime_error("DD4hep: referenceTransformation: No path from "+string(self.name())+ - " to reference element "+string(ref.name())+" present!"); + DetElement elt = _par(ref, me, nodes); + if (!elt.isValid()) { + throw runtime_error( + "DD4hep: referenceTransformation: No path from " + string(self.name()) + " to reference element " + + string(ref.name()) + " present!"); } TGeoMatrix* m = create_trafo(nodes); referenceTrafo = new TGeoHMatrix(m->Inverse()); @@ -256,72 +260,73 @@ TGeoMatrix* DetElement::Object::referenceTransformation() { } /// Constructor for a new subdetector element -DetElement::DetElement(const string& name, const string& type, int id) { - assign(new Object(),name,type); +DetElement::DetElement(const string& name, const string& type, int id) { + assign(new Object(), name, type); object<Object>().id = id; } /// Constructor for a new subdetector element -DetElement::DetElement(const string& name, int id) { - assign(new Object(),name,""); +DetElement::DetElement(const string& name, int id) { + assign(new Object(), name, ""); object<Object>().id = id; } /// Constructor for a new subdetector element -DetElement::DetElement(DetElement parent, const string& name, int id) { - assign(new Object(),name,parent.type()); +DetElement::DetElement(DetElement parent, const string& name, int id) { + assign(new Object(), name, parent.type()); object<Object>().id = id; parent.add(*this); } /// Add an extension object to the detector element -void* DetElement::i_addExtension(void* ptr, const type_info& info, void* (*copy)(const void*,DetElement), void (*destruct)(void*)) { +void* DetElement::i_addExtension(void* ptr, const type_info& info, void* (*copy)(const void*, DetElement), + void (*destruct)(void*)) { Object& o = object<Object>(); Extensions::iterator j = o.extensions.find(&info); - if ( j == o.extensions.end() ) { + if (j == o.extensions.end()) { ExtensionMap& m = detelement_extensions(); ExtensionMap::iterator i = m.find(&info); - if ( i == m.end() ) { + if (i == m.end()) { ExtensionEntry entry; entry.destruct = destruct; entry.copy = copy; entry.id = ++s_extensionID; - m.insert(make_pair(&info,entry)); + m.insert(make_pair(&info, entry)); i = m.find(&info); } ExtensionEntry& e = (*i).second; //cout << "Extension[" << name() << "]:" << ptr << " " << info.name() << endl; return o.extensions[&info] = ptr; } - throw runtime_error("DD4hep: addExtension: The object "+string(name())+ - " already has an extension of type:"+string(info.name())+"."); + throw runtime_error( + "DD4hep: addExtension: The object " + string(name()) + " already has an extension of type:" + string(info.name()) + "."); } /// Access an existing extension object from the detector element -void* DetElement::i_extension(const type_info& info) const { +void* DetElement::i_extension(const type_info& info) const { Object& o = object<Object>(); Extensions::const_iterator j = o.extensions.find(&info); - if ( j != o.extensions.end() ) { + if (j != o.extensions.end()) { return (*j).second; } - throw runtime_error("DD4hep: extension: The object "+string(name())+ - " has no extension of type:"+string(info.name())+"."); + throw runtime_error( + "DD4hep: extension: The object " + string(name()) + " has no extension of type:" + string(info.name()) + "."); } - + /// Access to the full path to the placed object string DetElement::placementPath() const { - if ( isValid() ) { + if (isValid()) { Object& o = object<Object>(); - if ( o.placementPath.empty() ) { + if (o.placementPath.empty()) { string res = ""; vector<TGeoNode*> nodes, path; - _top(*this,nodes); - if ( !collect_detector_nodes(nodes,path) ) { - throw runtime_error("DD4hep: DetElement cannot determine placement path of "+string(name())); + _top(*this, nodes); + if (!collect_detector_nodes(nodes, path)) { + throw runtime_error("DD4hep: DetElement cannot determine placement path of " + string(name())); } path.push_back(gGeoManager->GetTopNode()); - for(vector<TGeoNode*>::const_reverse_iterator i=path.rbegin(); i!=path.rend(); ++i) - res += (string("/")+(*i)->GetName()); + for (vector<TGeoNode*>::const_reverse_iterator i = path.rbegin(); i != path.rend(); ++i) + res += (string("/") + (*i)->GetName()); o.placementPath = res; } return o.placementPath; @@ -330,61 +335,62 @@ string DetElement::placementPath() const { } /// Access detector type (structure, tracker, calorimeter, etc.). -string DetElement::type() const { +string DetElement::type() const { return m_element ? m_element->GetTitle() : ""; } /// Set the type of the sensitive detector -DetElement& DetElement::setType(const string& typ) { - if ( isValid() ) { +DetElement& DetElement::setType(const string& typ) { + if (isValid()) { m_element->SetTitle(typ.c_str()); return *this; } throw runtime_error("DD4hep: DetElement::setType: Self is not defined [Invalid Handle]"); } -string DetElement::path() const { - if ( m_element ) { +string DetElement::path() const { + if (m_element) { Object& o = object<Object>(); - if ( o.path.empty() ) { + if (o.path.empty()) { DetElement par = o.parent; - o.path = par.isValid() ? (par.path()+"/")+name() : string("/") + name(); + o.path = par.isValid() ? (par.path() + "/") + name() : string("/") + name(); } return o.path; } return ""; } -int DetElement::id() const { +int DetElement::id() const { return object<Object>().id; } -bool DetElement::combineHits() const { +bool DetElement::combineHits() const { return object<Object>().combineHits != 0; } -DetElement& DetElement::setCombineHits(bool value, SensitiveDetector& sens) { +DetElement& DetElement::setCombineHits(bool value, SensitiveDetector& sens) { object<Object>().combineHits = value; - if ( sens.isValid() ) sens.setCombineHits(value); + if (sens.isValid()) + sens.setCombineHits(value); return *this; } #if 0 -Readout DetElement::readout() const { +Readout DetElement::readout() const { return object<Object>().readout; } -DetElement& DetElement::setReadout(const Readout& readout) { +DetElement& DetElement::setReadout(const Readout& readout) { object<Object>().readout = readout; return *this; } #endif -const DetElement::Children& DetElement::children() const { +const DetElement::Children& DetElement::children() const { return object<Object>().children; } /// Access to individual children by name DetElement DetElement::child(const string& name) const { - if ( isValid() ) { + if (isValid()) { const Children& c = object<Object>().children; Children::const_iterator i = c.find(name); return i == c.end() ? DetElement() : (*i).second; @@ -394,40 +400,40 @@ DetElement DetElement::child(const string& name) const { /// Access to the detector elements's parent DetElement DetElement::parent() const { - if ( isValid() ) { + if (isValid()) { return object<Object>().parent; } return DetElement(); } -void DetElement::check(bool condition, const string& msg) const { - if ( condition ) { - throw runtime_error("DD4hep: "+msg); +void DetElement::check(bool condition, const string& msg) const { + if (condition) { + throw runtime_error("DD4hep: " + msg); } } -DetElement& DetElement::add(DetElement sdet) { - if ( isValid() ) { - pair<Children::iterator,bool> r = object<Object>().children.insert(make_pair(sdet.name(),sdet)); - if ( r.second ) { +DetElement& DetElement::add(DetElement sdet) { + if (isValid()) { + pair<Children::iterator, bool> r = object<Object>().children.insert(make_pair(sdet.name(), sdet)); + if (r.second) { sdet.object<Object>().parent = *this; return *this; } - throw runtime_error("DD4hep: DetElement::add: Element "+string(sdet.name())+" is already present [Double-Insert]"); + throw runtime_error("DD4hep: DetElement::add: Element " + string(sdet.name()) + " is already present [Double-Insert]"); } throw runtime_error("DD4hep: DetElement::add: Self is not defined [Invalid Handle]"); } -DetElement DetElement::clone(const string& new_name) const { - if ( isValid() ) { +DetElement DetElement::clone(const string& new_name) const { + if (isValid()) { Object& o = object<Object>(); - return DetElement(o.clone(o.id,COPY_NONE), new_name, o.GetTitle()); + return DetElement(o.clone(o.id, COPY_NONE), new_name, o.GetTitle()); } throw runtime_error("DD4hep: DetElement::clone: Self is not defined - clone failed! [Invalid Handle]"); } -DetElement DetElement::clone(const string& new_name, int new_id) const { - if ( isValid() ) { +DetElement DetElement::clone(const string& new_name, int new_id) const { + if (isValid()) { Object& o = object<Object>(); return DetElement(o.clone(new_id, COPY_NONE), new_name, o.GetTitle()); } @@ -436,9 +442,9 @@ DetElement DetElement::clone(const string& new_name, int new_id) const { /// Access to the physical volume of this detector element PlacedVolume DetElement::placement() const { - if ( isValid() ) { + if (isValid()) { Object& o = object<Object>(); - if ( o.placement.isValid() ) { + if (o.placement.isValid()) { return o.placement; } } @@ -447,11 +453,11 @@ PlacedVolume DetElement::placement() const { /// Set the physical volumes of the detector element DetElement& DetElement::setPlacement(const PlacedVolume& placement) { - if ( isValid() ) { - if ( placement.isValid() ) { - Object& o = object<Object>(); + if (isValid()) { + if (placement.isValid()) { + Object& o = object<Object>(); o.placement = placement; - o.volume = placement.volume(); + o.volume = placement.volume(); return *this; } throw runtime_error("DD4hep: DetElement::setPlacement: Placement is not defined [Invalid Handle]"); @@ -460,24 +466,24 @@ DetElement& DetElement::setPlacement(const PlacedVolume& placement) { } /// Access to the logical volume of the placements (all daughters have the same!) -Volume DetElement::volume() const { - if ( isValid() ) { +Volume DetElement::volume() const { + if (isValid()) { return object<Object>().volume; } throw runtime_error("DD4hep: DetElement::volume: Self is not defined [Invalid Handle]"); } -DetElement& DetElement::setVisAttributes(const LCDD& lcdd, const string& name, const Volume& volume) { - if ( isValid() ) { - volume.setVisAttributes(lcdd,name); +DetElement& DetElement::setVisAttributes(const LCDD& lcdd, const string& name, const Volume& volume) { + if (isValid()) { + volume.setVisAttributes(lcdd, name); return *this; } throw runtime_error("DD4hep: DetElement::setVisAttributes: Self is not defined [Invalid Handle]"); } -DetElement& DetElement::setRegion(const LCDD& lcdd, const string& name, const Volume& volume) { - if ( isValid() ) { - if ( !name.empty() ) { +DetElement& DetElement::setRegion(const LCDD& lcdd, const string& name, const Volume& volume) { + if (isValid()) { + if (!name.empty()) { volume.setRegion(lcdd.region(name)); } return *this; @@ -485,9 +491,9 @@ DetElement& DetElement::setRegion(const LCDD& lcdd, const string& name, const Vo throw runtime_error("DD4hep: DetElement::setRegion: Self is not defined [Invalid Handle]"); } -DetElement& DetElement::setLimitSet(const LCDD& lcdd, const string& name, const Volume& volume) { - if ( isValid() ) { - if ( !name.empty() ) { +DetElement& DetElement::setLimitSet(const LCDD& lcdd, const string& name, const Volume& volume) { + if (isValid()) { + if (!name.empty()) { volume.setLimitSet(lcdd.limitSet(name)); } return *this; @@ -495,18 +501,15 @@ DetElement& DetElement::setLimitSet(const LCDD& lcdd, const string& name, const throw runtime_error("DD4hep: DetElement::setLimitSet: Self is not defined [Invalid Handle]"); } -DetElement& DetElement::setAttributes(const LCDD& lcdd, const Volume& volume, - const string& region, - const string& limits, - const string& vis) -{ - return setRegion(lcdd,region,volume).setLimitSet(lcdd,limits,volume).setVisAttributes(lcdd,vis,volume); +DetElement& DetElement::setAttributes(const LCDD& lcdd, const Volume& volume, const string& region, const string& limits, + const string& vis) { + return setRegion(lcdd, region, volume).setLimitSet(lcdd, limits, volume).setVisAttributes(lcdd, vis, volume); } /// Set detector element for reference transformations. Will delete existing reference trafo. DetElement& DetElement::setReference(DetElement reference) { Object& o = object<Object>(); - if ( o.referenceTrafo ) { + if (o.referenceTrafo) { delete o.referenceTrafo; o.referenceTrafo = 0; } @@ -515,64 +518,62 @@ DetElement& DetElement::setReference(DetElement reference) { } /// Transformation from local coordinates of the placed volume to the world system -bool DetElement::localToWorld(const Position& local, Position& global) const { - Double_t master_point[3]={0,0,0}, local_point[3] = {local.X(),local.Y(),local.Z()}; +bool DetElement::localToWorld(const Position& local, Position& global) const { + Double_t master_point[3] = { 0, 0, 0 }, local_point[3] = { local.X(), local.Y(), local.Z() }; // If the path is unknown an exception will be thrown inside worldTransformation() ! - object<Object>().worldTransformation()->LocalToMaster(local_point,master_point); + object<Object>().worldTransformation()->LocalToMaster(local_point, master_point); global.SetCoordinates(master_point); return true; } /// Transformation from local coordinates of the placed volume to the parent system -bool DetElement::localToParent(const Position& local, Position& global) const { +bool DetElement::localToParent(const Position& local, Position& global) const { // If the path is unknown an exception will be thrown inside parentTransformation() ! - Double_t master_point[3]={0,0,0}, local_point[3] = {local.X(),local.Y(),local.Z()}; - object<Object>().parentTransformation()->LocalToMaster(local_point,master_point); + Double_t master_point[3] = { 0, 0, 0 }, local_point[3] = { local.X(), local.Y(), local.Z() }; + object<Object>().parentTransformation()->LocalToMaster(local_point, master_point); global.SetCoordinates(master_point); return true; } /// Transformation from local coordinates of the placed volume to arbitrary parent system set as reference -bool DetElement::localToReference(const Position& local, Position& global) const { +bool DetElement::localToReference(const Position& local, Position& global) const { // If the path is unknown an exception will be thrown inside referenceTransformation() ! - Double_t master_point[3]={0,0,0}, local_point[3] = {local.X(),local.Y(),local.Z()}; - object<Object>().referenceTransformation()->LocalToMaster(local_point,master_point); + Double_t master_point[3] = { 0, 0, 0 }, local_point[3] = { local.X(), local.Y(), local.Z() }; + object<Object>().referenceTransformation()->LocalToMaster(local_point, master_point); global.SetCoordinates(master_point); return true; } /// Transformation from world coordinates of the local placed volume coordinates -bool DetElement::worldToLocal(const Position& global, Position& local) const { +bool DetElement::worldToLocal(const Position& global, Position& local) const { // If the path is unknown an exception will be thrown inside worldTransformation() ! - Double_t master_point[3]={global.X(),global.Y(),global.Z()}, local_point[3] = {0,0,0}; - object<Object>().worldTransformation()->MasterToLocal(master_point,local_point); + Double_t master_point[3] = { global.X(), global.Y(), global.Z() }, local_point[3] = { 0, 0, 0 }; + object<Object>().worldTransformation()->MasterToLocal(master_point, local_point); local.SetCoordinates(local_point); return true; } /// Transformation from parent coordinates of the local placed volume coordinates -bool DetElement::parentToLocal(const Position& global, Position& local) const { +bool DetElement::parentToLocal(const Position& global, Position& local) const { // If the path is unknown an exception will be thrown inside parentTransformation() ! - Double_t master_point[3]={global.X(),global.Y(),global.Z()}, local_point[3] = {0,0,0}; - object<Object>().parentTransformation()->MasterToLocal(master_point,local_point); + Double_t master_point[3] = { global.X(), global.Y(), global.Z() }, local_point[3] = { 0, 0, 0 }; + object<Object>().parentTransformation()->MasterToLocal(master_point, local_point); local.SetCoordinates(local_point); return true; } /// Transformation from arbitrary parent system coordinates of the local placed volume coordinates -bool DetElement::referenceToLocal(const Position& global, Position& local) const { +bool DetElement::referenceToLocal(const Position& global, Position& local) const { // If the path is unknown an exception will be thrown inside referenceTransformation() ! - Double_t master_point[3]={global.X(),global.Y(),global.Z()}, local_point[3] = {0,0,0}; - object<Object>().referenceTransformation()->MasterToLocal(master_point,local_point); + Double_t master_point[3] = { global.X(), global.Y(), global.Z() }, local_point[3] = { 0, 0, 0 }; + object<Object>().referenceTransformation()->MasterToLocal(master_point, local_point); local.SetCoordinates(local_point); return true; } /// Default constructor -SensitiveDetector::Object::Object() - : magic(magic_word()), verbose(0), combineHits(0), ecut(0.0), - hitsCollection(), readout(), region(), limits(), extensions() -{ +SensitiveDetector::Object::Object() + : magic(magic_word()), verbose(0), combineHits(0), ecut(0.0), hitsCollection(), readout(), region(), limits(), extensions() { InstanceCount::increment(this); } @@ -582,13 +583,14 @@ SensitiveDetector::Object::~Object() { readout.clear(); region.clear(); limits.clear(); - for(Extensions::iterator i = extensions.begin(); i!=extensions.end(); ++i) { + for (Extensions::iterator i = extensions.begin(); i != extensions.end(); ++i) { void* ptr = (*i).second; - if ( ptr ) { + if (ptr) { ExtensionMap::iterator j = m.find((*i).first); - if ( j != m.end() ) { - ExtensionEntry& e = (*j).second; - if ( e.destruct ) (*(e.destruct))(ptr); + if (j != m.end()) { + ExtensionEntry& e = (*j).second; + if (e.destruct) + (*(e.destruct))(ptr); } } } @@ -597,21 +599,21 @@ SensitiveDetector::Object::~Object() { } /// Constructor -SensitiveDetector::SensitiveDetector(const string& name, const string& type) { +SensitiveDetector::SensitiveDetector(const string& name, const string& type) { /* - <calorimeter ecut="0" eunit="MeV" hits_collection="EcalEndcapHits" name="EcalEndcap" verbose="0"> - <global_grid_xy grid_size_x="3.5" grid_size_y="3.5"/> - <idspecref ref="EcalEndcapHits"/> - </calorimeter> - */ - assign(new Object(),name,type); + <calorimeter ecut="0" eunit="MeV" hits_collection="EcalEndcapHits" name="EcalEndcap" verbose="0"> + <global_grid_xy grid_size_x="3.5" grid_size_y="3.5"/> + <idspecref ref="EcalEndcapHits"/> + </calorimeter> + */ + assign(new Object(), name, type); object<Object>().ecut = 0e0; object<Object>().verbose = 0; } /// Set the type of the sensitive detector -SensitiveDetector& SensitiveDetector::setType(const string& typ) { - if ( isValid() ) { +SensitiveDetector& SensitiveDetector::setType(const string& typ) { + if (isValid()) { m_element->SetTitle(typ.c_str()); return *this; } @@ -619,34 +621,34 @@ SensitiveDetector& SensitiveDetector::setType(const string& typ) { } /// Access the type of the sensitive detector -string SensitiveDetector::type() const { +string SensitiveDetector::type() const { return m_element ? m_element->GetTitle() : ""; } /// Assign the IDDescriptor reference -SensitiveDetector& SensitiveDetector::setReadout(Readout ro) { +SensitiveDetector& SensitiveDetector::setReadout(Readout ro) { object<Object>().readout = ro; return *this; } /// Assign the IDDescriptor reference -Readout SensitiveDetector::readout() const { +Readout SensitiveDetector::readout() const { return object<Object>().readout; } /// Set energy cut off -SensitiveDetector& SensitiveDetector::setEnergyCutoff(double value) { +SensitiveDetector& SensitiveDetector::setEnergyCutoff(double value) { object<Object>().ecut = value; return *this; } /// Access energy cut off -double SensitiveDetector::energyCutoff() const { +double SensitiveDetector::energyCutoff() const { return object<Object>().ecut; } /// Assign the name of the hits collection -SensitiveDetector& SensitiveDetector::setHitsCollection(const string& collection) { +SensitiveDetector& SensitiveDetector::setHitsCollection(const string& collection) { object<Object>().hitsCollection = collection; return *this; } @@ -657,7 +659,7 @@ const string& SensitiveDetector::hitsCollection() const { } /// Assign the name of the hits collection -SensitiveDetector& SensitiveDetector::setVerbose(bool value) { +SensitiveDetector& SensitiveDetector::setVerbose(bool value) { int v = value ? 1 : 0; object<Object>().verbose = v; return *this; @@ -669,7 +671,7 @@ bool SensitiveDetector::verbose() const { } /// Assign the name of the hits collection -SensitiveDetector& SensitiveDetector::setCombineHits(bool value) { +SensitiveDetector& SensitiveDetector::setCombineHits(bool value) { int v = value ? 1 : 0; object<Object>().combineHits = v; return *this; @@ -680,8 +682,8 @@ bool SensitiveDetector::combineHits() const { return object<Object>().combineHits == 1; } -/// Set the regional attributes to the sensitive detector -SensitiveDetector& SensitiveDetector::setRegion(Region reg) { +/// Set the regional attributes to the sensitive detector +SensitiveDetector& SensitiveDetector::setRegion(Region reg) { object<Object>().region = reg; return *this; } @@ -691,13 +693,13 @@ Region SensitiveDetector::region() const { return object<Object>().region; } -/// Set the limits to the sensitive detector -SensitiveDetector& SensitiveDetector::setLimitSet(LimitSet limits) { +/// Set the limits to the sensitive detector +SensitiveDetector& SensitiveDetector::setLimitSet(LimitSet limits) { object<Object>().limits = limits; return *this; } -/// Access to the limit set of the sensitive detector (not mandatory). +/// Access to the limit set of the sensitive detector (not mandatory). LimitSet SensitiveDetector::limits() const { return object<Object>().limits; } @@ -706,33 +708,33 @@ LimitSet SensitiveDetector::limits() const { void* SensitiveDetector::i_addExtension(void* ptr, const type_info& info, void (*destruct)(void*)) { Object& o = object<Object>(); Extensions::iterator j = o.extensions.find(&info); - if ( j == o.extensions.end() ) { + if (j == o.extensions.end()) { ExtensionMap& m = sensitive_detector_extensions(); ExtensionMap::iterator i = m.find(&info); - if ( i == m.end() ) { + if (i == m.end()) { ExtensionEntry entry; entry.destruct = destruct; entry.copy = 0; entry.id = ++s_extensionID; - m.insert(make_pair(&info,entry)); + m.insert(make_pair(&info, entry)); i = m.find(&info); } ExtensionEntry& e = (*i).second; - cout << "Extension["<<name()<<"]:" << ptr << " " << typeid(*(TNamed*)ptr).name() << endl; + cout << "Extension[" << name() << "]:" << ptr << " " << typeid(*(TNamed*) ptr).name() << endl; return o.extensions[&info] = ptr; } - throw runtime_error("DD4hep: addExtension: The object "+string(name())+ - " already has an extension of type:"+string(info.name())+"."); + throw runtime_error( + "DD4hep: addExtension: The object " + string(name()) + " already has an extension of type:" + string(info.name()) + "."); } /// Access an existing extension object from the detector element -void* SensitiveDetector::i_extension(const type_info& info) const { +void* SensitiveDetector::i_extension(const type_info& info) const { Object& o = object<Object>(); Extensions::const_iterator j = o.extensions.find(&info); - if ( j != o.extensions.end() ) { + if (j != o.extensions.end()) { return (*j).second; } - throw runtime_error("DD4hep: extension: The object "+string(name())+ - " has no extension of type:"+string(info.name())+"."); + throw runtime_error( + "DD4hep: extension: The object " + string(name()) + " has no extension of type:" + string(info.name()) + "."); } - + diff --git a/DDCore/src/ExpressionEvaluator.cpp b/DDCore/src/ExpressionEvaluator.cpp index cfd156bfe..17d409ff6 100644 --- a/DDCore/src/ExpressionEvaluator.cpp +++ b/DDCore/src/ExpressionEvaluator.cpp @@ -1,25 +1,19 @@ #include "XML/Evaluator.h" -namespace DD4hep { - XmlTools::Evaluator& evaluator() { +namespace DD4hep { + XmlTools::Evaluator& evaluator() { static XmlTools::Evaluator e; return e; } } namespace { - struct _Init { - _Init() { + struct _Init { + _Init() { // Initialize numerical expressions parser with the standard math functions // and the system of units used by Gaudi (Geant4) DD4hep::evaluator().setStdMath(); - DD4hep::evaluator().setSystemOfUnits (1.e+3, - 1./1.60217733e-25, - 1.e+9, - 1./1.60217733e-10, - 1.0, - 1.0, - 1.0); + DD4hep::evaluator().setSystemOfUnits(1.e+3, 1. / 1.60217733e-25, 1.e+9, 1. / 1.60217733e-10, 1.0, 1.0, 1.0); } }; _Init s_init; diff --git a/DDCore/src/FieldTypes.cpp b/DDCore/src/FieldTypes.cpp index 803b8ed27..3a247962a 100644 --- a/DDCore/src/FieldTypes.cpp +++ b/DDCore/src/FieldTypes.cpp @@ -25,27 +25,23 @@ void ConstantField::fieldComponents(const double* /* pos */, double* field) { } /// Initializing constructor -SolenoidField::SolenoidField() - : innerField(0), outerField(0), - minZ(-INFINITY), maxZ(INFINITY), - innerRadius(0), outerRadius(INFINITY) -{ - type = CartesianField::MAGNETIC; +SolenoidField::SolenoidField() + : innerField(0), outerField(0), minZ(-INFINITY), maxZ(INFINITY), innerRadius(0), outerRadius(INFINITY) { + type = CartesianField::MAGNETIC; } /// Call to access the field components at a given location void SolenoidField::fieldComponents(const double* pos, double* field) { - double radius = sqrt( pos[0] * pos[0] + pos[1] * pos[1] ); - if ( radius < innerRadius ) + double radius = sqrt(pos[0] * pos[0] + pos[1] * pos[1]); + if (radius < innerRadius) field[2] += innerField; - else if ( radius < outerRadius ) + else if (radius < outerRadius) field[2] += outerField; } /// Initializing constructor DipoleField::DipoleField() - : zmax(INFINITY), zmin(-INFINITY), rmax(INFINITY) -{ + : zmax(INFINITY), zmin(-INFINITY), rmax(INFINITY) { } /// Call to access the field components at a given location @@ -53,17 +49,18 @@ void DipoleField::fieldComponents(const double* pos, double* field) { double bx = 0, z = pos[2], r = sqrt(pos[0] * pos[0] + pos[1] * pos[1]); // Check if z coordinate is within dipole z bounds. - if (z > zmin && z < zmax && r < rmax) { + if (z > zmin && z < zmax && r < rmax) { // Apply all coefficients to this z coordinate. double pp = 1.0; double abs_z = fabs(z); bx = coefficents[0]; - for (size_t i=1; i<coefficents.size(); ++i) { + for (size_t i = 1; i < coefficents.size(); ++i) { pp *= abs_z; bx += coefficents[i] * abs_z; } // Flip sign for negative z. - if (z < 0) bx = -bx; + if (z < 0) + bx = -bx; // Add Bx to the input field. field[0] += bx; } diff --git a/DDCore/src/Fields.cpp b/DDCore/src/Fields.cpp index e3f532f00..337639df9 100644 --- a/DDCore/src/Fields.cpp +++ b/DDCore/src/Fields.cpp @@ -15,18 +15,19 @@ using namespace DD4hep::Geometry; namespace { void calculate_combined_field(vector<CartesianField>& v, const double* pos, double* field) { - for(vector<CartesianField>::iterator i=v.begin(); i!=v.end(); ++i) - (*i).value(pos,field); + for (vector<CartesianField>::iterator i = v.begin(); i != v.end(); ++i) + (*i).value(pos, field); } } /// Default constructor -CartesianField::Object::Object() : TNamed(), type(UNKNOWN) { +CartesianField::Object::Object() + : TNamed(), type(UNKNOWN) { InstanceCount::increment(this); } /// Default destructor -CartesianField::Object::~Object() { +CartesianField::Object::~Object() { InstanceCount::decrement(this); } @@ -37,66 +38,69 @@ const char* CartesianField::type() const { /// Does the field change the energy of charged particles? bool CartesianField::changesEnergy() const { - return ELECTRIC==(fieldType()&ELECTRIC); + return ELECTRIC == (fieldType() & ELECTRIC); } /// Access to properties container -CartesianField::Properties& CartesianField::properties() const { - return data<Object>()->properties; +CartesianField::Properties& CartesianField::properties() const { + return data<Object>()->properties; } /// Returns the 3 field components (x, y, z). -void CartesianField::value(const double* pos, double* val) const { - data<Object>()->fieldComponents(pos,val); +void CartesianField::value(const double* pos, double* val) const { + data<Object>()->fieldComponents(pos, val); } /// Default constructor -OverlayedField::Object::Object() : type(0), electric(), magnetic() { +OverlayedField::Object::Object() + : type(0), electric(), magnetic() { InstanceCount::increment(this); } /// Default destructor -OverlayedField::Object::~Object() { +OverlayedField::Object::~Object() { InstanceCount::decrement(this); } /// Object constructor -OverlayedField::OverlayedField(const string& name) : Ref_t() { - assign(new Object(),name,"overlay_field"); +OverlayedField::OverlayedField(const string& name) + : Ref_t() { + assign(new Object(), name, "overlay_field"); } /// Access to properties container -OverlayedField::Properties& OverlayedField::properties() const { - return data<Object>()->properties; +OverlayedField::Properties& OverlayedField::properties() const { + return data<Object>()->properties; } /// Does the field change the energy of charged particles? bool OverlayedField::changesEnergy() const { int field = data<Object>()->type; - return CartesianField::ELECTRIC==(field&CartesianField::ELECTRIC); + return CartesianField::ELECTRIC == (field & CartesianField::ELECTRIC); } /// Add a new field component void OverlayedField::add(CartesianField field) { - if ( field.isValid() ) { + if (field.isValid()) { Object* o = data<Object>(); - if ( o ) { + if (o) { int typ = field.fieldType(); - bool isEle = field.ELECTRIC==(typ&field.ELECTRIC); - bool isMag = field.MAGNETIC==(typ&field.MAGNETIC); - if ( isEle ) { - vector<CartesianField>& v = o->electric_components; - v.push_back(field); - o->type |= field.ELECTRIC; - o->electric = v.size()==1 ? field : CartesianField(); + bool isEle = field.ELECTRIC == (typ & field.ELECTRIC); + bool isMag = field.MAGNETIC == (typ & field.MAGNETIC); + if (isEle) { + vector < CartesianField > &v = o->electric_components; + v.push_back(field); + o->type |= field.ELECTRIC; + o->electric = v.size() == 1 ? field : CartesianField(); } - if ( isMag ) { - vector<CartesianField>& v = o->magnetic_components; - v.push_back(field); - o->type |= field.MAGNETIC; - o->magnetic = v.size()==1 ? field : CartesianField(); + if (isMag) { + vector < CartesianField > &v = o->magnetic_components; + v.push_back(field); + o->type |= field.MAGNETIC; + o->magnetic = v.size() == 1 ? field : CartesianField(); } - if ( isMag ||isEle ) return; + if (isMag || isEle) + return; throw runtime_error("OverlayedField::add: Attempt to add an unknown field type."); } throw runtime_error("OverlayedField::add: Attempt to add to an invalid object."); @@ -105,21 +109,21 @@ void OverlayedField::add(CartesianField field) { } /// Returns the 3 electric field components (x, y, z). -void OverlayedField::combinedElectric(const double* pos, double* field) const { +void OverlayedField::combinedElectric(const double* pos, double* field) const { field[0] = field[1] = field[2] = 0.; - calculate_combined_field(data<Object>()->electric_components,pos,field); + calculate_combined_field(data<Object>()->electric_components, pos, field); } /// Returns the 3 magnetic field components (x, y, z). -void OverlayedField::combinedMagnetic(const double* pos, double* field) const { +void OverlayedField::combinedMagnetic(const double* pos, double* field) const { field[0] = field[1] = field[2] = 0.; - calculate_combined_field(data<Object>()->magnetic_components,pos,field); + calculate_combined_field(data<Object>()->magnetic_components, pos, field); } /// Returns the 3 electric (val[0]-val[2]) and magnetic field components (val[3]-val[5]). -void OverlayedField::electromagneticField(const double* pos, double* field) const { +void OverlayedField::electromagneticField(const double* pos, double* field) const { Object* o = data<Object>(); field[0] = field[1] = field[2] = 0.; - calculate_combined_field(o->electric_components,pos,field); - calculate_combined_field(o->magnetic_components,pos,field+3); + calculate_combined_field(o->electric_components, pos, field); + calculate_combined_field(o->magnetic_components, pos, field + 3); } diff --git a/DDCore/src/GeoHandler.cpp b/DDCore/src/GeoHandler.cpp index b632d27ae..842f119f8 100644 --- a/DDCore/src/GeoHandler.cpp +++ b/DDCore/src/GeoHandler.cpp @@ -24,18 +24,19 @@ using namespace DD4hep; using namespace std; namespace { - void collectSolid(GeoHandler::GeometryInfo& geo, const string& name, const string& node, TGeoShape* shape, TGeoMatrix* matrix) { - if ( 0 == ::strncmp(shape->GetName(),"TGeo",4) ) { + void collectSolid(GeoHandler::GeometryInfo& geo, const string& name, const string& node, TGeoShape* shape, + TGeoMatrix* matrix) { + if (0 == ::strncmp(shape->GetName(), "TGeo", 4)) { shape->SetName(name.c_str()); } - if ( shape->IsA() == TGeoCompositeShape::Class() ) { - const TGeoCompositeShape* s = (const TGeoCompositeShape*)shape; + if (shape->IsA() == TGeoCompositeShape::Class()) { + const TGeoCompositeShape* s = (const TGeoCompositeShape*) shape; const TGeoBoolNode* boolean = s->GetBoolNode(); - collectSolid(geo, name+"_left", name+"_left", boolean->GetLeftShape(), boolean->GetLeftMatrix()); - collectSolid(geo, name+"_right", name+"_right", boolean->GetRightShape(), boolean->GetRightMatrix()); + collectSolid(geo, name + "_left", name + "_left", boolean->GetLeftShape(), boolean->GetLeftMatrix()); + collectSolid(geo, name + "_right", name + "_right", boolean->GetRightShape(), boolean->GetRightMatrix()); } geo.solids.insert(shape); - geo.trafos.push_back(make_pair(node,matrix)); + geo.trafos.push_back(make_pair(node, matrix)); } } @@ -45,12 +46,14 @@ GeoHandler::GeoHandler() { } /// Initializing constructor -GeoHandler::GeoHandler(Data* ptr) : m_data(ptr) { +GeoHandler::GeoHandler(Data* ptr) + : m_data(ptr) { } /// Default destructor GeoHandler::~GeoHandler() { - if ( m_data ) delete m_data; + if (m_data) + delete m_data; m_data = 0; } @@ -62,39 +65,41 @@ GeoHandler::Data* GeoHandler::release() { GeoHandler& GeoHandler::collect(DetElement element) { m_data->clear(); - return i_collect(element.placement().ptr(),0); + return i_collect(element.placement().ptr(), 0); } GeoHandler& GeoHandler::collect(DetElement element, GeometryInfo& info) { m_data->clear(); - i_collect(element.placement().ptr(),0); - for(Data::const_reverse_iterator i=m_data->rbegin(); i != m_data->rend(); ++i) { + i_collect(element.placement().ptr(), 0); + for (Data::const_reverse_iterator i = m_data->rbegin(); i != m_data->rend(); ++i) { int level = (*i).first; const Data::mapped_type& v = (*i).second; - for(Data::mapped_type::const_iterator j=v.begin(); j != v.end(); ++j) { + for (Data::mapped_type::const_iterator j = v.begin(); j != v.end(); ++j) { const TGeoNode* n = *j; TGeoVolume* v = n->GetVolume(); - if ( v ) { - TGeoMedium* m = v->GetMedium(); - Volume vol = Ref_t(v); - // Note : assemblies and the world do not have a real volume nor a material - if ( info.volumeSet.find(v) == info.volumeSet.end() ) { - info.volumeSet.insert(v); - info.volumes.push_back(v); - } - if ( m ) info.materials.insert(m); - if ( dynamic_cast<Volume::Object*>(v) ) { - VisAttr vis = vol.visAttributes(); - //Region reg = vol.region(); - //LimitSet lim = vol.limitSet(); - //SensitiveDetector det = vol.sensitiveDetector(); - - if ( vis.isValid() ) info.vis.insert(vis.ptr()); - //if ( lim.isValid() ) info.limits[lim.ptr()].insert(v); - //if ( reg.isValid() ) info.regions[reg.ptr()].insert(v); - //if ( det.isValid() ) info.sensitives[det.ptr()].insert(v); - } - collectSolid(info,v->GetName(),n->GetName(),v->GetShape(),n->GetMatrix()); + if (v) { + TGeoMedium* m = v->GetMedium(); + Volume vol = Ref_t(v); + // Note : assemblies and the world do not have a real volume nor a material + if (info.volumeSet.find(v) == info.volumeSet.end()) { + info.volumeSet.insert(v); + info.volumes.push_back(v); + } + if (m) + info.materials.insert(m); + if (dynamic_cast<Volume::Object*>(v)) { + VisAttr vis = vol.visAttributes(); + //Region reg = vol.region(); + //LimitSet lim = vol.limitSet(); + //SensitiveDetector det = vol.sensitiveDetector(); + + if (vis.isValid()) + info.vis.insert(vis.ptr()); + //if ( lim.isValid() ) info.limits[lim.ptr()].insert(v); + //if ( reg.isValid() ) info.regions[reg.ptr()].insert(v); + //if ( det.isValid() ) info.sensitives[det.ptr()].insert(v); + } + collectSolid(info, v->GetName(), n->GetName(), v->GetShape(), n->GetMatrix()); } } } @@ -103,14 +108,14 @@ GeoHandler& GeoHandler::collect(DetElement element, GeometryInfo& info) { GeoHandler& GeoHandler::i_collect(const TGeoNode* current, int level) { TGeoVolume* volume = current->GetVolume(); - TObjArray* nodes = volume->GetNodes(); - int num_children = nodes ? nodes->GetEntriesFast() : 0; + TObjArray* nodes = volume->GetNodes(); + int num_children = nodes ? nodes->GetEntriesFast() : 0; (*m_data)[level].insert(current); - if ( num_children > 0 ) { - for(int i=0; i<num_children; ++i) { - TGeoNode* node = (TGeoNode*)nodes->At(i); - i_collect(node,level+1); + if (num_children > 0) { + for (int i = 0; i < num_children; ++i) { + TGeoNode* node = (TGeoNode*) nodes->At(i); + i_collect(node, level + 1); } } return *this; @@ -123,7 +128,8 @@ GeoScan::GeoScan(DetElement e) { /// Default destructor GeoScan::~GeoScan() { - if ( m_data ) delete m_data; + if (m_data) + delete m_data; m_data = 0; } diff --git a/DDCore/src/GeometryTreeDump.cpp b/DDCore/src/GeometryTreeDump.cpp index 3048845f2..79a1607af 100644 --- a/DDCore/src/GeometryTreeDump.cpp +++ b/DDCore/src/GeometryTreeDump.cpp @@ -41,54 +41,55 @@ namespace { /// Reference to output stream ostream& m_output = cout; - - void getAngles(const Double_t* m, Double_t &phi, Double_t &theta, Double_t &psi) { + void getAngles(const Double_t* m, Double_t &phi, Double_t &theta, Double_t &psi) { // Retreive Euler angles. // Check if theta is 0 or 180. - if (TMath::Abs(1.-TMath::Abs(m[8]))<1.e-9) { - theta = TMath::ACos(m[8])*RAD_2_DEGREE; - phi = TMath::ATan2(-m[8]*m[1],m[0])*RAD_2_DEGREE; - psi = 0.; // convention, phi+psi matters + if (TMath::Abs(1. - TMath::Abs(m[8])) < 1.e-9) { + theta = TMath::ACos(m[8]) * RAD_2_DEGREE; + phi = TMath::ATan2(-m[8] * m[1], m[0]) * RAD_2_DEGREE; + psi = 0.; // convention, phi+psi matters return; } // sin(theta) != 0 - phi = TMath::ATan2(m[2],-m[5]); + phi = TMath::ATan2(m[2], -m[5]); Double_t sphi = TMath::Sin(phi); - if (TMath::Abs(sphi)<1.e-9) theta = -TMath::ASin(m[5]/TMath::Cos(phi))*RAD_2_DEGREE; - else theta = TMath::ASin(m[2]/sphi)*RAD_2_DEGREE; - phi *= RAD_2_DEGREE; - psi = TMath::ATan2(m[6],m[7])*RAD_2_DEGREE; + if (TMath::Abs(sphi) < 1.e-9) + theta = -TMath::ASin(m[5] / TMath::Cos(phi)) * RAD_2_DEGREE; + else + theta = TMath::ASin(m[2] / sphi) * RAD_2_DEGREE; + phi *= RAD_2_DEGREE; + psi = TMath::ATan2(m[6], m[7]) * RAD_2_DEGREE; } } /// Dump logical volume in GDML format to output stream -void* GeometryTreeDump::handleVolume(const string& name, const TGeoVolume* volume) const { - Volume vol = Handle<>(volume); - VisAttr vis = vol.visAttributes(); - TGeoShape* shape = volume->GetShape(); +void* GeometryTreeDump::handleVolume(const string& name, const TGeoVolume* volume) const { + Volume vol = Handle<>(volume); + VisAttr vis = vol.visAttributes(); + TGeoShape* shape = volume->GetShape(); TGeoMedium* medium = volume->GetMedium(); - int num = volume->GetNdaughters(); + int num = volume->GetNdaughters(); m_output << "\t\t<volume name=\"" << name << "\">" << endl; m_output << "\t\t\t<solidref ref=\"" << shape->GetName() << "\"/>" << endl; m_output << "\t\t\t<materialref ref=\"" << medium->GetName() << "\"/>" << endl; - if ( vis.isValid() ) { + if (vis.isValid()) { m_output << "\t\t\t<visref ref=\"" << vis.name() << "\"/>" << endl; } - if ( num > 0 ) { - for(int i=0; i<num; ++i) { - TGeoNode* n = volume->GetNode(i); + if (num > 0) { + for (int i = 0; i < num; ++i) { + TGeoNode* n = volume->GetNode(i); TGeoVolume* v = n->GetVolume(); TGeoMatrix* m = n->GetMatrix(); m_output << "\t\t\t<physvol>" << endl; m_output << "\t\t\t\t<volumeref ref=\"" << v->GetName() << "\"/>" << endl; - if ( m ) { - if ( m->IsTranslation() ) { - m_output << "\t\t\t\t<positionref ref=\"" << n->GetName() << "_pos\"/>" << endl; - } - if ( m->IsRotation() ) { - m_output << "\t\t\t\t<rotationref ref=\"" << n->GetName() << "_rot\"/>" << endl; - } + if (m) { + if (m->IsTranslation()) { + m_output << "\t\t\t\t<positionref ref=\"" << n->GetName() << "_pos\"/>" << endl; + } + if (m->IsRotation()) { + m_output << "\t\t\t\t<rotationref ref=\"" << n->GetName() << "_rot\"/>" << endl; + } } m_output << "\t\t\t</physvol>" << endl; } @@ -98,221 +99,197 @@ void* GeometryTreeDump::handleVolume(const string& name, const TGeoVolume* volum } /// Dump solid in GDML format to output stream -void* GeometryTreeDump::handleSolid(const string& name, const TGeoShape* shape) const { - if ( shape ) { - if ( shape->IsA() == TGeoBBox::Class() ) { - const TGeoBBox* s = (const TGeoBBox*)shape; - m_output << "\t\t<box name=\"" << name << "_shape\" x=\"" - << s->GetDX() << "\" y=\"" - << s->GetDY() << "\" z=\"" - << s->GetDZ() << "\" lunit=\"cm\"/>" << endl; +void* GeometryTreeDump::handleSolid(const string& name, const TGeoShape* shape) const { + if (shape) { + if (shape->IsA() == TGeoBBox::Class()) { + const TGeoBBox* s = (const TGeoBBox*) shape; + m_output << "\t\t<box name=\"" << name << "_shape\" x=\"" << s->GetDX() << "\" y=\"" << s->GetDY() << "\" z=\"" + << s->GetDZ() << "\" lunit=\"cm\"/>" << endl; } - else if ( shape->IsA() == TGeoTube::Class() ) { - const TGeoTube* s = (const TGeoTube*)shape; - m_output << "\t\t<tube name=\"" << name << "_shape\" rmin=\"" - << s->GetRmin() << "\" rmax=\"" - << s->GetRmax() << "\" z=\"" - << s->GetDz() << "\" startphi=\"0.0\" deltaphi=\"360.0\" aunit=\"deg\" lunit=\"cm\"/>" << endl; + else if (shape->IsA() == TGeoTube::Class()) { + const TGeoTube* s = (const TGeoTube*) shape; + m_output << "\t\t<tube name=\"" << name << "_shape\" rmin=\"" << s->GetRmin() << "\" rmax=\"" << s->GetRmax() << "\" z=\"" + << s->GetDz() << "\" startphi=\"0.0\" deltaphi=\"360.0\" aunit=\"deg\" lunit=\"cm\"/>" << endl; } - else if ( shape->IsA() == TGeoTubeSeg::Class() ) { - const TGeoTubeSeg* s = (const TGeoTubeSeg*)shape; - m_output << "\t\t<tube name=\"" << name << "_shape\" rmin=\"" - << s->GetRmin() << "\" rmax=\"" - << s->GetRmax() << "\" z=\"" - << s->GetDz() << "\" startphi=\"" - << s->GetPhi1() << "\" deltaphi=\"" - << s->GetPhi2() << "\" aunit=\"deg\" lunit=\"cm\"/>" << endl; + else if (shape->IsA() == TGeoTubeSeg::Class()) { + const TGeoTubeSeg* s = (const TGeoTubeSeg*) shape; + m_output << "\t\t<tube name=\"" << name << "_shape\" rmin=\"" << s->GetRmin() << "\" rmax=\"" << s->GetRmax() << "\" z=\"" + << s->GetDz() << "\" startphi=\"" << s->GetPhi1() << "\" deltaphi=\"" << s->GetPhi2() + << "\" aunit=\"deg\" lunit=\"cm\"/>" << endl; } - else if ( shape->IsA() == TGeoTrd1::Class() ) { - const TGeoTrd1* s = (const TGeoTrd1*)shape; - m_output << "\t\t<tube name=\"" << name << "_shape\" x1=\"" - << s->GetDx1() << "\" x2=\"" - << s->GetDx2() << "\" y1=\"" - << s->GetDy() << "\" y2=\"" - << s->GetDy() << "\" z=\"" - << s->GetDz() << "\" lunit=\"cm\"/>" << endl; + else if (shape->IsA() == TGeoTrd1::Class()) { + const TGeoTrd1* s = (const TGeoTrd1*) shape; + m_output << "\t\t<tube name=\"" << name << "_shape\" x1=\"" << s->GetDx1() << "\" x2=\"" << s->GetDx2() << "\" y1=\"" + << s->GetDy() << "\" y2=\"" << s->GetDy() << "\" z=\"" << s->GetDz() << "\" lunit=\"cm\"/>" << endl; } - else if ( shape->IsA() == TGeoTrd2::Class() ) { - const TGeoTrd2* s = (const TGeoTrd2*)shape; - m_output << "\t\t<tube name=\"" << name << "_shape\" x1=\"" - << s->GetDx1() << "\" x2=\"" - << s->GetDx2() << "\" y1=\"" - << s->GetDy1() << "\" y2=\"" - << s->GetDy2() << "\" z=\"" - << s->GetDz() << "\" lunit=\"cm\"/>" << endl; + else if (shape->IsA() == TGeoTrd2::Class()) { + const TGeoTrd2* s = (const TGeoTrd2*) shape; + m_output << "\t\t<tube name=\"" << name << "_shape\" x1=\"" << s->GetDx1() << "\" x2=\"" << s->GetDx2() << "\" y1=\"" + << s->GetDy1() << "\" y2=\"" << s->GetDy2() << "\" z=\"" << s->GetDz() << "\" lunit=\"cm\"/>" << endl; } - else if ( shape->IsA() == TGeoPgon::Class() ) { - const TGeoPgon* s = (const TGeoPgon*)shape; - m_output << "\t\t<polyhedra name=\"" << name << "_shape\" startphi=\"" - << s->GetPhi1() << "\" deltaphi=\"" - << s->GetDphi() << "\" numsides=\"" - << s->GetNedges() << "\" aunit=\"deg\" lunit=\"cm\">" << endl; - for(int i=0; i<s->GetNz(); ++i) { - m_output << "\t\t\t<zplane z=\"" << s->GetZ(i) - << "\" rmin=\"" << s->GetRmin(i) - << "\" rmax=\"" << s->GetRmax(i) - << "\" lunit=\"cm\"/>" << endl; + else if (shape->IsA() == TGeoPgon::Class()) { + const TGeoPgon* s = (const TGeoPgon*) shape; + m_output << "\t\t<polyhedra name=\"" << name << "_shape\" startphi=\"" << s->GetPhi1() << "\" deltaphi=\"" << s->GetDphi() + << "\" numsides=\"" << s->GetNedges() << "\" aunit=\"deg\" lunit=\"cm\">" << endl; + for (int i = 0; i < s->GetNz(); ++i) { + m_output << "\t\t\t<zplane z=\"" << s->GetZ(i) << "\" rmin=\"" << s->GetRmin(i) << "\" rmax=\"" << s->GetRmax(i) + << "\" lunit=\"cm\"/>" << endl; } m_output << "\t\t</polyhedra>" << endl; } - else if ( shape->IsA() == TGeoPcon::Class() ) { - const TGeoPcon* s = (const TGeoPcon*)shape; - m_output << "\t\t<polycone name=\"" << name << "_shape\" startphi=\"" - << s->GetPhi1() << "\" deltaphi=\"" - << s->GetDphi() << "\" aunit=\"deg\" lunit=\"cm\">" << endl; - for(int i=0; i<s->GetNz(); ++i) { - m_output << "\t\t\t<zplane z=\"" << s->GetZ(i) - << "\" rmin=\"" << s->GetRmin(i) - << "\" rmax=\"" << s->GetRmax(i) - << "\" lunit=\"cm\"/>" << endl; + else if (shape->IsA() == TGeoPcon::Class()) { + const TGeoPcon* s = (const TGeoPcon*) shape; + m_output << "\t\t<polycone name=\"" << name << "_shape\" startphi=\"" << s->GetPhi1() << "\" deltaphi=\"" << s->GetDphi() + << "\" aunit=\"deg\" lunit=\"cm\">" << endl; + for (int i = 0; i < s->GetNz(); ++i) { + m_output << "\t\t\t<zplane z=\"" << s->GetZ(i) << "\" rmin=\"" << s->GetRmin(i) << "\" rmax=\"" << s->GetRmax(i) + << "\" lunit=\"cm\"/>" << endl; } m_output << "\t\t</polycone>" << endl; } - else if ( shape->IsA() == TGeoCompositeShape::Class() ) { + else if (shape->IsA() == TGeoCompositeShape::Class()) { string nn = name; - const TGeoCompositeShape* s = (const TGeoCompositeShape*)shape; + const TGeoCompositeShape* s = (const TGeoCompositeShape*) shape; const TGeoBoolNode* boolean = s->GetBoolNode(); TGeoBoolNode::EGeoBoolType oper = boolean->GetBooleanOperator(); - handleSolid(name+"_left", boolean->GetLeftShape()); - handleSolid(name+"_right",boolean->GetRightShape()); + handleSolid(name + "_left", boolean->GetLeftShape()); + handleSolid(name + "_right", boolean->GetRightShape()); - if ( oper == TGeoBoolNode::kGeoSubtraction ) - m_output << "\t\t<subtraction name=\"" << nn << "\">" << endl; - else if ( oper == TGeoBoolNode::kGeoUnion ) - m_output << "\t\t<union name=\"" << nn << "\">" << endl; - else if ( oper == TGeoBoolNode::kGeoIntersection ) - m_output << "\t\t<intersection name=\"" << nn << "\">" << endl; + if (oper == TGeoBoolNode::kGeoSubtraction) + m_output << "\t\t<subtraction name=\"" << nn << "\">" << endl; + else if (oper == TGeoBoolNode::kGeoUnion) + m_output << "\t\t<union name=\"" << nn << "\">" << endl; + else if (oper == TGeoBoolNode::kGeoIntersection) + m_output << "\t\t<intersection name=\"" << nn << "\">" << endl; - m_output << "\t\t\t<first ref=\"" << nn << "_left\"/>" << endl; + m_output << "\t\t\t<first ref=\"" << nn << "_left\"/>" << endl; m_output << "\t\t\t<second ref=\"" << nn << "_right\"/>" << endl; indent = "\t"; handleTransformation("", boolean->GetRightMatrix()); indent = ""; - if ( oper == TGeoBoolNode::kGeoSubtraction ) - m_output << "\t\t</subtraction>" << endl; - else if ( oper == TGeoBoolNode::kGeoUnion ) - m_output << "\t\t</union>" << endl; - else if ( oper == TGeoBoolNode::kGeoIntersection ) - m_output << "\t\t</intersection>" << endl; + if (oper == TGeoBoolNode::kGeoSubtraction) + m_output << "\t\t</subtraction>" << endl; + else if (oper == TGeoBoolNode::kGeoUnion) + m_output << "\t\t</union>" << endl; + else if (oper == TGeoBoolNode::kGeoIntersection) + m_output << "\t\t</intersection>" << endl; } else { - cerr << "Failed to handle unknwon solid shape:" - << shape->IsA()->GetName() << endl; + cerr << "Failed to handle unknwon solid shape:" << shape->IsA()->GetName() << endl; } } return 0; } /// Dump structure information in GDML format to output stream -void GeometryTreeDump::handleStructure(const VolumeSet& volset) const { +void GeometryTreeDump::handleStructure(const VolumeSet& volset) const { m_output << "\t<structure>" << endl; - for(VolumeSet::const_iterator i=volset.begin(); i != volset.end(); ++i) - handleVolume((*i)->GetName(),*i); + for (VolumeSet::const_iterator i = volset.begin(); i != volset.end(); ++i) + handleVolume((*i)->GetName(), *i); m_output << "\t</structure>" << endl; } /// Dump single volume transformation in GDML format to output stream void* GeometryTreeDump::handleTransformation(const string& name, const TGeoMatrix* m) const { - if ( m ) { - if ( m->IsTranslation() ) { + if (m) { + if (m->IsTranslation()) { const Double_t* f = m->GetTranslation(); m_output << indent << "\t\t<position "; - if ( !name.empty() ) m_output << "name=\"" << name << "_pos\" "; - m_output << "x=\"" << f[0] << "\" " - << "y=\"" << f[1] << "\" " - << "z=\"" << f[2] << "\" unit=\"cm\"/>" << endl; + if (!name.empty()) + m_output << "name=\"" << name << "_pos\" "; + m_output << "x=\"" << f[0] << "\" " << "y=\"" << f[1] << "\" " << "z=\"" << f[2] << "\" unit=\"cm\"/>" << endl; } - if ( m->IsRotation() ) { + if (m->IsRotation()) { const Double_t* mat = m->GetRotationMatrix(); - Double_t theta=0.0, phi=0.0, psi=0.0; + Double_t theta = 0.0, phi = 0.0, psi = 0.0; getAngles(mat, theta, phi, psi); m_output << indent << "\t\t<rotation "; - if ( !name.empty() ) m_output << "name=\"" << name << "_rot\" "; - m_output << "x=\"" << theta << "\" " - << "y=\"" << psi << "\" " - << "z=\"" << phi << "\" unit=\"deg\"/>" << endl; + if (!name.empty()) + m_output << "name=\"" << name << "_rot\" "; + m_output << "x=\"" << theta << "\" " << "y=\"" << psi << "\" " << "z=\"" << phi << "\" unit=\"deg\"/>" << endl; } } return 0; } /// Dump Transformations in GDML format to output stream -void GeometryTreeDump::handleTransformations(const TransformSet& trafos) const { +void GeometryTreeDump::handleTransformations(const TransformSet& trafos) const { m_output << "\t<define>" << endl; - for(TransformSet::const_iterator i=trafos.begin(); i != trafos.end(); ++i) + for (TransformSet::const_iterator i = trafos.begin(); i != trafos.end(); ++i) handleTransformation((*i).first, (*i).second); m_output << "\t</define>" << endl; } /// Dump all solids in GDML format to output stream -void GeometryTreeDump::handleSolids(const SolidSet& solids) const { +void GeometryTreeDump::handleSolids(const SolidSet& solids) const { m_output << "\t<solids>" << endl; - for(SolidSet::const_iterator i=solids.begin(); i != solids.end(); ++i) - handleSolid((*i)->GetName(),*i); + for (SolidSet::const_iterator i = solids.begin(); i != solids.end(); ++i) + handleSolid((*i)->GetName(), *i); m_output << "\t</solids>" << endl; } /// Dump all constants in GDML format to output stream -void GeometryTreeDump::handleDefines(const LCDD::HandleMap& defs) const { +void GeometryTreeDump::handleDefines(const LCDD::HandleMap& defs) const { m_output << "\t<define>" << endl; - for(LCDD::HandleMap::const_iterator i=defs.begin(); i != defs.end(); ++i) - m_output << "\t\t<constant name=\"" << (*i).second->GetName() << "\" value=\"" << (*i).second->GetTitle() << "\" />" << endl; + for (LCDD::HandleMap::const_iterator i = defs.begin(); i != defs.end(); ++i) + m_output << "\t\t<constant name=\"" << (*i).second->GetName() << "\" value=\"" << (*i).second->GetTitle() << "\" />" + << endl; m_output << "\t</define>" << endl; } /// Dump all visualisation specs in LCDD format to output stream -void GeometryTreeDump::handleVisualisation(const LCDD::HandleMap& ) const { +void GeometryTreeDump::handleVisualisation(const LCDD::HandleMap&) const { } static string _path = ""; static void dumpStructure(PlacedVolume pv, int level) { - TGeoNode* current = pv.ptr(); - TGeoVolume* volume = current->GetVolume(); - TObjArray* nodes = volume->GetNodes(); - int num_children = nodes ? nodes->GetEntriesFast() : 0; + TGeoNode* current = pv.ptr(); + TGeoVolume* volume = current->GetVolume(); + TObjArray* nodes = volume->GetNodes(); + int num_children = nodes ? nodes->GetEntriesFast() : 0; char fmt[128]; _path += "/"; _path += current->GetName(); - ::snprintf(fmt, sizeof(fmt), "%%4d %%%ds %%7s %%s\n", level*2+5); - ::printf(fmt,level,""," ->LV: ",volume->GetName()); - ::printf(fmt,level,""," ->PV: ",current->GetName()); - ::printf(fmt,level,""," ->path:",_path.c_str()); - if ( num_children > 0 ) { - for(int i=0; i<num_children; ++i) { - TGeoNode* node = (TGeoNode*)nodes->At(i); - dumpStructure(PlacedVolume(node),level+1); + ::snprintf(fmt, sizeof(fmt), "%%4d %%%ds %%7s %%s\n", level * 2 + 5); + ::printf(fmt, level, "", " ->LV: ", volume->GetName()); + ::printf(fmt, level, "", " ->PV: ", current->GetName()); + ::printf(fmt, level, "", " ->path:", _path.c_str()); + if (num_children > 0) { + for (int i = 0; i < num_children; ++i) { + TGeoNode* node = (TGeoNode*) nodes->At(i); + dumpStructure(PlacedVolume(node), level + 1); } } - _path = _path.substr(0,_path.length()-1-strlen(current->GetName())); + _path = _path.substr(0, _path.length() - 1 - strlen(current->GetName())); } -static void dumpDetectors(DetElement parent,int level) { +static void dumpDetectors(DetElement parent, int level) { const DetElement::Children& children = parent.children(); PlacedVolume pl = parent.placement(); char fmt[128]; _path += "/"; _path += parent.name(); - ::snprintf(fmt, sizeof(fmt), "%%4d %%%ds %%7s %%s\n",level*2+5); - ::printf(fmt,level,"","->path:",_path.c_str()); - if ( pl.isValid() ) { - ::printf(fmt,level,""," ->placement:",parent.placementPath().c_str()); - ::printf(fmt,level,""," ->logvol: ",pl->GetVolume()->GetName()); - ::printf(fmt,level,""," ->shape: ",pl->GetVolume()->GetShape()->GetName()); + ::snprintf(fmt, sizeof(fmt), "%%4d %%%ds %%7s %%s\n", level * 2 + 5); + ::printf(fmt, level, "", "->path:", _path.c_str()); + if (pl.isValid()) { + ::printf(fmt, level, "", " ->placement:", parent.placementPath().c_str()); + ::printf(fmt, level, "", " ->logvol: ", pl->GetVolume()->GetName()); + ::printf(fmt, level, "", " ->shape: ", pl->GetVolume()->GetShape()->GetName()); } - for(DetElement::Children::const_iterator i=children.begin(); i!=children.end();++i) { - dumpDetectors((*i).second,level+1); + for (DetElement::Children::const_iterator i = children.begin(); i != children.end(); ++i) { + dumpDetectors((*i).second, level + 1); } - _path = _path.substr(0,_path.length()-1-strlen(parent.name())); + _path = _path.substr(0, _path.length() - 1 - strlen(parent.name())); } void GeometryTreeDump::create(DetElement top) { //PlacedVolume pv = top.placement(); - dumpDetectors(top,0); - dumpStructure(top.placement(),0); + dumpDetectors(top, 0); + dumpStructure(top.placement(), 0); //GeometryInfo geo; //collect(top,geo); //handleSetup(LCDD::getInstance().header()); diff --git a/DDCore/src/GeometryTreeDump.h b/DDCore/src/GeometryTreeDump.h index da82d9518..0bf1c8f6c 100644 --- a/DDCore/src/GeometryTreeDump.h +++ b/DDCore/src/GeometryTreeDump.h @@ -32,10 +32,12 @@ namespace DD4hep { * @author M.Frank * @version 1.0 */ - struct GeometryTreeDump : public GeoHandler { - GeometryTreeDump() {} + struct GeometryTreeDump: public GeoHandler { + GeometryTreeDump() { + } /// Standard destructor - virtual ~GeometryTreeDump() {} + virtual ~GeometryTreeDump() { + } /// Main entry point: create required object(s) void create(DetElement top); @@ -49,16 +51,15 @@ namespace DD4hep { /// Dump all constants in GDML format to output stream virtual void handleDefines(const LCDD::HandleMap& defs) const; /// Dump all visualisation specs in LCDD format to output stream - void handleVisualisation(const LCDD::HandleMap& vis) const; + void handleVisualisation(const LCDD::HandleMap& vis) const; /// Dump all solids in GDML format to output stream virtual void handleSolids(const SolidSet& solids) const; /// Dump Transformations in GDML format to output stream virtual void handleTransformations(const TransformSet& trafos) const; /// Dump structure information in GDML format to output stream - virtual void handleStructure(const VolumeSet& volset) const; + virtual void handleStructure(const VolumeSet& volset) const; }; } // End namespace Geometry } // End namespace DD4hep #endif // DD4HEP_GeometryTreeDump_H - diff --git a/DDCore/src/Handle.cpp b/DDCore/src/Handle.cpp index aed9497bf..410a294ea 100644 --- a/DDCore/src/Handle.cpp +++ b/DDCore/src/Handle.cpp @@ -16,7 +16,7 @@ #include "cxxabi.h" #endif -namespace DD4hep { +namespace DD4hep { XmlTools::Evaluator& evaluator(); } @@ -38,123 +38,130 @@ Counted::~Counted() { InstanceCount::decrement(this); } -int DD4hep::Geometry::_toInt(const string& value) { +int DD4hep::Geometry::_toInt(const string& value) { string s(value); size_t idx = s.find("(int)"); - if ( idx != string::npos ) - s.erase(idx,5); - while(s[0]==' ')s.erase(0,1); + if (idx != string::npos) + s.erase(idx, 5); + while (s[0] == ' ') + s.erase(0, 1); double result = eval.evaluate(s.c_str()); if (eval.status() != XmlTools::Evaluator::OK) { cerr << value << ": "; eval.print_error(); - throw runtime_error("DD4hep: Severe error during expression evaluation of "+value); + throw runtime_error("DD4hep: Severe error during expression evaluation of " + value); } - return (int)result; + return (int) result; } -long DD4hep::Geometry::_toLong(const string& value) { +long DD4hep::Geometry::_toLong(const string& value) { string s(value); size_t idx = s.find("(int)"); - if ( idx != string::npos ) - s.erase(idx,5); - while(s[0]==' ')s.erase(0,1); + if (idx != string::npos) + s.erase(idx, 5); + while (s[0] == ' ') + s.erase(0, 1); double result = eval.evaluate(s.c_str()); if (eval.status() != XmlTools::Evaluator::OK) { cerr << value << ": "; eval.print_error(); - throw runtime_error("DD4hep: Severe error during expression evaluation of "+value); + throw runtime_error("DD4hep: Severe error during expression evaluation of " + value); } - return (long)result; + return (long) result; } -bool DD4hep::Geometry::_toBool(const string& value) { +bool DD4hep::Geometry::_toBool(const string& value) { return value == "true"; } -float DD4hep::Geometry::_toFloat(const string& value) { +float DD4hep::Geometry::_toFloat(const string& value) { double result = eval.evaluate(value.c_str()); if (eval.status() != XmlTools::Evaluator::OK) { cerr << value << ": "; eval.print_error(); - throw runtime_error("DD4hep: Severe error during expression evaluation of "+value); + throw runtime_error("DD4hep: Severe error during expression evaluation of " + value); } - return (float)result; + return (float) result; } -double DD4hep::Geometry::_toDouble(const string& value) { +double DD4hep::Geometry::_toDouble(const string& value) { double result = eval.evaluate(value.c_str()); if (eval.status() != XmlTools::Evaluator::OK) { cerr << value << ": "; eval.print_error(); - throw runtime_error("DD4hep: Severe error during expression evaluation of "+value); + throw runtime_error("DD4hep: Severe error during expression evaluation of " + value); } return result; } -template <> int DD4hep::Geometry::_multiply<int>(const string& left, const string& right) { - return (int)_toDouble(left+"*"+right); +template <> int DD4hep::Geometry::_multiply<int>(const string& left, const string& right) { + return (int) _toDouble(left + "*" + right); } -template <> long DD4hep::Geometry::_multiply<long>(const string& left, const string& right) { - return (long)_toDouble(left+"*"+right); +template <> long DD4hep::Geometry::_multiply<long>(const string& left, const string& right) { + return (long) _toDouble(left + "*" + right); } -template <> float DD4hep::Geometry::_multiply<float>(const string& left, const string& right) { - return _toFloat(left+"*"+right); +template <> float DD4hep::Geometry::_multiply<float>(const string& left, const string& right) { + return _toFloat(left + "*" + right); } template <> double DD4hep::Geometry::_multiply<double>(const string& left, const string& right) { - return _toDouble(left+"*"+right); + return _toDouble(left + "*" + right); } -void DD4hep::Geometry::_toDictionary(const string& name, const string& value) { - string n=name, v=value; +void DD4hep::Geometry::_toDictionary(const string& name, const string& value) { + string n = name, v = value; size_t idx = v.find("(int)"); - if ( idx != string::npos ) - v.erase(idx,5); + if (idx != string::npos) + v.erase(idx, 5); idx = v.find("(float)"); - if ( idx != string::npos ) - v.erase(idx,7); - while(v[0]==' ')v.erase(0,1); + if (idx != string::npos) + v.erase(idx, 7); + while (v[0] == ' ') + v.erase(0, 1); double result = eval.evaluate(v.c_str()); if (eval.status() != XmlTools::Evaluator::OK) { cerr << value << ": "; eval.print_error(); - throw runtime_error("DD4hep: Severe error during expression evaluation "+name+"="+value); + throw runtime_error("DD4hep: Severe error during expression evaluation " + name + "=" + value); } - eval.setVariable(n.c_str(),result); + eval.setVariable(n.c_str(), result); } -string DD4hep::Geometry::_toString(bool value) { +string DD4hep::Geometry::_toString(bool value) { char text[32]; - ::snprintf(text,sizeof(text),"%s",value ? "true" : "false"); + ::snprintf(text, sizeof(text), "%s", value ? "true" : "false"); return text; } -string DD4hep::Geometry::_toString(int value) { +string DD4hep::Geometry::_toString(int value) { char text[32]; - ::snprintf(text,sizeof(text),"%d",value); + ::snprintf(text, sizeof(text), "%d", value); return text; } -string DD4hep::Geometry::_toString(float value) { +string DD4hep::Geometry::_toString(float value) { char text[32]; - ::snprintf(text,sizeof(text),"%f",value); + ::snprintf(text, sizeof(text), "%f", value); return text; } -string DD4hep::Geometry::_toString(double value) { +string DD4hep::Geometry::_toString(double value) { char text[32]; - ::snprintf(text,sizeof(text),"%f",value); + ::snprintf(text, sizeof(text), "%f", value); return text; } namespace DD4hep { namespace Geometry { static long s_numVerifies = 0; - long num_object_validations() { return s_numVerifies; } - void increment_object_validations() { ++s_numVerifies; } + long num_object_validations() { + return s_numVerifies; + } + void increment_object_validations() { + ++s_numVerifies; + } template <typename T> void Handle<T>::bad_assignment(const type_info& from, const type_info& to) { string msg = "Wrong assingment from "; @@ -166,15 +173,19 @@ namespace DD4hep { } template <typename T> void Handle<T>::assign(T* n, const string& nam, const string& tit) { this->m_element = n; - if ( !nam.empty() ) n->SetName(nam.c_str()); - if ( !tit.empty() ) n->SetTitle(tit.c_str()); + if (!nam.empty()) + n->SetName(nam.c_str()); + if (!tit.empty()) + n->SetTitle(tit.c_str()); } - template <typename T> const char* Handle<T>::name() const - { return this->m_element ? this->m_element->GetName() : ""; } + template <typename T> const char* Handle<T>::name() const { + return this->m_element ? this->m_element->GetName() : ""; + } - template <> const char* Handle<TObject>::name() const - { return ""; } + template <> const char* Handle<TObject>::name() const { + return ""; + } template <> void Handle<TObject>::bad_assignment(const type_info& from, const type_info& to) { string msg = "Wrong assingment from "; @@ -187,49 +198,49 @@ namespace DD4hep { } } -static const std::string __typeinfoName( const std::type_info& tinfo) { +static const std::string __typeinfoName(const std::type_info& tinfo) { const char* class_name = tinfo.name(); std::string result; #ifdef WIN32 size_t off = 0; - if ( ::strncmp(class_name, "class ", 6) == 0 ) { + if ( ::strncmp(class_name, "class ", 6) == 0 ) { // The returned name is prefixed with "class " off = 6; } - if ( ::strncmp(class_name, "struct ", 7) == 0 ) { + if ( ::strncmp(class_name, "struct ", 7) == 0 ) { // The returned name is prefixed with "struct " off = 7; } - if ( off != std::string::npos ) { + if ( off != std::string::npos ) { std::string tmp = class_name + off; size_t loc = 0; - while( (loc = tmp.find("class ")) != std::string::npos ) { + while( (loc = tmp.find("class ")) != std::string::npos ) { tmp.erase(loc, 6); } loc = 0; - while( (loc = tmp.find("struct ")) != std::string::npos ) { + while( (loc = tmp.find("struct ")) != std::string::npos ) { tmp.erase(loc, 7); } result = tmp; } - else { + else { result = class_name; } // Change any " *" to "*" - while ( (off=result.find(" *")) != std::string::npos ) { + while ( (off=result.find(" *")) != std::string::npos ) { result.replace(off, 2, "*"); } // Change any " &" to "&" - while ( (off=result.find(" &")) != std::string::npos ) { + while ( (off=result.find(" &")) != std::string::npos ) { result.replace(off, 2, "&"); } #elif defined(sun) result = class_name; #elif !defined(__ICC) - if ( ::strlen(class_name) == 1 ) { + if (::strlen(class_name) == 1) { // See http://www.realitydiluted.com/mirrors/reality.sgi.com/dehnert_engr/cxx/abi.pdf // for details - switch(class_name[0]) { + switch (class_name[0]) { case 'v': result = "void"; break; @@ -292,10 +303,10 @@ static const std::string __typeinfoName( const std::type_info& tinfo) { break; } } - else { - char buff[16*1024]; + else { + char buff[16 * 1024]; size_t len = sizeof(buff); - int status = 0; + int status = 0; result = __cxxabiv1::__cxa_demangle(class_name, buff, &len, &status); } #else @@ -309,21 +320,22 @@ string DD4hep::typeName(const type_info& typ) { return __typeinfoName(typ); } - - #include "DDSegmentation/Segmentation.h" typedef DDSegmentation::Segmentation _Segmentation; //INSTANTIATE_UNNAMED(_Segmentation); -namespace DD4hep { namespace Geometry { +namespace DD4hep { + namespace Geometry { template <> void Handle<_Segmentation>::assign(_Segmentation* s, const std::string& n, const std::string& t) { this->m_element = s; s->setType(t); s->setName(n); } - template <> const char* Handle<_Segmentation>::name() const - { return this->m_element ? this->m_element->name().c_str() : ""; } + template <> const char* Handle<_Segmentation>::name() const { + return this->m_element ? this->m_element->name().c_str() : ""; + } template struct DD4hep::Geometry::Handle<_Segmentation>; -}} + } +} #include "DD4hep/LCDD.h" #include "TMap.h" diff --git a/DDCore/src/IDDescriptor.cpp b/DDCore/src/IDDescriptor.cpp index 6ad1307eb..97677ed7b 100644 --- a/DDCore/src/IDDescriptor.cpp +++ b/DDCore/src/IDDescriptor.cpp @@ -18,112 +18,113 @@ using namespace DD4hep::Geometry; using DDSegmentation::BitField64; using DDSegmentation::BitFieldValue; - -namespace { +namespace { void _construct(IDDescriptor::Object* o, const string& dsc) { BitField64& bf = *o; o->fieldIDs.clear(); o->fieldMap.clear(); - o->description = dsc ; - for(size_t i=0; i < bf.size(); ++i) { + o->description = dsc; + for (size_t i = 0; i < bf.size(); ++i) { IDDescriptor::Field f = &bf[i]; - o->fieldIDs.push_back(make_pair(i,f->name())); - o->fieldMap.push_back(make_pair(f->name(),f)); + o->fieldIDs.push_back(make_pair(i, f->name())); + o->fieldMap.push_back(make_pair(f->name(), f)); } } } /// Standard constructor -IDDescriptor::Object::Object(const std::string& desc) : TNamed(), BitField64(desc) /*, maxBit(0) */ { +IDDescriptor::Object::Object(const std::string& desc) + : TNamed(), BitField64(desc) /*, maxBit(0) */{ InstanceCount::increment(this); } /// Default destructor -IDDescriptor::Object::~Object() { +IDDescriptor::Object::~Object() { InstanceCount::decrement(this); } - + /// Initializing constructor -IDDescriptor::IDDescriptor(const string& description) -{ +IDDescriptor::IDDescriptor(const string& description) { Object* obj = new Object(description); - assign(obj,description,"iddescriptor"); + assign(obj, description, "iddescriptor"); _construct(obj, description); } /// Acces string representation -string IDDescriptor::toString() const { - if ( isValid() ) { +string IDDescriptor::toString() const { + if (isValid()) { return m_element->GetName(); } return "----"; } -std::string IDDescriptor::fieldDescription() const { - BitField64* bf = data<Object>() ; - return bf->fieldDescription() ; +std::string IDDescriptor::fieldDescription() const { + BitField64* bf = data<Object>(); + return bf->fieldDescription(); } /// The total number of encoding bits for this descriptor -unsigned IDDescriptor::maxBit() const { +unsigned IDDescriptor::maxBit() const { return data<Object>()->highestBit(); } -/// Access the field-id container -const IDDescriptor::FieldIDs& IDDescriptor::ids() const { - if ( isValid() ) { +/// Access the field-id container +const IDDescriptor::FieldIDs& IDDescriptor::ids() const { + if (isValid()) { return data<Object>()->fieldIDs; } throw runtime_error("DD4hep: Attempt to access an invalid IDDescriptor object."); } -/// Access the fieldmap container -const IDDescriptor::FieldMap& IDDescriptor::fields() const { - if ( isValid() ) { - return data<Object>()->fieldMap; +/// Access the fieldmap container +const IDDescriptor::FieldMap& IDDescriptor::fields() const { + if (isValid()) { + return data<Object>()->fieldMap; } throw runtime_error("DD4hep: Attempt to access an invalid IDDescriptor object."); } /// Get the field descriptor of one field by name -IDDescriptor::Field IDDescriptor::field(const string& field_name) const { - const FieldMap& m = fields(); // This already checks the object validity - for(FieldMap::const_iterator i=m.begin(); i!=m.end(); ++i) - if ( (*i).first == field_name ) return (*i).second; - throw runtime_error("DD4hep: "+string(name())+": This ID descriptor has no field with the name:"+field_name); +IDDescriptor::Field IDDescriptor::field(const string& field_name) const { + const FieldMap& m = fields(); // This already checks the object validity + for (FieldMap::const_iterator i = m.begin(); i != m.end(); ++i) + if ((*i).first == field_name) + return (*i).second; + throw runtime_error("DD4hep: " + string(name()) + ": This ID descriptor has no field with the name:" + field_name); } /// Get the field descriptor of one field by its identifier -IDDescriptor::Field IDDescriptor::field(size_t identifier) const { - const FieldMap& m = fields(); // This already checks the object validity +IDDescriptor::Field IDDescriptor::field(size_t identifier) const { + const FieldMap& m = fields(); // This already checks the object validity return m[identifier].second; } /// Get the field identifier of one field by name -size_t IDDescriptor::fieldID(const string& field_name) const { - const FieldIDs& m = ids(); // This already checks the object validity - for(FieldIDs::const_iterator i=m.begin(); i!=m.end(); ++i) - if ( (*i).second == field_name ) return (*i).first; - throw runtime_error("DD4hep: "+string(name())+": This ID descriptor has no field with the name:"+field_name); +size_t IDDescriptor::fieldID(const string& field_name) const { + const FieldIDs& m = ids(); // This already checks the object validity + for (FieldIDs::const_iterator i = m.begin(); i != m.end(); ++i) + if ((*i).second == field_name) + return (*i).first; + throw runtime_error("DD4hep: " + string(name()) + ": This ID descriptor has no field with the name:" + field_name); } /// Encode a set of volume identifiers (corresponding to this description of course!) to a volumeID. -VolumeID IDDescriptor::encode(const std::vector<VolID>& ids) const { +VolumeID IDDescriptor::encode(const std::vector<VolID>& ids) const { typedef std::vector<VolID> VolIds; VolumeID id = 0; - for(VolIds::const_iterator i=ids.begin(); i!=ids.end(); ++i) { + for (VolIds::const_iterator i = ids.begin(); i != ids.end(); ++i) { Field f = field((*i).first); - id |= f->value((*i).second<<f->offset())<<f->offset(); + id |= f->value((*i).second << f->offset()) << f->offset(); } return id; } /// Decode volume IDs and return filled descriptor with all fields -void IDDescriptor::decodeFields(VolumeID vid, VolIDFields& fields) { +void IDDescriptor::decodeFields(VolumeID vid, VolIDFields& fields) { fields.clear(); - if ( isValid() ) { + if (isValid()) { const vector<BitFieldValue*>& v = data<Object>()->fields(); - for(vector<BitFieldValue*>::const_iterator i=v.begin(); i != v.end(); ++i) - fields.push_back(VolIDField(*i,(*i)->value(vid))); + for (vector<BitFieldValue*>::const_iterator i = v.begin(); i != v.end(); ++i) + fields.push_back(VolIDField(*i, (*i)->value(vid))); return; } throw runtime_error("DD4hep: Attempt to access an invalid IDDescriptor object."); @@ -131,5 +132,5 @@ void IDDescriptor::decodeFields(VolumeID vid, VolIDFields& fields) { /// Access the BitField64 object BitField64* IDDescriptor::decoder() { - return data<Object>(); + return data<Object>(); } diff --git a/DDCore/src/InstanceCount.cpp b/DDCore/src/InstanceCount.cpp index 82dd9093f..4651006a0 100644 --- a/DDCore/src/InstanceCount.cpp +++ b/DDCore/src/InstanceCount.cpp @@ -22,16 +22,20 @@ using namespace DD4hep; /// Do not clutter global namespace namespace { typedef InstanceCount::Counter COUNT; - typedef std::map<const std::type_info*, COUNT*> TypeCounter; - typedef std::map<const std::string*, COUNT*> StringCounter; + typedef std::map<const std::type_info*, COUNT*> TypeCounter; + typedef std::map<const std::string*, COUNT*> StringCounter; static bool s_trace_instances = ::getenv("DD4HEP_TRACE") != 0; - static std::auto_ptr<TypeCounter> s_typCounts(new TypeCounter()); - static std::auto_ptr<StringCounter> s_strCounts(new StringCounter()); + static std::auto_ptr<TypeCounter> s_typCounts(new TypeCounter()); + static std::auto_ptr<StringCounter> s_strCounts(new StringCounter()); static InstanceCount::Counter s_nullCount; static InstanceCount::Counter s_thisCount; - static InstanceCount s_counter; - inline TypeCounter& types() { return *(s_typCounts.get()); } - inline StringCounter& strings() { return *(s_strCounts.get()); } + static InstanceCount s_counter; + inline TypeCounter& types() { + return *(s_typCounts.get()); + } + inline StringCounter& strings() { + return *(s_strCounts.get()); + } } /// Standard Constructor @@ -41,73 +45,71 @@ InstanceCount::InstanceCount() { /// Standard destructor InstanceCount::~InstanceCount() { s_thisCount.decrement(); - if ( 0 == s_thisCount.value() ) { + if (0 == s_thisCount.value()) { StringCounter::iterator i; - TypeCounter::iterator j; + TypeCounter::iterator j; dump(s_trace_instances ? ALL : NONE); - for(i=s_strCounts->begin(); i != s_strCounts->end(); ++i) + for (i = s_strCounts->begin(); i != s_strCounts->end(); ++i) delete (*i).second; - for(j=s_typCounts->begin(); j != s_typCounts->end(); ++j) + for (j = s_typCounts->begin(); j != s_typCounts->end(); ++j) delete (*j).second; s_strCounts->clear(); s_typCounts->clear(); } } /// Check if tracing is enabled. -bool InstanceCount::doTrace() { +bool InstanceCount::doTrace() { return s_trace_instances; } /// Enable/Disable tracing -void InstanceCount::doTracing(bool value) { +void InstanceCount::doTracing(bool value) { s_trace_instances = value; } /// Access counter object for local caching on optimizations -InstanceCount::Counter* InstanceCount::getCounter(const std::type_info& typ) { +InstanceCount::Counter* InstanceCount::getCounter(const std::type_info& typ) { Counter* cnt = s_trace_instances ? types()[&typ] : &s_nullCount; - return (0!=cnt) ? cnt : types()[&typ] = new Counter(); + return (0 != cnt) ? cnt : types()[&typ] = new Counter(); } /// Access counter object for local caching on optimizations InstanceCount::Counter* InstanceCount::getCounter(const std::string& typ) { Counter* cnt = s_trace_instances ? strings()[&typ] : &s_nullCount; - return (0!=cnt) ? cnt : strings()[&typ] = new Counter(); + return (0 != cnt) ? cnt : strings()[&typ] = new Counter(); } /// Force dump of counters -void InstanceCount::dump(int typ) { +void InstanceCount::dump(int typ) { bool need_footer = false; - if ( (typ & STRING) && s_strCounts.get() ) { - if ( s_strCounts->begin() != s_strCounts->end() ) { + if ((typ & STRING) && s_strCounts.get()) { + if (s_strCounts->begin() != s_strCounts->end()) { StringCounter::const_iterator i; std::cout << "+----------------------------------------------------------------+" << std::endl; std::cout << "| I n s t a n c e c o u n t e r s b y N A M E |" << std::endl; std::cout << "+----------+---------+-------------------------------------------+" << std::endl; std::cout << "| Total | Leaking | Type identifier |" << std::endl; std::cout << "+----------+---------+-------------------------------------------+" << std::endl; - for(i=s_strCounts->begin(); i != s_strCounts->end(); ++i) { - std::cout << "|" << std::setw(10) << (*i).second->total() - << "|" << std::setw(9) << (*i).second->value() - << "|" << (*i).first << std::endl; + for (i = s_strCounts->begin(); i != s_strCounts->end(); ++i) { + std::cout << "|" << std::setw(10) << (*i).second->total() << "|" << std::setw(9) << (*i).second->value() << "|" + << (*i).first << std::endl; } need_footer = true; } } - if ( (typ & TYPEINFO) && s_typCounts.get() ) { - if ( s_typCounts->begin() != s_typCounts->end() ) { + if ((typ & TYPEINFO) && s_typCounts.get()) { + if (s_typCounts->begin() != s_typCounts->end()) { TypeCounter::const_iterator i; std::cout << "+----------------------------------------------------------------+" << std::endl; std::cout << "| I n s t a n c e c o u n t e r s b y T Y P E I N F O |" << std::endl; std::cout << "+----------+---------+-------------------------------------------+" << std::endl; std::cout << "| Total | Leaking | Type identifier |" << std::endl; std::cout << "+----------+---------+-------------------------------------------+" << std::endl; - for(i=s_typCounts->begin(); i != s_typCounts->end(); ++i) { - std::cout << "|" << std::setw(10) << (*i).second->total() - << "|" << std::setw(9) << (*i).second->value() - << "|" << typeName(*((*i).first)) << std::endl; + for (i = s_typCounts->begin(); i != s_typCounts->end(); ++i) { + std::cout << "|" << std::setw(10) << (*i).second->total() << "|" << std::setw(9) << (*i).second->value() << "|" + << typeName(*((*i).first)) << std::endl; } need_footer = true; - } + } } - if ( need_footer ) { + if (need_footer) { std::cout << "+----------+-------+-------------------------------------------+" << std::endl; } } diff --git a/DDCore/src/LCDDImp.cpp b/DDCore/src/LCDDImp.cpp index a41eea292..718e458ea 100644 --- a/DDCore/src/LCDDImp.cpp +++ b/DDCore/src/LCDDImp.cpp @@ -26,30 +26,39 @@ #include "XML/DocumentHandler.h" #if DD4HEP_USE_PYROOT - #include "TPython.h" +#include "TPython.h" #endif #ifndef __TIXML__ #include "xercesc/dom/DOMException.hpp" -namespace DD4hep { namespace XML { - typedef xercesc::DOMException XmlException; -}} +namespace DD4hep { + namespace XML { + typedef xercesc::DOMException XmlException; + } +} #endif using namespace DD4hep::Geometry; using namespace DD4hep; using namespace std; namespace { - struct TopDetElement : public DetElement { - TopDetElement(const string& nam, Volume vol) : DetElement(nam,/* "structure", */0) { object<Object>().volume = vol; } + struct TopDetElement: public DetElement { + TopDetElement(const string& nam, Volume vol) + : DetElement(nam,/* "structure", */0) { + object<Object>().volume = vol; + } }; struct TypePreserve { LCDDBuildType& m_t; - TypePreserve(LCDDBuildType& t) : m_t(t) { } - ~TypePreserve() { m_t = BUILD_NONE; } + TypePreserve(LCDDBuildType& t) + : m_t(t) { + } + ~TypePreserve() { + m_t = BUILD_NONE; + } }; struct ExtensionEntry { - int id; + int id; }; typedef map<const type_info*, ExtensionEntry> ExtensionMap; static int s_extensionID = 0; @@ -61,25 +70,24 @@ namespace { } LCDD& LCDD::getInstance() { - if ( !s_lcdd ) s_lcdd = new LCDDImp(); - return *s_lcdd; + if (!s_lcdd) + s_lcdd = new LCDDImp(); + return *s_lcdd; } /// Destroy the instance -void LCDD::destroyInstance() { - if ( s_lcdd ) delete s_lcdd; +void LCDD::destroyInstance() { + if (s_lcdd) + delete s_lcdd; s_lcdd = 0; } /// Default constructor -LCDDImp::LCDDImp() - : m_world(), m_trackers(), m_worldVol(), m_trackingVol(), m_field("global"), - m_buildType(BUILD_NONE) -{ +LCDDImp::LCDDImp() + : m_world(), m_trackers(), m_worldVol(), m_trackingVol(), m_field("global"), m_buildType(BUILD_NONE) { InstanceCount::increment(this); m_properties = new Properties(); - if ( 0 == gGeoManager ) - { + if (0 == gGeoManager) { gGeoManager = new TGeoManager(); } { @@ -88,12 +96,12 @@ LCDDImp::LCDDImp() m_manager->SetCurrentNavigator(0); //cout << "Navigator:" << (void*)m_manager->GetCurrentNavigator() << endl; } - //if ( 0 == gGeoIdentity ) + //if ( 0 == gGeoIdentity ) { gGeoIdentity = new TGeoIdentity(); } VisAttr attr("invisible"); - attr.setColor(0.5,0.5,0.5); + attr.setColor(0.5, 0.5, 0.5); attr.setAlpha(1); attr.setLineStyle(VisAttr::SOLID); attr.setDrawingStyle(VisAttr::SOLID); @@ -110,15 +118,15 @@ LCDDImp::~LCDDImp() { destroyHandle(m_header); destroyHandle(m_volManager); destroyObject(m_properties); - for_each(m_readouts.begin(), m_readouts.end(), destroyHandles(m_readouts)); - for_each(m_idDict.begin(), m_idDict.end(), destroyHandles(m_idDict)); - for_each(m_limits.begin(), m_limits.end(), destroyHandles(m_limits)); - for_each(m_regions.begin(), m_regions.end(), destroyHandles(m_regions)); - for_each(m_alignments.begin(), m_alignments.end(), destroyHandles(m_alignments)); - for_each(m_sensitive.begin(), m_sensitive.end(), destroyHandles(m_sensitive)); - for_each(m_display.begin(), m_display.end(), destroyHandles(m_display)); - for_each(m_fields.begin(), m_fields.end(), destroyHandles(m_fields)); - for_each(m_define.begin(), m_define.end(), destroyHandles(m_define)); + for_each(m_readouts.begin(), m_readouts.end(), destroyHandles(m_readouts)); + for_each(m_idDict.begin(), m_idDict.end(), destroyHandles(m_idDict)); + for_each(m_limits.begin(), m_limits.end(), destroyHandles(m_limits)); + for_each(m_regions.begin(), m_regions.end(), destroyHandles(m_regions)); + for_each(m_alignments.begin(), m_alignments.end(), destroyHandles(m_alignments)); + for_each(m_sensitive.begin(), m_sensitive.end(), destroyHandles(m_sensitive)); + for_each(m_display.begin(), m_display.end(), destroyHandles(m_display)); + for_each(m_fields.begin(), m_fields.end(), destroyHandles(m_fields)); + for_each(m_define.begin(), m_define.end(), destroyHandles(m_define)); m_trackers.clear(); m_worldVol.clear(); @@ -131,15 +139,15 @@ LCDDImp::~LCDDImp() { } /// Add an extension object to the detector element -void* LCDDImp::addUserExtension(void* ptr, const std::type_info& info) { +void* LCDDImp::addUserExtension(void* ptr, const std::type_info& info) { Extensions::iterator j = m_extensions.find(&info); - if ( j == m_extensions.end() ) { + if (j == m_extensions.end()) { ExtensionMap& m = lcdd_extensions(); ExtensionMap::iterator i = m.find(&info); - if ( i == m.end() ) { + if (i == m.end()) { ExtensionEntry entry; entry.id = ++s_extensionID; - m.insert(make_pair(&info,entry)); + m.insert(make_pair(&info, entry)); i = m.find(&info); } ExtensionEntry& e = (*i).second; @@ -147,24 +155,24 @@ void* LCDDImp::addUserExtension(void* ptr, const std::type_info& info) { return m_extensions[&info] = ptr; } throw runtime_error("DD4hep: LCDD::addUserExtension: The object " - " already has an extension of type:"+string(info.name())+"."); + " already has an extension of type:" + string(info.name()) + "."); } /// Access an existing extension object from the detector element -void* LCDDImp::userExtension(const std::type_info& info) const { +void* LCDDImp::userExtension(const std::type_info& info) const { Extensions::const_iterator j = m_extensions.find(&info); - if ( j != m_extensions.end() ) { + if (j != m_extensions.end()) { return (*j).second; } throw runtime_error("DD4hep: LCDD::userExtension: The object " - " has no extension of type:"+string(info.name())+"."); + " has no extension of type:" + string(info.name()) + "."); } -Volume LCDDImp::pickMotherVolume(const DetElement&) const { // throw if not existing +Volume LCDDImp::pickMotherVolume(const DetElement&) const { // throw if not existing return m_worldVol; } -LCDD& LCDDImp::addDetector(const Ref_t& x) { +LCDD& LCDDImp::addDetector(const Ref_t& x) { m_detectors.append(x); m_world.add(DetElement(x)); return *this; @@ -173,8 +181,9 @@ LCDD& LCDDImp::addDetector(const Ref_t& x) { /// Typed access to constants: access string values string LCDDImp::constantAsString(const string& name) const { Ref_t c = constant(name); - if ( c.isValid() ) return c->GetTitle(); - throw runtime_error("LCDD: The constant "+name+" is not known to the system."); + if (c.isValid()) + return c->GetTitle(); + throw runtime_error("LCDD: The constant " + name + " is not known to the system."); } /// Typed access to constants: long values @@ -195,75 +204,78 @@ LCDD& LCDDImp::addField(const Ref_t& x) { } /// Retrieve a matrial by it's name from the detector description -Material LCDDImp::material(const string& name) const { +Material LCDDImp::material(const string& name) const { TGeoMedium* mat = m_manager->GetMedium(name.c_str()); - if ( mat ) { + if (mat) { return Material(Ref_t(mat)); } - throw runtime_error("Cannot find a material the reference name:"+name); + throw runtime_error("Cannot find a material the reference name:" + name); } -Handle<TObject> LCDDImp::getRefChild(const HandleMap& e, const string& name, bool do_throw) const { +Handle<TObject> LCDDImp::getRefChild(const HandleMap& e, const string& name, bool do_throw) const { HandleMap::const_iterator i = e.find(name); - if ( i != e.end() ) { + if (i != e.end()) { return (*i).second; } - if ( do_throw ) { - throw runtime_error("Cannot find a child with the reference name:"+name); + if (do_throw) { + throw runtime_error("Cannot find a child with the reference name:" + name); } return 0; } namespace { - struct ShapePatcher : public GeoScan { + struct ShapePatcher: public GeoScan { VolumeManager m_volManager; - DetElement m_world; - ShapePatcher(VolumeManager m, DetElement e) : GeoScan(e), m_volManager(m), m_world(e) {} - void patchShapes() { + DetElement m_world; + ShapePatcher(VolumeManager m, DetElement e) + : GeoScan(e), m_volManager(m), m_world(e) { + } + void patchShapes() { GeoHandler::Data& data = *m_data; string nam; cout << "++ Patching names of anonymous shapes...." << endl; - for(GeoHandler::Data::const_reverse_iterator i=data.rbegin(); i != data.rend(); ++i) { - int level = (*i).first; + for (GeoHandler::Data::const_reverse_iterator i = data.rbegin(); i != data.rend(); ++i) { + int level = (*i).first; const GeoHandler::Data::mapped_type& v = (*i).second; - for(GeoHandler::Data::mapped_type::const_iterator j=v.begin(); j != v.end(); ++j) { + for (GeoHandler::Data::mapped_type::const_iterator j = v.begin(); j != v.end(); ++j) { const TGeoNode* n = *j; - TGeoVolume* v = n->GetVolume(); - TGeoShape* s = v->GetShape(); - const char* sn = s->GetName(); - if ( 0 == sn || 0 == ::strlen(sn) ) { + TGeoVolume* v = n->GetVolume(); + TGeoShape* s = v->GetShape(); + const char* sn = s->GetName(); + if (0 == sn || 0 == ::strlen(sn)) { nam = v->GetName(); nam += "_shape"; s->SetName(nam.c_str()); } - else if ( 0 == ::strcmp(sn,s->IsA()->GetName()) ) { + else if (0 == ::strcmp(sn, s->IsA()->GetName())) { nam = v->GetName(); nam += "_shape"; s->SetName(nam.c_str()); } - else { - nam = sn; - if ( nam.find("_shape") == string::npos ) nam += "_shape"; + else { + nam = sn; + if (nam.find("_shape") == string::npos) + nam += "_shape"; s->SetName(nam.c_str()); - } - if ( s->IsA() == TGeoCompositeShape::Class() ) { - TGeoCompositeShape* c = (TGeoCompositeShape*)s; + } + if (s->IsA() == TGeoCompositeShape::Class()) { + TGeoCompositeShape* c = (TGeoCompositeShape*) s; const TGeoBoolNode* boolean = c->GetBoolNode(); - s = boolean->GetLeftShape(); - sn = s->GetName(); - if ( 0 == sn || 0 == ::strlen(sn) ) { - s->SetName((nam+"_left").c_str()); - } - else if ( 0 == ::strcmp(sn,s->IsA()->GetName()) ) { - s->SetName((nam+"_left").c_str()); - } - s = boolean->GetRightShape(); - sn = s->GetName(); - if ( 0 == sn || 0 == ::strlen(sn) ) { - s->SetName((nam+"_right").c_str()); - } - else if ( 0 == ::strcmp(s->GetName(),s->IsA()->GetName()) ) { - s->SetName((nam+"_right").c_str()); + s = boolean->GetLeftShape(); + sn = s->GetName(); + if (0 == sn || 0 == ::strlen(sn)) { + s->SetName((nam + "_left").c_str()); + } + else if (0 == ::strcmp(sn, s->IsA()->GetName())) { + s->SetName((nam + "_left").c_str()); + } + s = boolean->GetRightShape(); + sn = s->GetName(); + if (0 == sn || 0 == ::strlen(sn)) { + s->SetName((nam + "_right").c_str()); + } + else if (0 == ::strcmp(s->GetName(), s->IsA()->GetName())) { + s->SetName((nam + "_right").c_str()); } } } @@ -273,9 +285,9 @@ namespace { } -void LCDDImp::endDocument() { +void LCDDImp::endDocument() { TGeoManager* mgr = m_manager; - if ( !mgr->IsClosed() ) { + if (!mgr->IsClosed()) { LCDD& lcdd = *this; #if 0 @@ -286,16 +298,16 @@ void LCDDImp::endDocument() { m_trackingVol.setRegion(trackingRegion); // Set the tracking volume to invisible. VisAttr trackingVis("TrackingVis"); - trackingVis.setVisible(false); + trackingVis.setVisible(false); m_trackingVol.setVisAttributes(trackingVis); - add(trackingVis); + add(trackingVis); #endif // Set the world volume to invisible. VisAttr worldVis("WorldVis"); worldVis.setAlpha(1.0); worldVis.setVisible(false); worldVis.setShowDaughters(true); - worldVis.setColor(1.0,1.0,1.0); + worldVis.setColor(1.0, 1.0, 1.0); worldVis.setLineStyle(VisAttr::SOLID); worldVis.setDrawingStyle(VisAttr::WIREFRAME); m_worldVol.setVisAttributes(worldVis); @@ -304,82 +316,81 @@ void LCDDImp::endDocument() { /// Since we allow now for anonymous shapes, /// we will rename them to use the name of the volume they are assigned to mgr->CloseGeometry(); - ShapePatcher patcher(m_volManager,m_world); + ShapePatcher patcher(m_volManager, m_world); patcher.patchShapes(); } } -void LCDDImp::init() { - if ( !m_world.isValid() ) { +void LCDDImp::init() { + if (!m_world.isValid()) { TGeoManager* mgr = m_manager; - Box worldSolid("world_box","world_x","world_y","world_z"); - std::cout << " *********** created World volume with size : " << worldSolid->GetDX() << ", " << worldSolid->GetDY() << ", " << worldSolid->GetDZ() << std::endl ; + Box worldSolid("world_x", "world_y", "world_z"); + std::cout << " *********** created World volume with size : " << worldSolid->GetDX() << ", " << worldSolid->GetDY() << ", " + << worldSolid->GetDZ() << std::endl; Material vacuum = material("Vacuum"); - Material air = material("Air"); - Volume world("world_volume",worldSolid,air); + Material air = material("Air"); + Volume world("world_volume", worldSolid, air); - m_world = TopDetElement("world",world); - m_worldVol = world; + m_world = TopDetElement("world", world); + m_worldVol = world; #if 0 - Tube trackingSolid("tracking_cylinder", - 0., - _toDouble("tracking_region_radius"), - _toDouble("2*tracking_region_zmax"),2*M_PI); + Tube trackingSolid(0., + _toDouble("tracking_region_radius"), + _toDouble("2*tracking_region_zmax"),2*M_PI); Volume tracking("tracking_volume",trackingSolid, air); - m_trackers = TopDetElement("tracking",tracking); - m_trackingVol = tracking; - PlacedVolume pv = m_worldVol.placeVolume(tracking); + m_trackers = TopDetElement("tracking",tracking); + m_trackingVol = tracking; + PlacedVolume pv = m_worldVol.placeVolume(tracking); m_trackers.setPlacement(pv); m_world.add(m_trackers); #endif - m_materialAir = air; + m_materialAir = air; m_materialVacuum = vacuum; m_detectors.append(m_world); m_manager->SetTopVolume(m_worldVol); - m_world.setPlacement(PlacedVolume(mgr->GetTopNode())); + m_world.setPlacement(PlacedVolume(mgr->GetTopNode())); } } void LCDDImp::fromXML(const string& xmlfile, LCDDBuildType build_type) { - TypePreserve build_type_preserve(m_buildType=build_type); + TypePreserve build_type_preserve(m_buildType = build_type); #if DD4HEP_USE_PYROOT string cmd; TPython::Exec("import lcdd"); cmd = "lcdd.fromXML('" + xmlfile + "')"; - TPython::Exec(cmd.c_str()); + TPython::Exec(cmd.c_str()); #else XML::Handle_t xml_root = XML::DocumentHandler().load(xmlfile).root(); string tag = xml_root.tag(); try { LCDD* lcdd = this; string type = tag + "_XML_reader"; - long result = PluginService::Create<long>(type,lcdd,&xml_root); - if ( 0 == result ) { + long result = PluginService::Create<long>(type, lcdd, &xml_root); + if (0 == result) { PluginDebug dbg; - PluginService::Create<long>(type,lcdd,&xml_root); + PluginService::Create<long>(type, lcdd, &xml_root); throw runtime_error("DD4hep: Failed to locate plugin to interprete files of type" - " \""+tag+"\" - no factory:"+type+". "+dbg.missingFactory(type)); + " \"" + tag + "\" - no factory:" + type + ". " + dbg.missingFactory(type)); } - result = *(long*)result; - if ( result != 1 ) { - throw runtime_error("DD4hep: Failed to parse the XML file "+xmlfile+" with the plugin "+type); + result = *(long*) result; + if (result != 1) { + throw runtime_error("DD4hep: Failed to parse the XML file " + xmlfile + " with the plugin " + type); } } - catch(const XML::XmlException& e) { - throw runtime_error(XML::_toString(e.msg)+ - "\nDD4hep: XML-DOM Exception while parsing "+xmlfile); - } - catch(const exception& e) { - throw runtime_error(string(e.what())+"\nDD4hep: while parsing "+xmlfile); + catch (const XML::XmlException& e) { + throw runtime_error(XML::_toString(e.msg) + "\nDD4hep: XML-DOM Exception while parsing " + xmlfile); + } + catch (const exception& e) { + throw runtime_error(string(e.what()) + "\nDD4hep: while parsing " + xmlfile); } - catch(...) { - throw runtime_error("DD4hep: UNKNOWN exception while parsing "+xmlfile); + catch (...) { + throw runtime_error("DD4hep: UNKNOWN exception while parsing " + xmlfile); } #endif } -void LCDDImp::dump() const { +void LCDDImp::dump() const { TGeoManager* mgr = m_manager; mgr->SetVisLevel(4); mgr->SetVisOption(1); @@ -387,27 +398,27 @@ void LCDDImp::dump() const { } /// Manipulate geometry using facroy converter -void LCDDImp::apply(const char* factory_type, int argc, char** argv) { +void LCDDImp::apply(const char* factory_type, int argc, char** argv) { string fac = factory_type; try { - long result = PluginService::Create<long>(fac,(LCDD*)this,argc,argv); - if ( 0 == result ) { + long result = PluginService::Create<long>(fac, (LCDD*) this, argc, argv); + if (0 == result) { PluginDebug dbg; - PluginService::Create<long>(fac,(LCDD*)this,argc,argv); - throw runtime_error("DD4hep: apply-plugin: Failed to locate plugin "+fac+". "+dbg.missingFactory(fac)); + PluginService::Create<long>(fac, (LCDD*) this, argc, argv); + throw runtime_error("DD4hep: apply-plugin: Failed to locate plugin " + fac + ". " + dbg.missingFactory(fac)); } - result = *(long*)result; - if ( result != 1 ) { - throw runtime_error("DD4hep: apply-plugin: Failed to execute plugin "+fac); + result = *(long*) result; + if (result != 1) { + throw runtime_error("DD4hep: apply-plugin: Failed to execute plugin " + fac); } } - catch(const XML::XmlException& e) { - throw runtime_error(XML::_toString(e.msg)+"\nDD4hep: XML-DOM Exception with plugin:"+fac); - } - catch(const exception& e) { - throw runtime_error(string(e.what())+"\nDD4hep: with plugin:"+fac); + catch (const XML::XmlException& e) { + throw runtime_error(XML::_toString(e.msg) + "\nDD4hep: XML-DOM Exception with plugin:" + fac); + } + catch (const exception& e) { + throw runtime_error(string(e.what()) + "\nDD4hep: with plugin:" + fac); } - catch(...) { - throw runtime_error("UNKNOWN exception from plugin:"+fac); + catch (...) { + throw runtime_error("UNKNOWN exception from plugin:" + fac); } } diff --git a/DDCore/src/LCDDImp.h b/DDCore/src/LCDDImp.h index 2014dc4af..11c88607c 100644 --- a/DDCore/src/LCDDImp.h +++ b/DDCore/src/LCDDImp.h @@ -23,79 +23,85 @@ class TGeoManager; * DD4hep namespace declaration */ namespace DD4hep { - + /* * XML namespace declaration */ - namespace Geometry { + namespace Geometry { - class LCDDImp : public LCDD { + class LCDDImp: public LCDD { private: /// Disable copy constructor - LCDDImp(const LCDDImp&) {} + LCDDImp(const LCDDImp&) { + } /// Disable assignment operator - LCDDImp& operator=(const LCDDImp&) { return *this; } + LCDDImp& operator=(const LCDDImp&) { + return *this; + } public: - struct InvalidObjectError : public std::runtime_error { - InvalidObjectError(const std::string& msg) : std::runtime_error("DD4hep: "+msg) {} + struct InvalidObjectError: public std::runtime_error { + InvalidObjectError(const std::string& msg) + : std::runtime_error("DD4hep: " + msg) { + } }; - - struct ObjectHandleMap : public HandleMap { - ObjectHandleMap() {} - void append(const Ref_t& e, bool throw_on_doubles=true) { - if ( e.isValid() ) { + + struct ObjectHandleMap: public HandleMap { + ObjectHandleMap() { + } + void append(const Ref_t& e, bool throw_on_doubles = true) { + if (e.isValid()) { std::string n = e.name(); - std::pair<iterator,bool> r = this->insert(std::make_pair(n,e.ptr())); - if ( !throw_on_doubles || r.second ) - return; - throw InvalidObjectError("Attempt to add an already existing object:"+std::string(e.name())+"."); + std::pair<iterator, bool> r = this->insert(std::make_pair(n, e.ptr())); + if (!throw_on_doubles || r.second) + return; + throw InvalidObjectError("Attempt to add an already existing object:" + std::string(e.name()) + "."); } throw InvalidObjectError("Attempt to add an invalid object."); } - template <typename T> void append(const Ref_t& e, bool throw_on_doubles=true) { + template <typename T> void append(const Ref_t& e, bool throw_on_doubles = true) { T* obj = dynamic_cast<T*>(e.ptr()); - if ( obj ) { - this->append(e,throw_on_doubles); - return; + if (obj) { + this->append(e, throw_on_doubles); + return; } throw InvalidObjectError("Attempt to add an object, which is of the wrong type."); } }; - - TGeoManager* m_manager; - ObjectHandleMap m_readouts; - ObjectHandleMap m_idDict; - ObjectHandleMap m_limits; - ObjectHandleMap m_regions; - ObjectHandleMap m_detectors; - ObjectHandleMap m_alignments; - - ObjectHandleMap m_sensitive; - ObjectHandleMap m_display; - ObjectHandleMap m_fields; - + + TGeoManager* m_manager; + ObjectHandleMap m_readouts; + ObjectHandleMap m_idDict; + ObjectHandleMap m_limits; + ObjectHandleMap m_regions; + ObjectHandleMap m_detectors; + ObjectHandleMap m_alignments; + + ObjectHandleMap m_sensitive; + ObjectHandleMap m_display; + ObjectHandleMap m_fields; + // GDML fields - ObjectHandleMap m_define; - - DetElement m_world; - DetElement m_trackers; - Volume m_worldVol; - Volume m_trackingVol; - VolumeManager m_volManager; - - Material m_materialAir; - Material m_materialVacuum; - VisAttr m_invisibleVis; - OverlayedField m_field; - Ref_t m_header; - Properties* m_properties; - LCDDBuildType m_buildType; + ObjectHandleMap m_define; + + DetElement m_world; + DetElement m_trackers; + Volume m_worldVol; + Volume m_trackingVol; + VolumeManager m_volManager; + + Material m_materialAir; + Material m_materialVacuum; + VisAttr m_invisibleVis; + OverlayedField m_field; + Ref_t m_header; + Properties* m_properties; + LCDDBuildType m_buildType; /// Definition of the extension type - typedef std::map<const std::type_info*,void*> Extensions; - Extensions m_extensions; + typedef std::map<const std::type_info*, void*> Extensions; + Extensions m_extensions; /// Default constructor LCDDImp(); @@ -104,15 +110,18 @@ namespace DD4hep { virtual ~LCDDImp(); /// Access flag to steer the detail of building of the geometry/detector description - virtual LCDDBuildType buildType() const { return m_buildType; } - + virtual LCDDBuildType buildType() const { + return m_buildType; + } + /// Read compact geometry description or alignment file - virtual void fromCompact(const std::string& fname, LCDDBuildType type=BUILD_DEFAULT) - { fromXML(fname,type); } + virtual void fromCompact(const std::string& fname, LCDDBuildType type = BUILD_DEFAULT) { + fromXML(fname, type); + } /// Read any XML file - virtual void fromXML(const std::string& fname,LCDDBuildType type=BUILD_DEFAULT); - + virtual void fromXML(const std::string& fname, LCDDBuildType type = BUILD_DEFAULT); + virtual void dump() const; /// Manipulate geometry using facroy converter @@ -124,138 +133,232 @@ namespace DD4hep { /// Add an extension object to the detector element virtual void* addUserExtension(void* ptr, const std::type_info& info); /// Access an existing extension object from the detector element - virtual void* userExtension(const std::type_info& info) const; + virtual void* userExtension(const std::type_info& info) const; - virtual Handle<TObject> getRefChild(const HandleMap& e, const std::string& name, bool throw_if_not=true) const; - virtual Volume pickMotherVolume(const DetElement& sd) const; + virtual Handle<TObject> getRefChild(const HandleMap& e, const std::string& name, bool throw_if_not = true) const; + virtual Volume pickMotherVolume(const DetElement& sd) const; /// Access the geometry manager of this instance - virtual TGeoManager& manager() const { return *m_manager; } + virtual TGeoManager& manager() const { + return *m_manager; + } /// Access to properties - Properties& properties() const { return *m_properties; } + Properties& properties() const { + return *m_properties; + } /// Return handle to material describing air - virtual Material air() const { return m_materialVacuum; } + virtual Material air() const { + return m_materialVacuum; + } /// Return handle to material describing vacuum - virtual Material vacuum() const { return m_materialAir; } + virtual Material vacuum() const { + return m_materialAir; + } /// Return handle to "invisible" visualization attributes - virtual VisAttr invisible() const { return m_invisibleVis; } + virtual VisAttr invisible() const { + return m_invisibleVis; + } /// Return reference to the top-most (world) detector element - virtual DetElement world() const { return m_world; } + virtual DetElement world() const { + return m_world; + } /// Return reference to detector element with all tracker devices. - virtual DetElement trackers() const { return m_trackers; } + virtual DetElement trackers() const { + return m_trackers; + } /// Return handle to the world volume containing everything - virtual Volume worldVolume() const { return m_worldVol; } + virtual Volume worldVolume() const { + return m_worldVol; + } /// Return handle to the world volume containing the volume with the tracking devices - virtual Volume trackingVolume() const { return m_trackingVol; } + virtual Volume trackingVolume() const { + return m_trackingVol; + } /// Return handle to the VolumeManager - virtual VolumeManager volumeManager() const { return m_volManager; } + virtual VolumeManager volumeManager() const { + return m_volManager; + } /// Return handle to the combined electromagentic field description. - virtual OverlayedField field() const { return m_field; } + virtual OverlayedField field() const { + return m_field; + } /// Accessor to the header entry - virtual Header header() const { return m_header; } + virtual Header header() const { + return m_header; + } /// Accessor to the header entry - virtual void setHeader(Header h) { m_header = h; } + virtual void setHeader(Header h) { + m_header = h; + } /// Typed access to constants: access string values - virtual std::string constantAsString(const std::string& name) const; + virtual std::string constantAsString(const std::string& name) const; /// Typed access to constants: long values - virtual long constantAsLong(const std::string& name) const; + virtual long constantAsLong(const std::string& name) const; /// Typed access to constants: double values - virtual double constantAsDouble(const std::string& name) const; + virtual double constantAsDouble(const std::string& name) const; /// Retrieve a constant by it's name from the detector description - virtual Constant constant(const std::string& name) const - { return getRefChild(m_define,name); } + virtual Constant constant(const std::string& name) const { + return getRefChild(m_define, name); + } /// Retrieve a limitset by it's name from the detector description - virtual LimitSet limitSet(const std::string& name) const - { return getRefChild(m_limits,name); } + virtual LimitSet limitSet(const std::string& name) const { + return getRefChild(m_limits, name); + } /// Retrieve a visualization attribute by it's name from the detector description - virtual VisAttr visAttributes(const std::string& name) const - { return getRefChild(m_display,name,false); } + virtual VisAttr visAttributes(const std::string& name) const { + return getRefChild(m_display, name, false); + } /// Retrieve a matrial by it's name from the detector description - virtual Material material(const std::string& name) const; + virtual Material material(const std::string& name) const; /// Retrieve a region object by it's name from the detector description - virtual Region region(const std::string& name) const - { return getRefChild(m_regions,name); } + virtual Region region(const std::string& name) const { + return getRefChild(m_regions, name); + } /// Retrieve a id descriptor by it's name from the detector description - virtual IDDescriptor idSpecification(const std::string& name) const - { return getRefChild(m_idDict,name); } + virtual IDDescriptor idSpecification(const std::string& name) const { + return getRefChild(m_idDict, name); + } /// Retrieve a readout object by it's name from the detector description - virtual Readout readout(const std::string& name) const - { return getRefChild(m_readouts,name); } + virtual Readout readout(const std::string& name) const { + return getRefChild(m_readouts, name); + } /// Retrieve an alignment entry by it's name from the detector description - virtual AlignmentEntry alignment(const std::string& path) const - { return getRefChild(alignments(),path); } + virtual AlignmentEntry alignment(const std::string& path) const { + return getRefChild(alignments(), path); + } /// Retrieve a subdetector element by it's name from the detector description - virtual DetElement detector(const std::string& name) const - { return getRefChild(m_detectors,name); } + virtual DetElement detector(const std::string& name) const { + return getRefChild(m_detectors, name); + } /// Retrieve a sensitive detector by it's name from the detector description - virtual SensitiveDetector sensitiveDetector(const std::string& name) const - { return getRefChild(m_sensitive,name,false); } + virtual SensitiveDetector sensitiveDetector(const std::string& name) const { + return getRefChild(m_sensitive, name, false); + } /// Retrieve a subdetector element by it's name from the detector description - virtual CartesianField field(const std::string& name) const - { return getRefChild(m_fields,name,false); } - + virtual CartesianField field(const std::string& name) const { + return getRefChild(m_fields, name, false); + } + /// Accessor to the map of constants - virtual const HandleMap& constants() const { return m_define; } + virtual const HandleMap& constants() const { + return m_define; + } /// Accessor to the map of visualisation attributes - virtual const HandleMap& visAttributes() const { return m_display; } + virtual const HandleMap& visAttributes() const { + return m_display; + } /// Accessor to the map of limit settings - virtual const HandleMap& limitsets() const { return m_limits; } + virtual const HandleMap& limitsets() const { + return m_limits; + } /// Accessor to the map of region settings - virtual const HandleMap& regions() const { return m_regions; } + virtual const HandleMap& regions() const { + return m_regions; + } /// Accessor to the map of readout structures - virtual const HandleMap& readouts() const { return m_readouts; } + virtual const HandleMap& readouts() const { + return m_readouts; + } /// Accessor to the map of sub-detectors - virtual const HandleMap& detectors() const { return m_detectors; } + virtual const HandleMap& detectors() const { + return m_detectors; + } /// Accessor to the map of aligment entries - virtual const HandleMap& alignments() const { return m_alignments; } + virtual const HandleMap& alignments() const { + return m_alignments; + } /// Accessor to the map of field entries, which together form the global field - virtual const HandleMap& fields() const { return m_fields; } + virtual const HandleMap& fields() const { + return m_fields; + } #define __R return *this /// Add a new constant to the detector description - virtual LCDD& add(Constant x) { return addConstant(x); } + virtual LCDD& add(Constant x) { + return addConstant(x); + } /// Add a new limit set to the detector description - virtual LCDD& add(LimitSet x) { return addLimitSet(x); } + virtual LCDD& add(LimitSet x) { + return addLimitSet(x); + } /// Add a new detector region to the detector description - virtual LCDD& add(Region x) { return addRegion(x); } + virtual LCDD& add(Region x) { + return addRegion(x); + } /// Add a new visualisation attribute to the detector description - virtual LCDD& add(VisAttr x) { return addVisAttribute(x); } + virtual LCDD& add(VisAttr x) { + return addVisAttribute(x); + } /// Add a new id descriptor to the detector description - virtual LCDD& add(IDDescriptor x) { return addIDSpecification(x); } + virtual LCDD& add(IDDescriptor x) { + return addIDSpecification(x); + } /// Add alignment entry to the detector description - virtual LCDD& add(AlignmentEntry x) { return addAlignment(x); } + virtual LCDD& add(AlignmentEntry x) { + return addAlignment(x); + } /// Add a new detector readout to the detector description - virtual LCDD& add(Readout x) { return addReadout(x); } + virtual LCDD& add(Readout x) { + return addReadout(x); + } /// Add a new subdetector to the detector description - virtual LCDD& add(DetElement x) { return addDetector(x); } + virtual LCDD& add(DetElement x) { + return addDetector(x); + } /// Add a field component to the detector description - virtual LCDD& add(CartesianField x) { return addField(x); } - + virtual LCDD& add(CartesianField x) { + return addField(x); + } + /// Add a new constant by named reference to the detector description - virtual LCDD& addConstant(const Ref_t& x) { m_define.append(x,false); __R;} + virtual LCDD& addConstant(const Ref_t& x) { + m_define.append(x, false); + __R; + } /// Add a new limit set by named reference to the detector description - virtual LCDD& addLimitSet(const Ref_t& x) { m_limits.append(x); __R;} + virtual LCDD& addLimitSet(const Ref_t& x) { + m_limits.append(x); + __R; + } /// Add a new detector region by named reference to the detector description - virtual LCDD& addRegion(const Ref_t& x) { m_regions.append(x); __R;} + virtual LCDD& addRegion(const Ref_t& x) { + m_regions.append(x); + __R; + } /// Add a new id descriptor by named reference to the detector description - virtual LCDD& addIDSpecification(const Ref_t& x) { m_idDict.append(x); __R;} + virtual LCDD& addIDSpecification(const Ref_t& x) { + m_idDict.append(x); + __R; + } /// Add a new detector readout by named reference to the detector description - virtual LCDD& addReadout(const Ref_t& x) { m_readouts.append(x); __R;} + virtual LCDD& addReadout(const Ref_t& x) { + m_readouts.append(x); + __R; + } /// Add a new visualisation attribute by named reference to the detector description - virtual LCDD& addVisAttribute(const Ref_t& x) { m_display.append(x); __R;} + virtual LCDD& addVisAttribute(const Ref_t& x) { + m_display.append(x); + __R; + } /// Add a new sensitive detector by named reference to the detector description - virtual LCDD& addSensitiveDetector(const Ref_t& x){ m_sensitive.append(x); __R;} + virtual LCDD& addSensitiveDetector(const Ref_t& x) { + m_sensitive.append(x); + __R; + } /// Add a new subdetector by named reference to the detector description virtual LCDD& addDetector(const Ref_t& x); /// Add a new alignment entry by named reference to the detector description - virtual LCDD& addAlignment(const Ref_t& x) { m_alignments.append(x); __R;} + virtual LCDD& addAlignment(const Ref_t& x) { + m_alignments.append(x); + __R; + } /// Add a field component by named reference to the detector description virtual LCDD& addField(const Ref_t& x); #undef __R - + }; } -} /* End namespace DD4hep */ +} /* End namespace DD4hep */ #endif /* DD4hep_LCDDGEOIMP_H */ diff --git a/DDCore/src/MatrixHelpers.cpp b/DDCore/src/MatrixHelpers.cpp index d42aec7ed..9a69f5450 100644 --- a/DDCore/src/MatrixHelpers.cpp +++ b/DDCore/src/MatrixHelpers.cpp @@ -18,39 +18,39 @@ TGeoIdentity* DD4hep::Geometry::identityTransform() { } TGeoTranslation* DD4hep::Geometry::_translation(const Position& pos) { - return new TGeoTranslation("",pos.X()*MM_2_CM,pos.Y()*MM_2_CM,pos.Z()*MM_2_CM); + return new TGeoTranslation("", pos.X() * MM_2_CM, pos.Y() * MM_2_CM, pos.Z() * MM_2_CM); } TGeoRotation* DD4hep::Geometry::_rotationZYX(const RotationZYX& rot) { - return new TGeoRotation("",rot.Phi()*RAD_2_DEGREE,rot.Theta()*RAD_2_DEGREE,rot.Psi()*RAD_2_DEGREE); + return new TGeoRotation("", rot.Phi() * RAD_2_DEGREE, rot.Theta() * RAD_2_DEGREE, rot.Psi() * RAD_2_DEGREE); } -TGeoRotation* DD4hep::Geometry::_rotation3D(const Rotation3D& rot3D) { +TGeoRotation* DD4hep::Geometry::_rotation3D(const Rotation3D& rot3D) { EulerAngles rot(rot3D); - return new TGeoRotation("",rot.Phi()*RAD_2_DEGREE,rot.Theta()*RAD_2_DEGREE,rot.Psi()*RAD_2_DEGREE); + return new TGeoRotation("", rot.Phi() * RAD_2_DEGREE, rot.Theta() * RAD_2_DEGREE, rot.Psi() * RAD_2_DEGREE); } -TGeoHMatrix* DD4hep::Geometry::_transform(const Transform3D& trans) { +TGeoHMatrix* DD4hep::Geometry::_transform(const Transform3D& trans) { #if 0 TGeoHMatrix* tr = new TGeoHMatrix(); - Double_t* t = tr->GetTranslation(); - Double_t* r = tr->GetRotationMatrix(); + Double_t* t = tr->GetTranslation(); + Double_t* r = tr->GetRotationMatrix(); trans.GetComponents(r[0],r[1],r[2],t[0],r[3],r[4],r[5],t[1],r[6],r[7],r[8],t[2]); t[0] *= MM_2_CM; t[1] *= MM_2_CM; t[2] *= MM_2_CM; #endif - double t[3]; + double t[3]; RotationZYX rot; - Position pos; - trans.GetDecomposition(rot,pos); + Position pos; + trans.GetDecomposition(rot, pos); TGeoHMatrix *tr = new TGeoHMatrix(); - tr->RotateZ(rot.Phi()*RAD_2_DEGREE); - tr->RotateY(rot.Theta()*RAD_2_DEGREE); - tr->RotateX(rot.Psi()*RAD_2_DEGREE); + tr->RotateZ(rot.Phi() * RAD_2_DEGREE); + tr->RotateY(rot.Theta() * RAD_2_DEGREE); + tr->RotateX(rot.Psi() * RAD_2_DEGREE); pos.GetCoordinates(t); - tr->SetDx(t[0]*MM_2_CM); - tr->SetDy(t[1]*MM_2_CM); - tr->SetDz(t[2]*MM_2_CM); + tr->SetDx(t[0] * MM_2_CM); + tr->SetDy(t[1] * MM_2_CM); + tr->SetDz(t[2] * MM_2_CM); return tr; } diff --git a/DDCore/src/MatrixHelpers.h b/DDCore/src/MatrixHelpers.h index d74b53dab..41c6ff58f 100644 --- a/DDCore/src/MatrixHelpers.h +++ b/DDCore/src/MatrixHelpers.h @@ -26,15 +26,15 @@ namespace DD4hep { /* * Geometry namespace declaration */ - namespace Geometry { + namespace Geometry { - TGeoIdentity* identityTransform(); + TGeoIdentity* identityTransform(); TGeoTranslation* _translation(const Position& pos); - TGeoRotation* _rotationZYX(const RotationZYX& rot); - TGeoRotation* _rotation3D(const Rotation3D& rot); - TGeoHMatrix* _transform(const Transform3D& trans); + TGeoRotation* _rotationZYX(const RotationZYX& rot); + TGeoRotation* _rotation3D(const Rotation3D& rot); + TGeoHMatrix* _transform(const Transform3D& trans); - } /* End namespace Geometry */ -} /* End namespace DD4hep */ + } /* End namespace Geometry */ +} /* End namespace DD4hep */ #endif // DD4HEP_IMP_MATRIXHELPERS_H diff --git a/DDCore/src/Objects.cpp b/DDCore/src/Objects.cpp index adae1bfb2..3ae550ebb 100644 --- a/DDCore/src/Objects.cpp +++ b/DDCore/src/Objects.cpp @@ -27,48 +27,49 @@ using namespace std; using namespace DD4hep::Geometry; /// Constructor to be used when creating a new DOM tree -Author::Author(LCDD& /* lcdd */) { - m_element = new TNamed("","author"); +Author::Author(LCDD& /* lcdd */) { + m_element = new TNamed("", "author"); } /// Access the auhor's name -std::string Author::authorName() const { +std::string Author::authorName() const { return m_element->GetName(); } /// Set the author's name -void Author::setAuthorName(const std::string& nam) { +void Author::setAuthorName(const std::string& nam) { m_element->SetName(nam.c_str()); } /// Access the auhor's email address -std::string Author::authorEmail() const { +std::string Author::authorEmail() const { return m_element->GetTitle(); } /// Set the author's email address -void Author::setAuthorEmail(const std::string& addr) { +void Author::setAuthorEmail(const std::string& addr) { m_element->SetTitle(addr.c_str()); } /// Standard constructor -Header::Object::Object() : TNamed() { +Header::Object::Object() + : TNamed() { InstanceCount::increment(this); } /// Default destructor -Header::Object::~Object() { +Header::Object::~Object() { InstanceCount::decrement(this); } /// Constructor to be used when creating a new DOM tree -Header::Header(const string& author, const string& url) { +Header::Header(const string& author, const string& url) { Object* ptr = new Object(); - assign(ptr,author, url); + assign(ptr, author, url); } /// Accessor to object name -const std::string Header::name() const { +const std::string Header::name() const { return m_element->GetName(); } @@ -78,7 +79,7 @@ void Header::setName(const std::string& new_name) { } /// Accessor to object title -const std::string Header::title() const { +const std::string Header::title() const { return m_element->GetTitle(); } @@ -88,7 +89,7 @@ void Header::setTitle(const std::string& new_title) { } /// Accessor to object url -const std::string& Header::url() const { +const std::string& Header::url() const { return data<Object>()->url; } @@ -98,7 +99,7 @@ void Header::setUrl(const std::string& new_url) { } /// Accessor to object author -const std::string& Header::author() const { +const std::string& Header::author() const { return data<Object>()->author; } @@ -108,7 +109,7 @@ void Header::setAuthor(const std::string& new_author) { } /// Accessor to object status -const std::string& Header::status() const { +const std::string& Header::status() const { return data<Object>()->status; } @@ -118,7 +119,7 @@ void Header::setStatus(const std::string& new_status) { } /// Accessor to object version -const std::string& Header::version() const { +const std::string& Header::version() const { return data<Object>()->version; } @@ -128,7 +129,7 @@ void Header::setVersion(const std::string& new_version) { } /// Accessor to object comment -const std::string& Header::comment() const { +const std::string& Header::comment() const { return data<Object>()->comment; } @@ -138,21 +139,19 @@ void Header::setComment(const std::string& new_comment) { } /// Constructor to be used when creating a new DOM tree -Constant::Constant(const string& nam, const string& val) -{ - m_element = new TNamed(nam.c_str(),val.c_str()); +Constant::Constant(const string& nam, const string& val) { + m_element = new TNamed(nam.c_str(), val.c_str()); } /// Constructor to be used when creating a new DOM tree -Constant::Constant(const string& name) { - m_element = new TNamed(name.c_str(),""); +Constant::Constant(const string& name) { + m_element = new TNamed(name.c_str(), ""); } /// String representation of this object -string Constant::toString() const { +string Constant::toString() const { stringstream os; - os << m_element->GetName() << " \"" << m_element->GetTitle() - << "\" Value:" << _toDouble(m_element->GetTitle()); + os << m_element->GetName() << " \"" << m_element->GetTitle() << "\" Value:" << _toDouble(m_element->GetTitle()); return os.str(); } @@ -160,7 +159,7 @@ string Constant::toString() const { Atom::Atom(const string& name, const string& formula, int Z, int N, double density) { TGeoElementTable* t = TGeoElement::GetElementTable(); TGeoElement* e = t->FindElement(name.c_str()); - if ( !e ) { + if (!e) { t->AddElement(name.c_str(), formula.c_str(), Z, N, density); e = t->FindElement(name.c_str()); } @@ -169,233 +168,232 @@ Atom::Atom(const string& name, const string& formula, int Z, int N, double densi /// Access the radiation length of the underlying material double Material::radLength() const { - Handle<TGeoMedium> val(*this); - if ( val.isValid() ) { + Handle < TGeoMedium > val(*this); + if (val.isValid()) { TGeoMaterial* m = val->GetMaterial(); - if ( m ) return m->GetRadLen(); - throw runtime_error("DD4hep: The medium "+string(val->GetName())+" has an invalid material reference!"); + if (m) + return m->GetRadLen(); + throw runtime_error("DD4hep: The medium " + string(val->GetName()) + " has an invalid material reference!"); } throw runtime_error("DD4hep: Attempt to access radiation length from invalid material handle!"); } /// Access the radiation length of the underlying material double Material::intLength() const { - Handle<TGeoMedium> val(*this); - if ( val.isValid() ) { + Handle < TGeoMedium > val(*this); + if (val.isValid()) { TGeoMaterial* m = val->GetMaterial(); - if ( m ) return m->GetIntLen(); - throw runtime_error("The medium "+string(val->GetName())+" has an invalid material reference!"); + if (m) + return m->GetIntLen(); + throw runtime_error("The medium " + string(val->GetName()) + " has an invalid material reference!"); } throw runtime_error("Attempt to access interaction length from invalid material handle!"); } /// String representation of this object -string Material::toString() const { - Handle<TGeoMedium> val(*this); +string Material::toString() const { + Handle < TGeoMedium > val(*this); stringstream os; - os << val->GetName() << " " << val->GetTitle() << " id:" << hex << val->GetId() - << " Pointer:" << val->GetPointerName(); + os << val->GetName() << " " << val->GetTitle() << " id:" << hex << val->GetId() << " Pointer:" << val->GetPointerName(); return os.str(); } /// Standard constructor -VisAttr::Object::Object() - : magic(magic_word()), col(0), color(0), alpha(0), - drawingStyle(SOLID), lineStyle(SOLID), - showDaughters(true), visible(true) -{ +VisAttr::Object::Object() + : magic(magic_word()), col(0), color(0), alpha(0), drawingStyle(SOLID), lineStyle(SOLID), showDaughters(true), visible(true) { InstanceCount::increment(this); } /// Default destructor -VisAttr::Object::~Object() { +VisAttr::Object::~Object() { InstanceCount::decrement(this); } /// Constructor to be used when creating a new DOM tree -VisAttr::VisAttr(const string& name) { +VisAttr::VisAttr(const string& name) { Object* obj = new Object(); assign(obj, name, "vis"); - obj->color = 2; - setLineStyle(SOLID); + obj->color = 2; + setLineStyle (SOLID); setDrawingStyle(SOLID); setShowDaughters(true); setAlpha(0.1f); } /// Get Flag to show/hide daughter elements -bool VisAttr::showDaughters() const { +bool VisAttr::showDaughters() const { return object<Object>().showDaughters; } /// Set Flag to show/hide daughter elements -void VisAttr::setShowDaughters(bool value) { +void VisAttr::setShowDaughters(bool value) { object<Object>().showDaughters = value; } /// Get visibility flag -bool VisAttr::visible() const { +bool VisAttr::visible() const { return object<Object>().visible; } /// Set visibility flag -void VisAttr::setVisible(bool value) { +void VisAttr::setVisible(bool value) { object<Object>().visible = value; } /// Get line style -int VisAttr::lineStyle() const { +int VisAttr::lineStyle() const { return object<Object>().lineStyle; } /// Set line style -void VisAttr::setLineStyle(int value) { +void VisAttr::setLineStyle(int value) { object<Object>().lineStyle = value; } /// Get drawing style -int VisAttr::drawingStyle() const { +int VisAttr::drawingStyle() const { return object<Object>().drawingStyle; } /// Set drawing style -void VisAttr::setDrawingStyle(int value) { +void VisAttr::setDrawingStyle(int value) { object<Object>().drawingStyle = value; } /// Get alpha value -float VisAttr::alpha() const { +float VisAttr::alpha() const { //TNamed* obj = first_value<TNamed>(*this); //obj->SetAlpha(value); return object<Object>().alpha; } /// Set alpha value -void VisAttr::setAlpha(float value) { +void VisAttr::setAlpha(float value) { object<Object>().alpha = value; //TNamed* obj = first_value<TNamed>(*this); //obj->SetAlpha(value); } /// Get object color -int VisAttr::color() const { +int VisAttr::color() const { return object<Object>().color; } /// Set object color -void VisAttr::setColor(float red, float green, float blue) { +void VisAttr::setColor(float red, float green, float blue) { Object& o = object<Object>(); - o.color = TColor::GetColor(red,green,blue); - o.col = gROOT->GetColor(o.color); + o.color = TColor::GetColor(red, green, blue); + o.col = gROOT->GetColor(o.color); } /// Get RGB values of the color (if valid) bool VisAttr::rgb(float& red, float& green, float& blue) const { Object& o = object<Object>(); - if ( o.col ) { - TColor* c = (TColor*)o.col; - c->GetRGB(red,green,blue); + if (o.col) { + TColor* c = (TColor*) o.col; + c->GetRGB(red, green, blue); return true; } return false; } /// String representation of this object -string VisAttr::toString() const { +string VisAttr::toString() const { const VisAttr::Object* obj = &object<Object>(); TColor* col = gROOT->GetColor(obj->color); char text[256]; - ::snprintf(text,sizeof(text), - "%-20s RGB:%-8s [%d] %7.2f Style:%d %d ShowDaughters:%3s Visible:%3s", - ptr()->GetName(),col->AsHexString(), obj->color, col->GetAlpha(), - int(obj->drawingStyle), int(obj->lineStyle), - obj->showDaughters ? "YES" : "NO", obj->visible ? "YES" : "NO"); + ::snprintf(text, sizeof(text), "%-20s RGB:%-8s [%d] %7.2f Style:%d %d ShowDaughters:%3s Visible:%3s", ptr()->GetName(), + col->AsHexString(), obj->color, col->GetAlpha(), int(obj->drawingStyle), int(obj->lineStyle), + obj->showDaughters ? "YES" : "NO", obj->visible ? "YES" : "NO"); return text; } /// Constructor to be used when creating a new aligment entry -AlignmentEntry::AlignmentEntry(const string& path) { +AlignmentEntry::AlignmentEntry(const string& path) { TGeoPhysicalNode* obj = new TGeoPhysicalNode(path.c_str()); - assign(obj,path,"*"); + assign(obj, path, "*"); } /// Align the PhysicalNode (translation only) int AlignmentEntry::align(const Position& pos, bool check, double overlap) { - return align(pos,RotationZYX(),check,overlap); + return align(pos, RotationZYX(), check, overlap); } /// Align the PhysicalNode (rotation only) int AlignmentEntry::align(const RotationZYX& rot, bool check, double overlap) { - return align(Position(),rot,check,overlap); + return align(Position(), rot, check, overlap); } /// Align the PhysicalNode (translation + rotation) int AlignmentEntry::align(const Position& pos, const RotationZYX& rot, bool check, double overlap) { - if ( isValid() ) { + if (isValid()) { TGeoHMatrix* new_matrix = dynamic_cast<TGeoHMatrix*>(m_element->GetOriginalMatrix()->MakeClone()); - TGeoRotation rotation("",rot.Phi()*RAD_2_DEGREE,rot.Theta()*RAD_2_DEGREE,rot.Psi()*RAD_2_DEGREE); - TGeoCombiTrans m(pos.X(),pos.Y(),pos.Z(),0); + TGeoRotation rotation("", rot.Phi() * RAD_2_DEGREE, rot.Theta() * RAD_2_DEGREE, rot.Psi() * RAD_2_DEGREE); + TGeoCombiTrans m(pos.X(), pos.Y(), pos.Z(), 0); m.SetRotation(rotation); new_matrix->Multiply(&m); - m_element->Align(new_matrix,0,check,overlap); + m_element->Align(new_matrix, 0, check, overlap); return 1; } throw runtime_error("DD4hep: Cannot align non existing physical node."); } - /// Assignment operator -Limit& Limit::operator=(const Limit& c) { - if ( this != &c ) { +Limit& Limit::operator=(const Limit& c) { + if (this != &c) { particles = c.particles; - name = c.name; - unit = c.unit; - value = c.value; - content = c.content; + name = c.name; + unit = c.unit; + value = c.value; + content = c.content; } return *this; } /// Equality operator bool Limit::operator==(const Limit& c) const { - return value==c.value && name==c.name && particles == c.particles; + return value == c.value && name == c.name && particles == c.particles; } /// operator less -bool Limit::operator< (const Limit& c) const { - if ( value < c.value ) return true; - if ( name < c.name ) return true; - if ( particles < c.particles ) return true; +bool Limit::operator<(const Limit& c) const { + if (value < c.value) + return true; + if (name < c.name) + return true; + if (particles < c.particles) + return true; return false; } /// Conversion to a string representation -string Limit::toString() const { +string Limit::toString() const { string res = name + " = " + content; - if ( !unit.empty() ) res += unit + " "; + if (!unit.empty()) + res += unit + " "; res + " (" + particles + ")"; return res; } /// Standard constructor -LimitSet::Object::Object() { +LimitSet::Object::Object() { InstanceCount::increment(this); } /// Default destructor -LimitSet::Object::~Object() { +LimitSet::Object::~Object() { InstanceCount::decrement(this); } /// Constructor to be used when creating a new DOM tree -LimitSet::LimitSet(const string& name) { - assign(new Object(),name,"limitset"); +LimitSet::LimitSet(const string& name) { + assign(new Object(), name, "limitset"); } /// Add new limit. Returns true if the new limit was added, false if it already existed. -bool LimitSet::addLimit(const Limit& limit) { - pair<Object::iterator,bool> ret = data<Object>()->insert(limit); +bool LimitSet::addLimit(const Limit& limit) { + pair<Object::iterator, bool> ret = data<Object>()->insert(limit); return ret.second; } @@ -405,19 +403,18 @@ const set<Limit>& LimitSet::limits() const { return *o; } - /// Standard constructor -Region::Object::Object() { +Region::Object::Object() { InstanceCount::increment(this); } /// Default destructor -Region::Object::~Object() { +Region::Object::~Object() { InstanceCount::decrement(this); } /// Constructor to be used when creating a new DOM tree -Region::Region(const string& name) { +Region::Region(const string& name) { Object* p = new Object(); assign(p, name, "region"); p->magic = magic_word(); @@ -428,27 +425,27 @@ Region::Region(const string& name) { p->cut = 10.0; } -Region& Region::setStoreSecondaries(bool value) { +Region& Region::setStoreSecondaries(bool value) { object<Object>().store_secondaries = value; return *this; } -Region& Region::setThreshold(double value) { +Region& Region::setThreshold(double value) { object<Object>().threshold = value; return *this; } -Region& Region::setCut(double value) { +Region& Region::setCut(double value) { object<Object>().cut = value; return *this; } -Region& Region::setLengthUnit(const string& unit) { +Region& Region::setLengthUnit(const string& unit) { object<Object>().lunit = unit; return *this; } -Region& Region::setEnergyUnit(const string& unit) { +Region& Region::setEnergyUnit(const string& unit) { object<Object>().eunit = unit; return *this; } @@ -474,12 +471,12 @@ bool Region::storeSecondaries() const { } /// Access the length unit -const std::string& Region::lengthUnit() const { +const std::string& Region::lengthUnit() const { return object<Object>().lunit; } /// Access the energy unit -const std::string& Region::energyUnit() const { +const std::string& Region::energyUnit() const { return object<Object>().eunit; } @@ -488,26 +485,26 @@ const std::string& Region::energyUnit() const { #if 0 /** @class IDSpec Objects.h - * + * * @author M.Frank * @version 1.0 */ -struct IDSpec : public Ref_t { +struct IDSpec : public Ref_t { /// Constructor to be used when reading the already parsed DOM tree - template <typename Q> + template <typename Q> IDSpec(const Handle<Q>& e) : Ref_t(e) {} /// Constructor to be used when creating a new DOM tree IDSpec(LCDD& doc, const std::string& name, const IDDescriptor& dsc); void addField(const std::string& name, const std::pair<int,int>& field); }; -IDSpec::IDSpec(LCDD& lcdd, const string& name, const IDDescriptor& dsc) +IDSpec::IDSpec(LCDD& lcdd, const string& name, const IDDescriptor& dsc) : RefElement(doc,Tag_idspec,name) { const IDDescriptor::FieldIDs& f = dsc.ids(); const IDDescriptor::FieldMap& m = dsc.fields(); object<Object>().Attr_length = dsc.maxBit(); - for(IDDescriptor::FieldIDs::const_iterator i=f.begin(); i!=f.end();++i) { + for(IDDescriptor::FieldIDs::const_iterator i=f.begin(); i!=f.end();++i) { int ident = (*i).first; const string& nam = (*i).second; const pair<int,int>& fld = m.find(nam)->second; @@ -515,11 +512,11 @@ IDSpec::IDSpec(LCDD& lcdd, const string& name, const IDDescriptor& dsc) } } -void IDSpec::addField(const string& name, const pair<int,int>& field) { +void IDSpec::addField(const string& name, const pair<int,int>& field) { addField(Strng_t(name),field); } -void IDSpec::addField(const string& name, const pair<int,int>& field) { +void IDSpec::addField(const string& name, const pair<int,int>& field) { Element e(document(),Tag_idfield); e.object<Object>().Attr_signed = field.second<0; e.object<Object>().Attr_label = name; diff --git a/DDCore/src/Plugins.cpp b/DDCore/src/Plugins.cpp index 02db9f3ac..95a041b2f 100644 --- a/DDCore/src/Plugins.cpp +++ b/DDCore/src/Plugins.cpp @@ -15,23 +15,23 @@ using namespace DD4hep; using namespace ROOT::Reflex; /// Default constructor -PluginDebug::PluginDebug(int dbg) : m_debug(0) { +PluginDebug::PluginDebug(int dbg) + : m_debug(0) { m_debug = PluginService::Debug(); PluginService::SetDebug(dbg); } /// Default destructor -PluginDebug::~PluginDebug() { - PluginService::SetDebug(m_debug); +PluginDebug::~PluginDebug() { + PluginService::SetDebug (m_debug); } /// Helper to check factory existence -string PluginDebug::missingFactory(const string& name) const { +string PluginDebug::missingFactory(const string& name) const { string msg = ""; Scope factories = Scope::ByName(PLUGINSVC_FACTORY_NS); string factoryname = PluginService::FactoryName(name); - msg = "\n\t\tNo factory with name "+factoryname+" for type "+name+" found.\n\t\tPlease check library load path."; + msg = "\n\t\tNo factory with name " + factoryname + " for type " + name + " found.\n\t\tPlease check library load path."; return msg; } - diff --git a/DDCore/src/Printout.cpp b/DDCore/src/Printout.cpp index 506b33d27..c558957a0 100644 --- a/DDCore/src/Printout.cpp +++ b/DDCore/src/Printout.cpp @@ -13,16 +13,16 @@ #include <cstdarg> #include <stdexcept> -static size_t _the_printer(void*, DD4hep::PrintLevel, const char* src, const char* text) { - size_t len = ::fputs(src,stdout); - len += fputs(": ",stdout); - len += fputs(text,stdout); +static size_t _the_printer(void*, DD4hep::PrintLevel, const char* src, const char* text) { + size_t len = ::fputs(src, stdout); + len += fputs(": ", stdout); + len += fputs(text, stdout); ::fflush(stdout); return len; } -static DD4hep::PrintLevel print_lvl = DD4hep::INFO; -static void* print_arg = 0; +static DD4hep::PrintLevel print_lvl = DD4hep::INFO; +static void* print_arg = 0; static DD4hep::output_function_t print_func = _the_printer; /** Calls the display action @@ -31,11 +31,11 @@ static DD4hep::output_function_t print_func = _the_printer; * @arg fmt [string,read-only] Format string for ellipsis args * @return Status code indicating success or failure */ -int DD4hep::printout(PrintLevel severity, const char* src, const char* fmt, ...) { - if ( severity >= print_lvl ) { +int DD4hep::printout(PrintLevel severity, const char* src, const char* fmt, ...) { + if (severity >= print_lvl) { va_list args; - va_start(args,fmt); - printout(severity,src,fmt,args); + va_start(args, fmt); + printout(severity, src, fmt, args); va_end(args); } return 1; @@ -47,11 +47,11 @@ int DD4hep::printout(PrintLevel severity, const char* src, const char* fmt, ...) * @arg fmt [string,read-only] Format string for ellipsis args * @return Status code indicating success or failure */ -int DD4hep::printout(PrintLevel severity, const std::string& src, const char* fmt, ...) { - if ( severity >= print_lvl ) { +int DD4hep::printout(PrintLevel severity, const std::string& src, const char* fmt, ...) { + if (severity >= print_lvl) { va_list args; - va_start(args,fmt); - printout(severity,src.c_str(),fmt,args); + va_start(args, fmt); + printout(severity, src.c_str(), fmt, args); va_end(args); } return 1; @@ -63,11 +63,11 @@ int DD4hep::printout(PrintLevel severity, const std::string& src, const char* fm * @arg fmt [string,read-only] Format string for ellipsis args * @return Status code indicating success or failure */ -int DD4hep::printout(PrintLevel severity, const char* src, const std::string& fmt, ...) { - if ( severity >= print_lvl ) { +int DD4hep::printout(PrintLevel severity, const char* src, const std::string& fmt, ...) { + if (severity >= print_lvl) { va_list args; - va_start(args,fmt); - printout(severity,src,fmt.c_str(),args); + va_start(args, fmt); + printout(severity, src, fmt.c_str(), args); va_end(args); } return 1; @@ -79,11 +79,11 @@ int DD4hep::printout(PrintLevel severity, const char* src, const std::string& fm * @arg fmt [string,read-only] Format string for ellipsis args * @return Status code indicating success or failure */ -int DD4hep::printout(PrintLevel severity, const std::string& src, const std::string& fmt, ...) { - if ( severity >= print_lvl ) { +int DD4hep::printout(PrintLevel severity, const std::string& src, const std::string& fmt, ...) { + if (severity >= print_lvl) { va_list args; - va_start(args,fmt); - printout(severity,src.c_str(),fmt.c_str(),args); + va_start(args, fmt); + printout(severity, src.c_str(), fmt.c_str(), args); va_end(args); } return 1; @@ -95,13 +95,13 @@ int DD4hep::printout(PrintLevel severity, const std::string& src, const std::str * @arg fmt [string,read-only] Format string for ellipsis args * @return Status code indicating success or failure */ -int DD4hep::printout(PrintLevel severity, const char* src, const char* fmt, va_list& args) { - if ( severity >= print_lvl ) { +int DD4hep::printout(PrintLevel severity, const char* src, const char* fmt, va_list& args) { + if (severity >= print_lvl) { char str[4096]; - size_t len = vsnprintf(str,sizeof(str)-2,fmt,args); - str[len] = '\n'; - str[len+1] = '\0'; - print_func(print_arg,severity,src,str); + size_t len = vsnprintf(str, sizeof(str) - 2, fmt, args); + str[len] = '\n'; + str[len + 1] = '\0'; + print_func(print_arg, severity, src, str); } return 1; } @@ -112,8 +112,8 @@ int DD4hep::printout(PrintLevel severity, const char* src, const char* fmt, va_l * @arg fmt [string,read-only] Format string for ellipsis args * @return Status code indicating success or failure */ -int DD4hep::printout(PrintLevel severity, const std::string& src, const char* fmt, va_list& args) { - return printout(severity,src.c_str(),fmt,args); +int DD4hep::printout(PrintLevel severity, const std::string& src, const char* fmt, va_list& args) { + return printout(severity, src.c_str(), fmt, args); } /** Calls the display action @@ -122,8 +122,8 @@ int DD4hep::printout(PrintLevel severity, const std::string& src, const char* fm * @arg fmt [string,read-only] Format string for ellipsis args * @return Status code indicating success or failure */ -int DD4hep::printout(PrintLevel severity, const char* src, const std::string& fmt, va_list& args) { - return printout(severity,src,fmt.c_str(),args); +int DD4hep::printout(PrintLevel severity, const char* src, const std::string& fmt, va_list& args) { + return printout(severity, src, fmt.c_str(), args); } /** Calls the display action @@ -132,8 +132,8 @@ int DD4hep::printout(PrintLevel severity, const char* src, const std::string& fm * @arg fmt [string,read-only] Format string for ellipsis args * @return Status code indicating success or failure */ -int DD4hep::printout(PrintLevel severity, const std::string& src, const std::string& fmt, va_list& args) { - return printout(severity,src.c_str(),fmt.c_str(),args); +int DD4hep::printout(PrintLevel severity, const std::string& src, const std::string& fmt, va_list& args) { + return printout(severity, src.c_str(), fmt.c_str(), args); } /** Build exception string and throw std::runtime_error @@ -141,10 +141,10 @@ int DD4hep::printout(PrintLevel severity, const std::string& src, const std::str * @arg fmt [string,read-only] Format string for ellipsis args * @return Status code indicating success or failure */ -std::string DD4hep::format(const std::string& src, const std::string& fmt, ...) { +std::string DD4hep::format(const std::string& src, const std::string& fmt, ...) { va_list args; - va_start(args,fmt); - std::string str = format(src,fmt,args); + va_start(args, fmt); + std::string str = format(src, fmt, args); va_end(args); return str; } @@ -155,22 +155,22 @@ std::string DD4hep::format(const std::string& src, const std::string& fmt, ...) * @arg args [ap_list,read-only] List with variable number of arguments to fill format string. * @return Status code indicating success or failure */ -std::string DD4hep::format(const std::string& src, const std::string& fmt, va_list& args) { +std::string DD4hep::format(const std::string& src, const std::string& fmt, va_list& args) { char str[4096]; - size_t len = ::snprintf(str,sizeof(str),"%s: ",src.c_str()); - ::vsnprintf(str+len,sizeof(str)-len,fmt.c_str(),args); + size_t len = ::snprintf(str, sizeof(str), "%s: ", src.c_str()); + ::vsnprintf(str + len, sizeof(str) - len, fmt.c_str(), args); return std::string(str); } /// Set new print level. Returns the old print level -DD4hep::PrintLevel DD4hep::setPrintLevel(PrintLevel new_level) { +DD4hep::PrintLevel DD4hep::setPrintLevel(PrintLevel new_level) { PrintLevel old = print_lvl; print_lvl = new_level; return old; } /// Customize printer function -void DD4hep::setPrinter(void* arg, output_function_t fcn) { +void DD4hep::setPrinter(void* arg, output_function_t fcn) { print_arg = arg; print_func = fcn; } @@ -182,112 +182,102 @@ using namespace std; namespace DD4hep { using namespace Geometry; - template <typename T> void PrintMap<T>::operator()() const { - Printer<T> p(lcdd,os); + template <typename T> void PrintMap<T>::operator()() const { + Printer < T > p(lcdd, os); os << "++" << endl << "++ " << text << endl << "++" << endl; - for (LCDD::HandleMap::const_iterator i=cont.begin(); i != cont.end(); ++i) + for (LCDD::HandleMap::const_iterator i = cont.begin(); i != cont.end(); ++i) p((*i).second); } - template <> void Printer<Handle<TNamed> >::operator()(const Handle<TNamed>& val) const { - printout(INFO,"Printer","%s ++ Handle:%s %s", - prefix.c_str(),val->GetName(),val->GetTitle()); + template <> void Printer<Handle<TNamed> >::operator()(const Handle<TNamed>& val) const { + printout(INFO, "Printer", "%s ++ Handle:%s %s", prefix.c_str(), val->GetName(), val->GetTitle()); } - template <> void Printer<Constant>::operator()(const Constant& val) const { - printout(INFO,"Printer","%s ++ Constant:%s %s", - prefix.c_str(),val->GetName(),val.toString().c_str()); + template <> void Printer<Constant>::operator()(const Constant& val) const { + printout(INFO, "Printer", "%s ++ Constant:%s %s", prefix.c_str(), val->GetName(), val.toString().c_str()); } - template <> void Printer<Material>::operator()(const Material& val) const { - printout(INFO,"Printer","%s ++ Material:%s %s", - prefix.c_str(),val->GetName(),val.toString().c_str()); + template <> void Printer<Material>::operator()(const Material& val) const { + printout(INFO, "Printer", "%s ++ Material:%s %s", prefix.c_str(), val->GetName(), val.toString().c_str()); } - template <> void Printer<VisAttr>::operator()(const VisAttr& val) const { - printout(INFO,"Printer","%s ++ VisAttr: %s",prefix.c_str(),val.toString().c_str()); + template <> void Printer<VisAttr>::operator()(const VisAttr& val) const { + printout(INFO, "Printer", "%s ++ VisAttr: %s", prefix.c_str(), val.toString().c_str()); } - template <> void Printer<Readout>::operator()(const Readout& val) const { - printout(INFO,"Printer","%s ++ Readout: %s of type %s", - prefix.c_str(),val->GetName(),val->GetTitle()); + template <> void Printer<Readout>::operator()(const Readout& val) const { + printout(INFO, "Printer", "%s ++ Readout: %s of type %s", prefix.c_str(), val->GetName(), val->GetTitle()); } - template <> void Printer<Region>::operator()(const Region& val) const { - printout(INFO,"Printer","%s ++ Region: %s of type %s", - prefix.c_str(),val->GetName(),val->GetTitle()); + template <> void Printer<Region>::operator()(const Region& val) const { + printout(INFO, "Printer", "%s ++ Region: %s of type %s", prefix.c_str(), val->GetName(), val->GetTitle()); } - template <> void Printer<RotationZYX>::operator()(const RotationZYX& val) const { - printout(INFO,"Printer","%s ++ ZYXRotation: phi: %7.3 rad theta: %7.3 rad psi: %7.3 rad", - prefix.c_str(),val.Phi(),val.Theta(),val.Psi()); + template <> void Printer<RotationZYX>::operator()(const RotationZYX& val) const { + printout(INFO, "Printer", "%s ++ ZYXRotation: phi: %7.3 rad theta: %7.3 rad psi: %7.3 rad", prefix.c_str(), val.Phi(), + val.Theta(), val.Psi()); } - template <> void Printer<Position>::operator()(const Position& val) const { - printout(INFO,"Printer","%s ++ Position: x: %9.3 mm y: %9.3 mm z: %9.3 mm", - prefix.c_str(),val.X(),val.Y(),val.Z()); + template <> void Printer<Position>::operator()(const Position& val) const { + printout(INFO, "Printer", "%s ++ Position: x: %9.3 mm y: %9.3 mm z: %9.3 mm", prefix.c_str(), val.X(), val.Y(), val.Z()); } - template <> void Printer<LimitSet>::operator()(const LimitSet& val) const { + template <> void Printer<LimitSet>::operator()(const LimitSet& val) const { const set<Limit>& o = val.limits(); - printout(INFO,"Printer","%s ++ LimitSet: %s",prefix.c_str(),val.name()); + printout(INFO, "Printer", "%s ++ LimitSet: %s", prefix.c_str(), val.name()); val->TNamed::Print(); - for(set<Limit>::const_iterator i=o.begin(); i!=o.end(); ++i) { - os << "++ Limit:" << (*i).name << " " << (*i).particles - << " [" << (*i).unit << "] " << (*i).content << " " << (*i).value << endl; + for (set<Limit>::const_iterator i = o.begin(); i != o.end(); ++i) { + os << "++ Limit:" << (*i).name << " " << (*i).particles << " [" << (*i).unit << "] " << (*i).content << " " + << (*i).value << endl; } } - template <> void Printer<DetElement>::operator()(const DetElement& val) const { + template <> void Printer<DetElement>::operator()(const DetElement& val) const { DetElement::Object* obj = val.data<DetElement::Object>(); - if ( obj ) { + if (obj) { char text[256]; const DetElement& sd = val; PlacedVolume plc = sd.placement(); bool vis = plc.isValid(); bool env = plc.isValid(); bool mat = plc.isValid(); - ::snprintf(text,sizeof(text),"ID:%-3d Combine Hits:%3s Material:%s Envelope:%s VisAttr:%s", - sd.id(), yes_no(sd.combineHits()), - mat ? plc.material()->GetName() : yes_no(mat), - env ? plc.motherVol()->GetName() : yes_no(env), - yes_no(vis) - ); + ::snprintf(text, sizeof(text), "ID:%-3d Combine Hits:%3s Material:%s Envelope:%s VisAttr:%s", sd.id(), + yes_no(sd.combineHits()), mat ? plc.material()->GetName() : yes_no(mat), + env ? plc.motherVol()->GetName() : yes_no(env), yes_no(vis)); os << prefix << "+= DetElement: " << val->GetName() << " " << val.type() << endl; os << prefix << "| " << text << endl; - if ( vis ) { - VisAttr attr = plc.volume().visAttributes(); - VisAttr::Object* v = attr.data<VisAttr::Object>(); - TColor* col = gROOT->GetColor(v->color); - char text[256]; - ::snprintf(text,sizeof(text)," RGB:%-8s [%d] %7.2f Style:%d %d ShowDaughters:%3s Visible:%3s", - col->AsHexString(), v->color, col->GetAlpha(), int(v->drawingStyle), int(v->lineStyle), - v->showDaughters ? "YES" : "NO", v->visible ? "YES" : "NO"); - os << prefix << "| VisAttr: " << setw(32) << left << attr.name() << text << endl; + if (vis) { + VisAttr attr = plc.volume().visAttributes(); + VisAttr::Object* v = attr.data<VisAttr::Object>(); + TColor* col = gROOT->GetColor(v->color); + char text[256]; + ::snprintf(text, sizeof(text), " RGB:%-8s [%d] %7.2f Style:%d %d ShowDaughters:%3s Visible:%3s", col->AsHexString(), + v->color, col->GetAlpha(), int(v->drawingStyle), int(v->lineStyle), v->showDaughters ? "YES" : "NO", + v->visible ? "YES" : "NO"); + os << prefix << "| VisAttr: " << setw(32) << left << attr.name() << text << endl; } - if ( plc.isValid() ) { - Volume vol = plc.volume(); - Solid s = vol.solid(); - Material m = vol.material(); - ::snprintf(text,sizeof(text),"Volume:%s Shape:%s Material:%s", - vol->GetName(), s.isValid() ? s.name() : "Unknonw", m.isValid() ? m->GetName() : "Unknown" - ); - os << prefix << "+------------- " << text << endl; + if (plc.isValid()) { + Volume vol = plc.volume(); + Solid s = vol.solid(); + Material m = vol.material(); + ::snprintf(text, sizeof(text), "Volume:%s Shape:%s Material:%s", vol->GetName(), s.isValid() ? s.name() : "Unknonw", + m.isValid() ? m->GetName() : "Unknown"); + os << prefix << "+------------- " << text << endl; } const DetElement::Children& ch = sd.children(); - for(DetElement::Children::const_iterator i=ch.begin(); i!=ch.end(); ++i) - Printer<DetElement>(lcdd,os,prefix+"| ")((*i).second); + for (DetElement::Children::const_iterator i = ch.begin(); i != ch.end(); ++i) + Printer < DetElement > (lcdd, os, prefix + "| ")((*i).second); return; } } - template <> void Printer<const LCDD*>::operator()(const LCDD*const&) const { + template <> void Printer<const LCDD*>::operator()(const LCDD* const &) const { //Header(lcdd.header()).fromCompact(doc,compact.child(Tag_info),Strng_t("In memory")); - PrintMap<Constant > (lcdd,os,lcdd->constants(), "List of Constants")(); - PrintMap<VisAttr > (lcdd,os,lcdd->visAttributes(),"List of Visualization attributes")(); - PrintMap<LimitSet > (lcdd,os,lcdd->readouts(), "List of Readouts")(); - PrintMap<Region > (lcdd,os,lcdd->regions(), "List of Regions")(); - PrintMap<DetElement> (lcdd,os,lcdd->detectors(), "List of DetElements")(); + PrintMap < Constant > (lcdd, os, lcdd->constants(), "List of Constants")(); + PrintMap < VisAttr > (lcdd, os, lcdd->visAttributes(), "List of Visualization attributes")(); + PrintMap < LimitSet > (lcdd, os, lcdd->readouts(), "List of Readouts")(); + PrintMap < Region > (lcdd, os, lcdd->regions(), "List of Regions")(); + PrintMap < DetElement > (lcdd, os, lcdd->detectors(), "List of DetElements")(); } } diff --git a/DDCore/src/Readout.cpp b/DDCore/src/Readout.cpp index d8fa1b9b5..4111bac3b 100644 --- a/DDCore/src/Readout.cpp +++ b/DDCore/src/Readout.cpp @@ -18,31 +18,30 @@ using namespace DD4hep::Geometry; using tgeo::mm; /// Standard constructor -Readout::Object::Object() { +Readout::Object::Object() { InstanceCount::increment(this); } /// Default destructor -Readout::Object::~Object() { +Readout::Object::~Object() { //destroyHandle(segmentation); InstanceCount::decrement(this); } /// Initializing constructor to create a new object -Readout::Readout(const string& nam) -{ - assign(new Object(),nam,"readout"); +Readout::Readout(const string& nam) { + assign(new Object(), nam, "readout"); } /// Assign IDDescription to readout structure -void Readout::setIDDescriptor(const Ref_t& new_descriptor) const { - if ( isValid() ) { // Remember: segmentation is NOT owned by readout structure! - if ( new_descriptor.isValid() ) { // Do NOT delete! +void Readout::setIDDescriptor(const Ref_t& new_descriptor) const { + if (isValid()) { // Remember: segmentation is NOT owned by readout structure! + if (new_descriptor.isValid()) { // Do NOT delete! data<Object>()->id = new_descriptor; Segmentation seg = data<Object>()->segmentation; IDDescriptor id = new_descriptor; if (seg.isValid()) { - //seg.segmentation()->setDecoder(id.decoder()); + //seg.segmentation()->setDecoder(id.decoder()); } return; } @@ -51,19 +50,19 @@ void Readout::setIDDescriptor(const Ref_t& new_descriptor) const { } /// Access IDDescription structure -IDDescriptor Readout::idSpec() const { +IDDescriptor Readout::idSpec() const { return object<Object>().id; } /// Assign segmentation structure to readout -void Readout::setSegmentation(const Segmentation& seg) const { - if ( isValid() ) { +void Readout::setSegmentation(const Segmentation& seg) const { + if (isValid()) { Object& ro = object<Object>(); Segmentation::Implementation* e = ro.segmentation.ptr(); - if ( e ) { // Remember: segmentation is owned by readout structure! - delete e; // Need to delete the segmentation object + if (e) { // Remember: segmentation is owned by readout structure! + delete e; // Need to delete the segmentation object } - if ( seg.isValid() ) { + if (seg.isValid()) { ro.segmentation = seg; return; } @@ -72,7 +71,7 @@ void Readout::setSegmentation(const Segmentation& seg) const { } /// Access segmentation structure -Segmentation Readout::segmentation() const { +Segmentation Readout::segmentation() const { return object<Object>().segmentation; } @@ -82,7 +81,7 @@ PlacedVolume Readout::getPlacement(const long64& cellID) const { return volMan.lookupPlacement(cellID); } -DetElement Readout::getSubDetector(const long64& cellID) const{ +DetElement Readout::getSubDetector(const long64& cellID) const { VolumeManager volMan = LCDD::getInstance().volumeManager(); return volMan.lookupDetector(cellID); } @@ -93,10 +92,10 @@ DetElement Readout::getDetectorElement(const long64& cellID) const { } Position Readout::getPosition(const long64& cellID) const { - double global[3] = {0., 0., 0.}; + double global[3] = { 0., 0., 0. }; VolumeManager volMan = LCDD::getInstance().volumeManager(); volMan.worldTransformation(cellID).LocalToMaster(&(segmentation().segmentation()->getPosition(cellID))[0], global); - return Position(global[0]/tgeo::mm, global[1]/tgeo::mm, global[2]/tgeo::mm); + return Position(global[0] / tgeo::mm, global[1] / tgeo::mm, global[2] / tgeo::mm); } Position Readout::getLocalPosition(const long64& cellID) const { @@ -110,33 +109,31 @@ const TGeoMatrix& Readout::getWorldTransformation(const long64& cellID) const { } /// Standard constructor -Alignment::Object::Object() { +Alignment::Object::Object() { InstanceCount::increment(this); } /// Default destructor -Alignment::Object::~Object() { +Alignment::Object::~Object() { InstanceCount::decrement(this); } /// Initializing constructor to create a new object -Alignment::Alignment(const LCDD& /* lcdd */, const string& nam) -{ - assign(new Object(),nam,"alignment"); +Alignment::Alignment(const LCDD& /* lcdd */, const string& nam) { + assign(new Object(), nam, "alignment"); } /// Standard constructor -Conditions::Object::Object() { +Conditions::Object::Object() { InstanceCount::increment(this); } /// Default destructor -Conditions::Object::~Object() { +Conditions::Object::~Object() { InstanceCount::decrement(this); } /// Initializing constructor to create a new object -Conditions::Conditions(const LCDD& /* lcdd */, const string& nam) -{ - assign(new Object(),nam,"conditions"); +Conditions::Conditions(const LCDD& /* lcdd */, const string& nam) { + assign(new Object(), nam, "conditions"); } diff --git a/DDCore/src/Segementations.cpp b/DDCore/src/Segementations.cpp index d14440c28..92100e39b 100644 --- a/DDCore/src/Segementations.cpp +++ b/DDCore/src/Segementations.cpp @@ -17,15 +17,14 @@ using namespace DD4hep; using namespace DD4hep::Geometry; namespace { - void not_implemented_call(const char* tag) { + void not_implemented_call(const char* tag) { throw runtime_error(tag); } } /// Standard constructor -Segmentation::Object::Object() - : magic(magic_word()), useForHitPosition(0) -{ +Segmentation::Object::Object() + : magic(magic_word()), useForHitPosition(0) { InstanceCount::increment(this); } @@ -35,190 +34,192 @@ Segmentation::Object::~Object() { } /// Accessor: Segmentation type -std::string Segmentation::type() const { +std::string Segmentation::type() const { return segmentation()->type(); } -bool Segmentation::useForHitPosition() const { +bool Segmentation::useForHitPosition() const { return object<Object>().useForHitPosition != 0; } /// Segmentation type -string SegmentationParams::type() const { +string SegmentationParams::type() const { return object<Object>().segmentation->type(); } /// Access to the parameters -SegmentationParams::Parameters SegmentationParams::parameters() const { +SegmentationParams::Parameters SegmentationParams::parameters() const { return object<Object>().segmentation->parameters(); } /// Access segmentation object -DD4hep::DDSegmentation::Segmentation* Segmentation::segmentation() const { +DD4hep::DDSegmentation::Segmentation* Segmentation::segmentation() const { Object& o = object<Object>(); if (o.segmentation != 0) return o.segmentation; - throw runtime_error("DD4hep: The segmentation object "+string(type())+ - " knows no implementation object [This is no longer allowed in the presence of DDSegmentation]"); + throw runtime_error( + "DD4hep: The segmentation object " + string(type()) + + " knows no implementation object [This is no longer allowed in the presence of DDSegmentation]"); } /// Default destructor -ProjectiveCylinder::Data::~Data() { +ProjectiveCylinder::Data::~Data() { } /// determine the local position based on the cell ID -std::vector<double> ProjectiveCylinder::Data::getPosition(const long64& cellID) const { +std::vector<double> ProjectiveCylinder::Data::getPosition(const long64& cellID) const { not_implemented_call("ProjectiveCylinder::Data::getLocalPosition"); return vector<double>(); } /// determine the local position based on the cell ID -std::vector<double> ProjectiveCylinder::Data::getLocalPosition(const long64& cellID) const { +std::vector<double> ProjectiveCylinder::Data::getLocalPosition(const long64& cellID) const { not_implemented_call("ProjectiveCylinder::Data::getLocalPosition"); return vector<double>(); } /// determine the cell ID based on the local position -long64 ProjectiveCylinder::Data::getCellID(double x, double y, double z) const { +long64 ProjectiveCylinder::Data::getCellID(double x, double y, double z) const { not_implemented_call("ProjectiveCylinder::Data::getCellID"); return 0; } /// Constructor to create a new segmentation object -ProjectiveCylinder::ProjectiveCylinder(LCDD&) : Segmentation(new Data(),"segmentation","projective_cylinder") -{ +ProjectiveCylinder::ProjectiveCylinder(LCDD&) + : Segmentation(new Data(), "segmentation", "projective_cylinder") { } /// Accessors: get number of bins in theta -int ProjectiveCylinder::thetaBins() const { +int ProjectiveCylinder::thetaBins() const { return object<Data>().ntheta; } /// Accessors: get number of bins in phi -int ProjectiveCylinder::phiBins() const { +int ProjectiveCylinder::phiBins() const { return object<Data>().nphi; } /// Accessors: get number of bins in z -int ProjectiveCylinder::zBins() const { +int ProjectiveCylinder::zBins() const { return object<Data>().nz; } /// Accessors: set number of bins in theta -void ProjectiveCylinder::setThetaBins(int value) { +void ProjectiveCylinder::setThetaBins(int value) { object<Data>().ntheta = value; } /// Accessors: set grid size in Y -void ProjectiveCylinder::setPhiBins(int value) { +void ProjectiveCylinder::setPhiBins(int value) { object<Data>().nphi = value; } /// Accessors: set number of bins in Z -void ProjectiveCylinder::setZBins(int value) { +void ProjectiveCylinder::setZBins(int value) { object<Data>().nz = value; } /// Default destructor -NonProjectiveCylinder::Data::~Data() { +NonProjectiveCylinder::Data::~Data() { } /// determine the local position based on the cell ID -std::vector<double> NonProjectiveCylinder::Data::getPosition(const long64& cellID) const { +std::vector<double> NonProjectiveCylinder::Data::getPosition(const long64& cellID) const { not_implemented_call("NonProjectiveCylinder::Data::getLocalPosition"); return vector<double>(); } /// determine the local position based on the cell ID -std::vector<double> NonProjectiveCylinder::Data::getLocalPosition(const long64& cellID) const { +std::vector<double> NonProjectiveCylinder::Data::getLocalPosition(const long64& cellID) const { not_implemented_call("NonProjectiveCylinder::Data::getLocalPosition"); return vector<double>(); } /// determine the cell ID based on the local position -long64 NonProjectiveCylinder::Data::getCellID(double x, double y, double z) const { +long64 NonProjectiveCylinder::Data::getCellID(double x, double y, double z) const { not_implemented_call("NonProjectiveCylinder::Data::getCellID"); return 0; } /// Constructor to create a new segmentation object -NonProjectiveCylinder::NonProjectiveCylinder(LCDD&) : Segmentation(new Data(),"segmentation","nonprojective_cylinder") -{ +NonProjectiveCylinder::NonProjectiveCylinder(LCDD&) + : Segmentation(new Data(), "segmentation", "nonprojective_cylinder") { } /// Accessors: get size of bins in Z -double NonProjectiveCylinder::gridSizeZ() const { +double NonProjectiveCylinder::gridSizeZ() const { return object<Data>().grid_size_z; } /// Accessors: get size of bins in phi -double NonProjectiveCylinder::gridSizePhi() const { +double NonProjectiveCylinder::gridSizePhi() const { return object<Data>().grid_size_phi; } /// Accessors: set number of bins in theta -void NonProjectiveCylinder::setThetaBinSize(double value) { +void NonProjectiveCylinder::setThetaBinSize(double value) { object<Data>().grid_size_phi = value; } /// Accessors: set grid size in Y -void NonProjectiveCylinder::setPhiBinSize(double value) { +void NonProjectiveCylinder::setPhiBinSize(double value) { object<Data>().grid_size_z = value; } /// Default destructor -ProjectiveZPlane::Data::~Data() { +ProjectiveZPlane::Data::~Data() { } /// determine the local position based on the cell ID -std::vector<double> ProjectiveZPlane::Data::getLocalPosition(const long64& cellID) const { +std::vector<double> ProjectiveZPlane::Data::getLocalPosition(const long64& cellID) const { not_implemented_call("ProjectiveZPlane::Data::getLocalPosition"); return vector<double>(); } /// determine the local position based on the cell ID -std::vector<double> ProjectiveZPlane::Data::getPosition(const long64& cellID) const { +std::vector<double> ProjectiveZPlane::Data::getPosition(const long64& cellID) const { not_implemented_call("ProjectiveZPlane::Data::getLocalPosition"); return vector<double>(); } /// determine the cell ID based on the local position -long64 ProjectiveZPlane::Data::getCellID(double x, double y, double z) const { +long64 ProjectiveZPlane::Data::getCellID(double x, double y, double z) const { not_implemented_call("ProjectiveZPlane::Data::getCellID"); return 0; } /// Constructor to be used when creating a new object. -ProjectiveZPlane::ProjectiveZPlane(LCDD&) : Segmentation(new Data(),"segmentation","projective_zplane") -{ +ProjectiveZPlane::ProjectiveZPlane(LCDD&) + : Segmentation(new Data(), "segmentation", "projective_zplane") { } /// Accessors: get number of bins in phi -int ProjectiveZPlane::phiBins() const { +int ProjectiveZPlane::phiBins() const { return object<Data>().nphi; } /// Accessors: get number of bins in theta -int ProjectiveZPlane::thetaBins() const { +int ProjectiveZPlane::thetaBins() const { return object<Data>().ntheta; } /// Accessors: set number of bins in theta -void ProjectiveZPlane::setThetaBins(int value) { +void ProjectiveZPlane::setThetaBins(int value) { object<Data>().ntheta = value; } /// Accessors: set grid size in Y -void ProjectiveZPlane::setPhiBins(int value) { +void ProjectiveZPlane::setPhiBins(int value) { object<Data>().nphi = value; } /// Default destructor -GridXY::Data::~Data() { +GridXY::Data::~Data() { } /// Constructor to be used when creating a new object. -GridXY::GridXY(LCDD&, const std::string& typ) : Segmentation(new Data(),"segmentation",typ) { +GridXY::GridXY(LCDD&, const std::string& typ) + : Segmentation(new Data(), "segmentation", typ) { } /// Accessors: get grid size in X @@ -232,22 +233,23 @@ double GridXY::getGridSizeY() const { } /// Accessors: set grid size in X -void GridXY::setGridSizeX(double value) { +void GridXY::setGridSizeX(double value) { object<Data>().setGridSizeX(value); } /// Accessors: set grid size in Y -void GridXY::setGridSizeY(double value) { +void GridXY::setGridSizeY(double value) { object<Data>().setGridSizeY(value); } /// Default destructor -GridXYZ::Data::~Data() { +GridXYZ::Data::~Data() { } /// Constructor to be used when creating a new object. -GridXYZ::GridXYZ(LCDD& , const std::string& typ) : Segmentation(new Data(),"segmentation",typ) { - assign(new Data(),"segmentation",typ); +GridXYZ::GridXYZ(LCDD&, const std::string& typ) + : Segmentation(new Data(), "segmentation", typ) { + assign(new Data(), "segmentation", typ); } /// Accessors: get grid size in X @@ -266,16 +268,16 @@ double GridXYZ::getGridSizeZ() const { } /// Accessors: set grid size in X -void GridXYZ::setGridSizeX(double value) { +void GridXYZ::setGridSizeX(double value) { object<Data>().setGridSizeX(value); } /// Accessors: set grid size in Y -void GridXYZ::setGridSizeY(double value) { +void GridXYZ::setGridSizeY(double value) { object<Data>().setGridSizeY(value); } /// Accessors: set grid size in Z -void GridXYZ::setGridSizeZ(double value) { +void GridXYZ::setGridSizeZ(double value) { object<Data>().setGridSizeZ(value); } diff --git a/DDCore/src/Shapes.cpp b/DDCore/src/Shapes.cpp index 8a291910d..b5a37cf0d 100644 --- a/DDCore/src/Shapes.cpp +++ b/DDCore/src/Shapes.cpp @@ -31,465 +31,339 @@ using namespace std; using namespace DD4hep::Geometry; -template<typename T> void Solid_type<T>::_setDimensions(double* param) { +template <typename T> void Solid_type<T>::_setDimensions(double* param) { this->ptr()->SetDimensions(param); this->ptr()->ComputeBBox(); } /// Assign pointrs and register solid to geometry -template<typename T> +template <typename T> void Solid_type<T>::_assign(T* n, const string& nam, const string& tit, bool cbbox) { - this->assign(n,nam,tit); - if ( cbbox ) n->ComputeBBox(); + this->assign(n, nam, tit); + if (cbbox) + n->ComputeBBox(); } /// Access to shape name -template<typename T> const char* Solid_type<T>::name() const { +template <typename T> const char* Solid_type<T>::name() const { return this->ptr()->GetName(); } -void Box::make(const string& name, double x, double y, double z) { - _assign(new TGeoBBox(x*MM_2_CM,y*MM_2_CM,z*MM_2_CM),name,"box",true); +void Box::make(const string& name, double x, double y, double z) { + _assign(new TGeoBBox(x * MM_2_CM, y * MM_2_CM, z * MM_2_CM), name, "box", true); } /// Set the box dimensionsy -Box& Box::setDimensions(double x, double y, double z) { - double params[] = {x*MM_2_CM,y*MM_2_CM,z*MM_2_CM}; +Box& Box::setDimensions(double x, double y, double z) { + double params[] = { x * MM_2_CM, y * MM_2_CM, z * MM_2_CM }; _setDimensions(params); return *this; } /// Access half "length" of the box double Box::x() const { - return this->ptr()->GetDX()*CM_2_MM; + return this->ptr()->GetDX() * CM_2_MM; } /// Access half "width" of the box double Box::y() const { - return this->ptr()->GetDY()*CM_2_MM; + return this->ptr()->GetDY() * CM_2_MM; } /// Access half "depth" of the box double Box::z() const { - return this->ptr()->GetDZ()*CM_2_MM; + return this->ptr()->GetDZ() * CM_2_MM; } /// Constructor to be used when creating a new object -Polycone::Polycone(const string& name) { - _assign(new TGeoPcon(0,RAD_2_DEGREE*(2.*M_PI),0),name,"polycone",false); -} - -/// Constructor to be used when creating a new object -Polycone::Polycone(double start, double delta) { - _assign(new TGeoPcon(RAD_2_DEGREE*start,RAD_2_DEGREE*delta,0),"","polycone",false); -} - -/// Constructor to be used when creating a new object -Polycone::Polycone(const string& name, double start, double delta) { - _assign(new TGeoPcon(RAD_2_DEGREE*start,RAD_2_DEGREE*delta,0),name,"polycone",false); +Polycone::Polycone(double start, double delta) { + _assign(new TGeoPcon(RAD_2_DEGREE * start, RAD_2_DEGREE * delta, 0), "", "polycone", false); } /// Constructor to be used when creating a new polycone object. Add at the same time all Z planes -Polycone::Polycone(double start, double delta, const vector<double>& rmin, const vector<double>& rmax, const vector<double>& z) -{ +Polycone::Polycone(double start, double delta, const vector<double>& rmin, const vector<double>& rmax, + const vector<double>& z) { vector<double> params; - if ( rmin.size() < 2 ) { + if (rmin.size() < 2) { throw runtime_error("DD4hep: PolyCone::addZPlanes> Not enough Z planes. minimum is 2!"); } params.push_back(RAD_2_DEGREE * start); params.push_back(RAD_2_DEGREE * delta); params.push_back(rmin.size()); - for( size_t i=0; i<rmin.size(); ++i ) { - params.push_back(z[i]*MM_2_CM); - params.push_back(rmin[i]*MM_2_CM); - params.push_back(rmax[i]*MM_2_CM); + for (size_t i = 0; i < rmin.size(); ++i) { + params.push_back(z[i] * MM_2_CM); + params.push_back(rmin[i] * MM_2_CM); + params.push_back(rmax[i] * MM_2_CM); } - _assign( new TGeoPcon(¶ms[0]),"","polycone",true); -} - -/// Constructor to be used when creating a new polycone object. Add at the same time all Z planes -Polycone::Polycone(const string& name, double start, double delta, const vector<double>& rmin, const vector<double>& rmax, const vector<double>& z) -{ - vector<double> params; - if ( rmin.size() < 2 ) { - throw runtime_error("DD4hep: PolyCone::addZPlanes> Not enough Z planes. minimum is 2!"); - } - params.push_back(RAD_2_DEGREE * start); - params.push_back(RAD_2_DEGREE * delta); - params.push_back(rmin.size()); - for( size_t i=0; i<rmin.size(); ++i ) { - params.push_back(z[i]*MM_2_CM); - params.push_back(rmin[i]*MM_2_CM); - params.push_back(rmax[i]*MM_2_CM); - } - _assign( new TGeoPcon(¶ms[0]),name,"polycone",true); + _assign(new TGeoPcon(¶ms[0]), "", "polycone", true); } /// Add Z-planes to the Polycone -void Polycone::addZPlanes(const vector<double>& rmin, const vector<double>& rmax, const vector<double>& z) { +void Polycone::addZPlanes(const vector<double>& rmin, const vector<double>& rmax, const vector<double>& z) { TGeoPcon* s = *this; vector<double> params; size_t num = s->GetNz(); - if ( rmin.size() < 2 ) { + if (rmin.size() < 2) { throw runtime_error("DD4hep: PolyCone::addZPlanes> Not enough Z planes. minimum is 2!"); } params.push_back(s->GetPhi1()); params.push_back(s->GetDphi()); - params.push_back(num+rmin.size()); - for( size_t i=0; i<num; ++i ) { + params.push_back(num + rmin.size()); + for (size_t i = 0; i < num; ++i) { params.push_back(s->GetZ(i)); params.push_back(s->GetRmin(i)); params.push_back(s->GetRmax(i)); } - for( size_t i=0; i<rmin.size(); ++i ) { - params.push_back(z[i]*MM_2_CM); - params.push_back(rmin[i]*MM_2_CM); - params.push_back(rmax[i]*MM_2_CM); + for (size_t i = 0; i < rmin.size(); ++i) { + params.push_back(z[i] * MM_2_CM); + params.push_back(rmin[i] * MM_2_CM); + params.push_back(rmax[i] * MM_2_CM); } _setDimensions(¶ms[0]); } -/// Constructor to be used when creating a new object -ConeSegment::ConeSegment(const string& name) { - _assign(new TGeoConeSeg(),name,"cone_segment",false); -} - -/// Constructor to be used when creating a new cone segment object -ConeSegment::ConeSegment(double dz, double rmin1, double rmax1, double rmin2, double rmax2, double phi1, double phi2) { - _assign(new TGeoConeSeg(dz*MM_2_CM,rmin1*MM_2_CM,rmax1*MM_2_CM,rmin2*MM_2_CM,rmax2*MM_2_CM,RAD_2_DEGREE*phi1,RAD_2_DEGREE*phi2),"","cone_segment",true); -} - /// Constructor to be used when creating a new cone segment object -ConeSegment::ConeSegment(const string& name, double dz, double rmin1, double rmax1, double rmin2, double rmax2, double phi1, double phi2) { - _assign(new TGeoConeSeg(dz*MM_2_CM,rmin1*MM_2_CM,rmax1*MM_2_CM,rmin2*MM_2_CM,rmax2*MM_2_CM,RAD_2_DEGREE*phi1,RAD_2_DEGREE*phi2),name,"cone_segment",true); +ConeSegment::ConeSegment(double dz, double rmin1, double rmax1, double rmin2, double rmax2, double phi1, double phi2) { + _assign( + new TGeoConeSeg(dz * MM_2_CM, rmin1 * MM_2_CM, rmax1 * MM_2_CM, rmin2 * MM_2_CM, rmax2 * MM_2_CM, RAD_2_DEGREE * phi1, + RAD_2_DEGREE * phi2), "", "cone_segment", true); } /// Set the cone segment dimensions -ConeSegment& ConeSegment::setDimensions(double dz, double rmin1, double rmax1, double rmin2, double rmax2, double phi1, double phi2) { - double params[] = {dz*MM_2_CM,rmin1*MM_2_CM,rmax1*MM_2_CM,rmin2*MM_2_CM,rmax2*MM_2_CM,RAD_2_DEGREE*phi1,RAD_2_DEGREE*phi2}; +ConeSegment& ConeSegment::setDimensions(double dz, double rmin1, double rmax1, double rmin2, double rmax2, double phi1, + double phi2) { + double params[] = { dz * MM_2_CM, rmin1 * MM_2_CM, rmax1 * MM_2_CM, rmin2 * MM_2_CM, rmax2 * MM_2_CM, RAD_2_DEGREE * phi1, + RAD_2_DEGREE * phi2 }; _setDimensions(params); return *this; } /// Constructor to be used when creating a new object with attribute initialization -void Tube::make(const string& name, double rmin, double rmax, double z, double startPhi, double deltaPhi) -{ +void Tube::make(const string& name, double rmin, double rmax, double z, double startPhi, double deltaPhi) { //_assign(new TGeoTubeSeg(rmin*MM_2_CM,rmax*MM_2_CM,z*MM_2_CM,RAD_2_DEGREE*startPhi,RAD_2_DEGREE*deltaPhi),name,"tube",true); - _assign(new MyConeSeg(),name,"tube",true); - setDimensions(rmin,rmax,z,startPhi,deltaPhi); + _assign(new MyConeSeg(), name, "tube", true); + setDimensions(rmin, rmax, z, startPhi, deltaPhi); } /// Set the tube dimensions -Tube& Tube::setDimensions(double rmin, double rmax, double z, double startPhi, double deltaPhi) -{ +Tube& Tube::setDimensions(double rmin, double rmax, double z, double startPhi, double deltaPhi) { //double params[] = {rmin*MM_2_CM,rmax*MM_2_CM,z*MM_2_CM,RAD_2_DEGREE*startPhi,RAD_2_DEGREE*deltaPhi}; - double params[] = {z*MM_2_CM,rmin*MM_2_CM,rmax*MM_2_CM,rmin*MM_2_CM,rmax*MM_2_CM,RAD_2_DEGREE*startPhi,RAD_2_DEGREE*deltaPhi}; + double params[] = { z * MM_2_CM, rmin * MM_2_CM, rmax * MM_2_CM, rmin * MM_2_CM, rmax * MM_2_CM, RAD_2_DEGREE * startPhi, + RAD_2_DEGREE * deltaPhi }; _setDimensions(params); return *this; } /// Constructor to be used when creating a new object with attribute initialization -void Cone::make(const string& name, - double z, - double rmin1, - double rmax1, - double rmin2, - double rmax2) -{ - _assign(new TGeoCone(z*MM_2_CM,rmin1*MM_2_CM,rmax1*MM_2_CM,rmin2*MM_2_CM,rmax2*MM_2_CM),name,"cone",true); -} - -Cone& Cone::setDimensions(double z,double rmin1,double rmax1,double rmin2,double rmax2) { - double params[] = {z*MM_2_CM,rmin1*MM_2_CM,rmax1*MM_2_CM,rmin2*MM_2_CM,rmax2*MM_2_CM}; - _setDimensions(params); - return *this; +void Cone::make(const string& name, double z, double rmin1, double rmax1, double rmin2, double rmax2) { + _assign(new TGeoCone(z * MM_2_CM, rmin1 * MM_2_CM, rmax1 * MM_2_CM, rmin2 * MM_2_CM, rmax2 * MM_2_CM), name, "cone", true); } -/// Constructor to be used when creating a new object -Trapezoid::Trapezoid() { - _assign(new TGeoTrd2(0,0,0,0,0),"","trd2",true); -} - -/// Constructor to be used when creating a new object -Trapezoid::Trapezoid(const string& name) { - _assign(new TGeoTrd2(0,0,0,0,0),name,"trd2",true); -} - -/// Constructor to be used when creating a new object with attribute initialization -Trapezoid::Trapezoid(const string& name, double x1, double x2, double y1, double y2, double z) { - _assign(new TGeoTrd2(x1*MM_2_CM,x2*MM_2_CM,y1*MM_2_CM,y2*MM_2_CM,z*MM_2_CM),name,"trd2",true); +Cone& Cone::setDimensions(double z, double rmin1, double rmax1, double rmin2, double rmax2) { + double params[] = { z * MM_2_CM, rmin1 * MM_2_CM, rmax1 * MM_2_CM, rmin2 * MM_2_CM, rmax2 * MM_2_CM }; + _setDimensions(params); + return *this; } /// Constructor to be used when creating a new object with attribute initialization -Trapezoid::Trapezoid(double x1, double x2, double y1, double y2, double z) { - _assign(new TGeoTrd2(x1*MM_2_CM,x2*MM_2_CM,y1*MM_2_CM,y2*MM_2_CM,z*MM_2_CM),"","trd2",true); +Trapezoid::Trapezoid(double x1, double x2, double y1, double y2, double z) { + _assign(new TGeoTrd2(x1 * MM_2_CM, x2 * MM_2_CM, y1 * MM_2_CM, y2 * MM_2_CM, z * MM_2_CM), "", "trd2", true); } /// Set the Trapezoid dimensions -Trapezoid& Trapezoid::setDimensions(double x1, double x2, double y1, double y2, double z) { - double params[] = {x1*MM_2_CM,x2*MM_2_CM,y1*MM_2_CM,y2*MM_2_CM,z*MM_2_CM}; +Trapezoid& Trapezoid::setDimensions(double x1, double x2, double y1, double y2, double z) { + double params[] = { x1 * MM_2_CM, x2 * MM_2_CM, y1 * MM_2_CM, y2 * MM_2_CM, z * MM_2_CM }; _setDimensions(params); return *this; } -/// Constructor to be used when creating a new object -Paraboloid::Paraboloid(const string& name) { - _assign(new TGeoParaboloid(0,0,0),name,"paraboloid",true); -} - -/// Constructor to be used when creating a new identified object with attribute initialization -Paraboloid::Paraboloid(const string& name, double r_low, double r_high, double delta_z) { - _assign(new TGeoParaboloid(r_low*MM_2_CM,r_high*MM_2_CM,delta_z*MM_2_CM),name,"paraboloid",true); -} - /// Constructor to be used when creating a new object with attribute initialization -Paraboloid::Paraboloid(double r_low, double r_high, double delta_z) { - _assign(new TGeoParaboloid(r_low*MM_2_CM,r_high*MM_2_CM,delta_z*MM_2_CM),"","paraboloid",true); +Paraboloid::Paraboloid(double r_low, double r_high, double delta_z) { + _assign(new TGeoParaboloid(r_low * MM_2_CM, r_high * MM_2_CM, delta_z * MM_2_CM), "", "paraboloid", true); } /// Set the Paraboloid dimensions -Paraboloid& Paraboloid::setDimensions(double r_low, double r_high, double delta_z) { - double params[] = {r_low*MM_2_CM,r_high*MM_2_CM,delta_z*MM_2_CM}; +Paraboloid& Paraboloid::setDimensions(double r_low, double r_high, double delta_z) { + double params[] = { r_low * MM_2_CM, r_high * MM_2_CM, delta_z * MM_2_CM }; _setDimensions(params); return *this; } -/// Constructor to be used when creating a new anonymous object -Sphere::Sphere() { - _assign(new TGeoSphere(0,0),"","sphere",true); -} - -/// Constructor to be used when creating a new identified object -Sphere::Sphere(const string& name) { - _assign(new TGeoSphere(0,0),name,"sphere",true); -} - -/// Constructor to be used when creating a new identified object with attribute initialization -Sphere::Sphere(const string& name, double rmin, double rmax, double theta, double delta_theta, double phi, double delta_phi) { - _assign(new TGeoSphere(rmin*MM_2_CM,rmax*MM_2_CM,RAD_2_DEGREE*theta,RAD_2_DEGREE*delta_theta,RAD_2_DEGREE*phi,RAD_2_DEGREE*delta_phi),name,"sphere",true); -} - /// Constructor to be used when creating a new object with attribute initialization -Sphere::Sphere(double rmin, double rmax, double theta, double delta_theta, double phi, double delta_phi) { - _assign(new TGeoSphere(rmin*MM_2_CM,rmax*MM_2_CM,RAD_2_DEGREE*theta,RAD_2_DEGREE*delta_theta,RAD_2_DEGREE*phi,RAD_2_DEGREE*delta_phi),"","sphere",true); +Sphere::Sphere(double rmin, double rmax, double theta, double delta_theta, double phi, double delta_phi) { + _assign( + new TGeoSphere(rmin * MM_2_CM, rmax * MM_2_CM, RAD_2_DEGREE * theta, RAD_2_DEGREE * delta_theta, RAD_2_DEGREE * phi, + RAD_2_DEGREE * delta_phi), "", "sphere", true); } /// Set the Sphere dimensions -Sphere& Sphere::setDimensions(double rmin, double rmax, double theta, double delta_theta, double phi, double delta_phi) { - double params[] = {rmin*MM_2_CM,rmax*MM_2_CM,RAD_2_DEGREE*theta,RAD_2_DEGREE*delta_theta,RAD_2_DEGREE*phi,RAD_2_DEGREE*delta_phi}; +Sphere& Sphere::setDimensions(double rmin, double rmax, double theta, double delta_theta, double phi, double delta_phi) { + double params[] = { rmin * MM_2_CM, rmax * MM_2_CM, RAD_2_DEGREE * theta, RAD_2_DEGREE * delta_theta, RAD_2_DEGREE * phi, + RAD_2_DEGREE * delta_phi }; _setDimensions(params); return *this; } -/// Constructor to be used when creating a new object -Torus::Torus() { - _assign(new TGeoTorus(0,0,0),"","torus",true); -} - -/// Constructor to be used when creating a new object -Torus::Torus(const string& name) { - _assign(new TGeoTorus(0,0,0),name,"torus",true); -} - -/// Constructor to be used when creating a new identified object with attribute initialization -Torus::Torus(const string& name, double r, double rmin, double rmax, double phi, double delta_phi) { - _assign(new TGeoTorus(r*MM_2_CM,rmin*MM_2_CM,rmax*MM_2_CM,RAD_2_DEGREE*phi,RAD_2_DEGREE*delta_phi),name,"torus",true); -} - /// Constructor to be used when creating a new object with attribute initialization -Torus::Torus(double r, double rmin, double rmax, double phi, double delta_phi) { - _assign(new TGeoTorus(r*MM_2_CM,rmin*MM_2_CM,rmax*MM_2_CM,RAD_2_DEGREE*phi,RAD_2_DEGREE*delta_phi),"","torus",true); +Torus::Torus(double r, double rmin, double rmax, double phi, double delta_phi) { + _assign(new TGeoTorus(r * MM_2_CM, rmin * MM_2_CM, rmax * MM_2_CM, RAD_2_DEGREE * phi, RAD_2_DEGREE * delta_phi), "", "torus", + true); } /// Set the Torus dimensions -Torus& Torus::setDimensions(double r, double rmin, double rmax, double phi, double delta_phi) { - double params[] = {r*MM_2_CM,rmin*MM_2_CM,rmax*MM_2_CM,RAD_2_DEGREE*phi,RAD_2_DEGREE*delta_phi}; +Torus& Torus::setDimensions(double r, double rmin, double rmax, double phi, double delta_phi) { + double params[] = { r * MM_2_CM, rmin * MM_2_CM, rmax * MM_2_CM, RAD_2_DEGREE * phi, RAD_2_DEGREE * delta_phi }; _setDimensions(params); return *this; } -/// Constructor to be used when creating a new identified object with attribute initialization -Trap::Trap( const string& name, - double z, - double theta, - double phi, - double y1, - double x1, - double x2, - double alpha1, - double y2, - double x3, - double x4, - double alpha2) -{ - _assign(new TGeoTrap(z,RAD_2_DEGREE*theta,RAD_2_DEGREE*phi,y1*MM_2_CM,x1*MM_2_CM,x2*MM_2_CM,alpha1,y2*MM_2_CM,x3*MM_2_CM,x4*MM_2_CM,alpha2),name,"trap",true); -} - /// Constructor to be used when creating a new anonymous object with attribute initialization -Trap::Trap( double z, - double theta, - double phi, - double y1, - double x1, - double x2, - double alpha1, - double y2, - double x3, - double x4, - double alpha2) -{ - _assign(new TGeoTrap(z,RAD_2_DEGREE*theta,RAD_2_DEGREE*phi,y1*MM_2_CM,x1*MM_2_CM,x2*MM_2_CM,alpha1,y2*MM_2_CM,x3*MM_2_CM,x4*MM_2_CM,alpha2),"","trap",true); +Trap::Trap(double z, double theta, double phi, double y1, double x1, double x2, double alpha1, double y2, double x3, double x4, + double alpha2) { + _assign( + new TGeoTrap(z, RAD_2_DEGREE * theta, RAD_2_DEGREE * phi, y1 * MM_2_CM, x1 * MM_2_CM, x2 * MM_2_CM, alpha1, y2 * MM_2_CM, + x3 * MM_2_CM, x4 * MM_2_CM, alpha2), "", "trap", true); } /// Constructor to be used when creating a new anonymous object with attribute initialization -Trap::Trap( double pz, double py, double px, double pLTX) { - double z = pz/2e0; - double theta = 0e0; - double phi = 0e0; - double y1 = py/2e0; - double x1 = px/2e0; - double x2 = pLTX/2e0; - double alpha1 = (pLTX-px)/py; - _assign(new TGeoTrap(z,RAD_2_DEGREE*theta,RAD_2_DEGREE*phi,y1*MM_2_CM,x1*MM_2_CM,x2*MM_2_CM,alpha1,y1*MM_2_CM,x1*MM_2_CM,x2*MM_2_CM,alpha1),"","trap",true); +Trap::Trap(double pz, double py, double px, double pLTX) { + double z = pz / 2e0; + double theta = 0e0; + double phi = 0e0; + double y1 = py / 2e0; + double x1 = px / 2e0; + double x2 = pLTX / 2e0; + double alpha1 = (pLTX - px) / py; + _assign( + new TGeoTrap(z, RAD_2_DEGREE * theta, RAD_2_DEGREE * phi, y1 * MM_2_CM, x1 * MM_2_CM, x2 * MM_2_CM, alpha1, y1 * MM_2_CM, + x1 * MM_2_CM, x2 * MM_2_CM, alpha1), "", "trap", true); } /// Set the trap dimensions -Trap& Trap::setDimensions(double z,double theta,double phi, - double y1,double x1,double x2,double alpha1, - double y2,double x3,double x4,double alpha2) { - double params[] = {z,RAD_2_DEGREE * theta,RAD_2_DEGREE * phi,y1*MM_2_CM,x1*MM_2_CM,x2*MM_2_CM,alpha1,y2*MM_2_CM,x3*MM_2_CM,x4*MM_2_CM,alpha2}; +Trap& Trap::setDimensions(double z, double theta, double phi, double y1, double x1, double x2, double alpha1, double y2, + double x3, double x4, double alpha2) { + double params[] = { z, RAD_2_DEGREE * theta, RAD_2_DEGREE * phi, y1 * MM_2_CM, x1 * MM_2_CM, x2 * MM_2_CM, alpha1, y2 + * MM_2_CM, x3 * MM_2_CM, x4 * MM_2_CM, alpha2 }; _setDimensions(params); return *this; } /// Helper function to create holy hedron -void PolyhedraRegular::_create(const string& name, int nsides, double rmin, double rmax, - double zpos, double zneg, double start, double delta) -{ - if ( rmin<0e0 || rmin>rmax ) - throw runtime_error("DD4hep: PolyhedraRegular: Illegal argument rmin:<"+_toString(rmin)+"> is invalid!"); - else if ( rmax<0e0 ) - throw runtime_error("DD4hep: PolyhedraRegular: Illegal argument rmax:<"+_toString(rmax)+"> is invalid!"); - _assign(new TGeoPgon(),name,"polyhedra",false); - double params[] = { - RAD_2_DEGREE * start, - RAD_2_DEGREE * delta, - double(nsides), - 2e0, - zpos*MM_2_CM,rmin*MM_2_CM,rmax*MM_2_CM, - zneg*MM_2_CM,rmin*MM_2_CM,rmax*MM_2_CM - }; +void PolyhedraRegular::_create(const string& name, int nsides, double rmin, double rmax, double zpos, double zneg, double start, + double delta) { + if (rmin < 0e0 || rmin > rmax) + throw runtime_error("DD4hep: PolyhedraRegular: Illegal argument rmin:<" + _toString(rmin) + "> is invalid!"); + else if (rmax < 0e0) + throw runtime_error("DD4hep: PolyhedraRegular: Illegal argument rmax:<" + _toString(rmax) + "> is invalid!"); + _assign(new TGeoPgon(), name, "polyhedra", false); + double params[] = { RAD_2_DEGREE * start, RAD_2_DEGREE * delta, double(nsides), 2e0, zpos * MM_2_CM, rmin * MM_2_CM, rmax + * MM_2_CM, zneg * MM_2_CM, rmin * MM_2_CM, rmax * MM_2_CM }; _setDimensions(¶ms[0]); } /// Constructor to be used when creating a new object -PolyhedraRegular::PolyhedraRegular(const string& name, int nsides, double rmin, double rmax, double zlen) { - _create(name,nsides,rmin,rmax,zlen/2,-zlen/2,0,2*M_PI); -} - -/// Constructor to be used when creating a new object -PolyhedraRegular::PolyhedraRegular(int nsides, double rmin, double rmax, double zlen) { - _create("",nsides,rmin,rmax,zlen/2,-zlen/2,0,2*M_PI); +PolyhedraRegular::PolyhedraRegular(int nsides, double rmin, double rmax, double zlen) { + _create("", nsides, rmin, rmax, zlen / 2, -zlen / 2, 0, 2 * M_PI); } /// Constructor to be used when creating a new object -PolyhedraRegular::PolyhedraRegular(int nsides, double phistart, double rmin, double rmax, double zlen) { - _create("",nsides,rmin,rmax,zlen/2,-zlen/2,phistart,2*M_PI); +PolyhedraRegular::PolyhedraRegular(int nsides, double phistart, double rmin, double rmax, double zlen) { + _create("", nsides, rmin, rmax, zlen / 2, -zlen / 2, phistart, 2 * M_PI); } /// Constructor to be used when creating a new object -PolyhedraRegular::PolyhedraRegular(int nsides, double rmin, double rmax, double zplanes[2]) { - _create("",nsides,rmin,rmax,zplanes[0],zplanes[1],0,2*M_PI); +PolyhedraRegular::PolyhedraRegular(int nsides, double rmin, double rmax, double zplanes[2]) { + _create("", nsides, rmin, rmax, zplanes[0], zplanes[1], 0, 2 * M_PI); } /// Constructor to be used when creating a new object. Position is identity, Rotation is the identity rotation -SubtractionSolid::SubtractionSolid(const Solid& shape1, const Solid& shape2) { - TGeoSubtraction* sub = new TGeoSubtraction(shape1,shape2,identityTransform(),identityTransform()); - _assign(new TGeoCompositeShape("",sub),"","subtraction",true); +SubtractionSolid::SubtractionSolid(const Solid& shape1, const Solid& shape2) { + TGeoSubtraction* sub = new TGeoSubtraction(shape1, shape2, identityTransform(), identityTransform()); + _assign(new TGeoCompositeShape("", sub), "", "subtraction", true); } /// Constructor to be used when creating a new object. Placement by a generic transformation within the mother -SubtractionSolid::SubtractionSolid(const Solid& shape1, const Solid& shape2, const Transform3D& trans) { - TGeoSubtraction* sub = new TGeoSubtraction(shape1,shape2,identityTransform(),_transform(trans)); - _assign(new TGeoCompositeShape("",sub),"","subtraction",true); +SubtractionSolid::SubtractionSolid(const Solid& shape1, const Solid& shape2, const Transform3D& trans) { + TGeoSubtraction* sub = new TGeoSubtraction(shape1, shape2, identityTransform(), _transform(trans)); + _assign(new TGeoCompositeShape("", sub), "", "subtraction", true); } /// Constructor to be used when creating a new object. Rotation is the identity rotation -SubtractionSolid::SubtractionSolid(const Solid& shape1, const Solid& shape2, const Position& pos) { - TGeoSubtraction* sub = new TGeoSubtraction(shape1,shape2,identityTransform(),_translation(pos)); - _assign(new TGeoCompositeShape("",sub),"","subtraction",true); +SubtractionSolid::SubtractionSolid(const Solid& shape1, const Solid& shape2, const Position& pos) { + TGeoSubtraction* sub = new TGeoSubtraction(shape1, shape2, identityTransform(), _translation(pos)); + _assign(new TGeoCompositeShape("", sub), "", "subtraction", true); } /// Constructor to be used when creating a new object -SubtractionSolid::SubtractionSolid(const Solid& shape1, const Solid& shape2, const RotationZYX& rot) { - TGeoSubtraction* sub = new TGeoSubtraction(shape1,shape2,identityTransform(),_rotationZYX(rot)); - _assign(new TGeoCompositeShape("",sub),"","subtraction",true); +SubtractionSolid::SubtractionSolid(const Solid& shape1, const Solid& shape2, const RotationZYX& rot) { + TGeoSubtraction* sub = new TGeoSubtraction(shape1, shape2, identityTransform(), _rotationZYX(rot)); + _assign(new TGeoCompositeShape("", sub), "", "subtraction", true); } /// Constructor to be used when creating a new object -SubtractionSolid::SubtractionSolid(const Solid& shape1, const Solid& shape2, const Rotation3D& rot) { - TGeoSubtraction* sub = new TGeoSubtraction(shape1,shape2,identityTransform(),_rotation3D(rot)); - _assign(new TGeoCompositeShape("",sub),"","subtraction",true); +SubtractionSolid::SubtractionSolid(const Solid& shape1, const Solid& shape2, const Rotation3D& rot) { + TGeoSubtraction* sub = new TGeoSubtraction(shape1, shape2, identityTransform(), _rotation3D(rot)); + _assign(new TGeoCompositeShape("", sub), "", "subtraction", true); } /// Constructor to be used when creating a new object. Position is identity, Rotation is identity rotation -UnionSolid::UnionSolid(const Solid& shape1, const Solid& shape2) { - TGeoUnion* uni = new TGeoUnion(shape1,shape2,identityTransform(),identityTransform()); - _assign(new TGeoCompositeShape("",uni),"","union",true); +UnionSolid::UnionSolid(const Solid& shape1, const Solid& shape2) { + TGeoUnion* uni = new TGeoUnion(shape1, shape2, identityTransform(), identityTransform()); + _assign(new TGeoCompositeShape("", uni), "", "union", true); } /// Constructor to be used when creating a new object. Placement by a generic transformation within the mother -UnionSolid::UnionSolid(const Solid& shape1, const Solid& shape2, const Transform3D& trans) { - TGeoUnion* uni = new TGeoUnion(shape1,shape2,identityTransform(),_transform(trans)); - _assign(new TGeoCompositeShape("",uni),"","union",true); +UnionSolid::UnionSolid(const Solid& shape1, const Solid& shape2, const Transform3D& trans) { + TGeoUnion* uni = new TGeoUnion(shape1, shape2, identityTransform(), _transform(trans)); + _assign(new TGeoCompositeShape("", uni), "", "union", true); } /// Constructor to be used when creating a new object. Rotation is identity rotation -UnionSolid::UnionSolid(const Solid& shape1, const Solid& shape2, const Position& pos) { - TGeoUnion* uni = new TGeoUnion(shape1,shape2,identityTransform(),_translation(pos)); - _assign(new TGeoCompositeShape("",uni),"","union",true); +UnionSolid::UnionSolid(const Solid& shape1, const Solid& shape2, const Position& pos) { + TGeoUnion* uni = new TGeoUnion(shape1, shape2, identityTransform(), _translation(pos)); + _assign(new TGeoCompositeShape("", uni), "", "union", true); } /// Constructor to be used when creating a new object -UnionSolid::UnionSolid(const Solid& shape1, const Solid& shape2, const RotationZYX& rot) { - TGeoUnion *uni = new TGeoUnion(shape1,shape2,identityTransform(),_rotationZYX(rot)); - _assign(new TGeoCompositeShape("",uni),"","union",true); +UnionSolid::UnionSolid(const Solid& shape1, const Solid& shape2, const RotationZYX& rot) { + TGeoUnion *uni = new TGeoUnion(shape1, shape2, identityTransform(), _rotationZYX(rot)); + _assign(new TGeoCompositeShape("", uni), "", "union", true); } /// Constructor to be used when creating a new object -UnionSolid::UnionSolid(const Solid& shape1, const Solid& shape2, const Rotation3D& rot) { - TGeoUnion *uni = new TGeoUnion(shape1,shape2,identityTransform(),_rotation3D(rot)); - _assign(new TGeoCompositeShape("",uni),"","union",true); +UnionSolid::UnionSolid(const Solid& shape1, const Solid& shape2, const Rotation3D& rot) { + TGeoUnion *uni = new TGeoUnion(shape1, shape2, identityTransform(), _rotation3D(rot)); + _assign(new TGeoCompositeShape("", uni), "", "union", true); } /// Constructor to be used when creating a new object. Position is identity, Rotation is identity rotation -IntersectionSolid::IntersectionSolid(const Solid& shape1, const Solid& shape2) { - TGeoIntersection* inter = new TGeoIntersection(shape1,shape2,identityTransform(),identityTransform()); - _assign(new TGeoCompositeShape("",inter),"","intersection",true); +IntersectionSolid::IntersectionSolid(const Solid& shape1, const Solid& shape2) { + TGeoIntersection* inter = new TGeoIntersection(shape1, shape2, identityTransform(), identityTransform()); + _assign(new TGeoCompositeShape("", inter), "", "intersection", true); } /// Constructor to be used when creating a new object. Placement by a generic transformation within the mother -IntersectionSolid::IntersectionSolid(const Solid& shape1, const Solid& shape2, const Transform3D& trans) { - TGeoIntersection* inter = new TGeoIntersection(shape1,shape2,identityTransform(),_transform(trans)); - _assign(new TGeoCompositeShape("",inter),"","intersection",true); +IntersectionSolid::IntersectionSolid(const Solid& shape1, const Solid& shape2, const Transform3D& trans) { + TGeoIntersection* inter = new TGeoIntersection(shape1, shape2, identityTransform(), _transform(trans)); + _assign(new TGeoCompositeShape("", inter), "", "intersection", true); } /// Constructor to be used when creating a new object. Position is identity. -IntersectionSolid::IntersectionSolid(const Solid& shape1, const Solid& shape2, const Position& pos) { - TGeoIntersection* inter = new TGeoIntersection(shape1,shape2,identityTransform(),_translation(pos)); - _assign(new TGeoCompositeShape("",inter),"","intersection",true); +IntersectionSolid::IntersectionSolid(const Solid& shape1, const Solid& shape2, const Position& pos) { + TGeoIntersection* inter = new TGeoIntersection(shape1, shape2, identityTransform(), _translation(pos)); + _assign(new TGeoCompositeShape("", inter), "", "intersection", true); } /// Constructor to be used when creating a new object -IntersectionSolid::IntersectionSolid(const Solid& shape1, const Solid& shape2, const RotationZYX& rot) { - TGeoIntersection* inter = new TGeoIntersection(shape1,shape2,identityTransform(),_rotationZYX(rot)); - _assign(new TGeoCompositeShape("",inter),"","intersection",true); +IntersectionSolid::IntersectionSolid(const Solid& shape1, const Solid& shape2, const RotationZYX& rot) { + TGeoIntersection* inter = new TGeoIntersection(shape1, shape2, identityTransform(), _rotationZYX(rot)); + _assign(new TGeoCompositeShape("", inter), "", "intersection", true); } /// Constructor to be used when creating a new object -IntersectionSolid::IntersectionSolid(const Solid& shape1, const Solid& shape2, const Rotation3D& rot) { - TGeoIntersection* inter = new TGeoIntersection(shape1,shape2,identityTransform(),_rotation3D(rot)); - _assign(new TGeoCompositeShape("",inter),"","intersection",true); +IntersectionSolid::IntersectionSolid(const Solid& shape1, const Solid& shape2, const Rotation3D& rot) { + TGeoIntersection* inter = new TGeoIntersection(shape1, shape2, identityTransform(), _rotation3D(rot)); + _assign(new TGeoCompositeShape("", inter), "", "intersection", true); } #define INSTANTIATE(X) template class DD4hep::Geometry::Solid_type<X> diff --git a/DDCore/src/SimpleGDMLWriter.cpp b/DDCore/src/SimpleGDMLWriter.cpp index 7488c25be..adb060f89 100644 --- a/DDCore/src/SimpleGDMLWriter.cpp +++ b/DDCore/src/SimpleGDMLWriter.cpp @@ -37,53 +37,55 @@ using namespace std; namespace { string indent = ""; - void getAngles(const Double_t* m, Double_t &phi, Double_t &theta, Double_t &psi) { + void getAngles(const Double_t* m, Double_t &phi, Double_t &theta, Double_t &psi) { // Retreive Euler angles. // Check if theta is 0 or 180. - if (TMath::Abs(1.-TMath::Abs(m[8]))<1.e-9) { - theta = TMath::ACos(m[8])*RAD_2_DEGREE; - phi = TMath::ATan2(-m[8]*m[1],m[0])*RAD_2_DEGREE; - psi = 0.; // convention, phi+psi matters + if (TMath::Abs(1. - TMath::Abs(m[8])) < 1.e-9) { + theta = TMath::ACos(m[8]) * RAD_2_DEGREE; + phi = TMath::ATan2(-m[8] * m[1], m[0]) * RAD_2_DEGREE; + psi = 0.; // convention, phi+psi matters return; } // sin(theta) != 0 - phi = TMath::ATan2(m[2],-m[5]); + phi = TMath::ATan2(m[2], -m[5]); Double_t sphi = TMath::Sin(phi); - if (TMath::Abs(sphi)<1.e-9) theta = -TMath::ASin(m[5]/TMath::Cos(phi))*RAD_2_DEGREE; - else theta = TMath::ASin(m[2]/sphi)*RAD_2_DEGREE; - phi *= RAD_2_DEGREE; - psi = TMath::ATan2(m[6],m[7])*RAD_2_DEGREE; + if (TMath::Abs(sphi) < 1.e-9) + theta = -TMath::ASin(m[5] / TMath::Cos(phi)) * RAD_2_DEGREE; + else + theta = TMath::ASin(m[2] / sphi) * RAD_2_DEGREE; + phi *= RAD_2_DEGREE; + psi = TMath::ATan2(m[6], m[7]) * RAD_2_DEGREE; } } /// Dump logical volume in GDML format to output stream -void* SimpleGDMLWriter::handleVolume(const string& name, const TGeoVolume* volume) const { - Volume vol = Handle<>(volume); - VisAttr vis = vol.visAttributes(); - TGeoShape* shape = volume->GetShape(); +void* SimpleGDMLWriter::handleVolume(const string& name, const TGeoVolume* volume) const { + Volume vol = Handle<>(volume); + VisAttr vis = vol.visAttributes(); + TGeoShape* shape = volume->GetShape(); TGeoMedium* medium = volume->GetMedium(); - int num = volume->GetNdaughters(); + int num = volume->GetNdaughters(); m_output << "\t\t<volume name=\"" << name << "\">" << endl; m_output << "\t\t\t<solidref ref=\"" << shape->GetName() << "\"/>" << endl; m_output << "\t\t\t<materialref ref=\"" << medium->GetName() << "\"/>" << endl; - if ( vis.isValid() ) { + if (vis.isValid()) { m_output << "\t\t\t<visref ref=\"" << vis.name() << "\"/>" << endl; } - if ( num > 0 ) { - for(int i=0; i<num; ++i) { - TGeoNode* n = volume->GetNode(i); + if (num > 0) { + for (int i = 0; i < num; ++i) { + TGeoNode* n = volume->GetNode(i); TGeoVolume* v = n->GetVolume(); TGeoMatrix* m = n->GetMatrix(); m_output << "\t\t\t<physvol>" << endl; m_output << "\t\t\t\t<volumeref ref=\"" << v->GetName() << "\"/>" << endl; - if ( m ) { - if ( m->IsTranslation() ) { - m_output << "\t\t\t\t<positionref ref=\"" << n->GetName() << "_pos\"/>" << endl; - } - if ( m->IsRotation() ) { - m_output << "\t\t\t\t<rotationref ref=\"" << n->GetName() << "_rot\"/>" << endl; - } + if (m) { + if (m->IsTranslation()) { + m_output << "\t\t\t\t<positionref ref=\"" << n->GetName() << "_pos\"/>" << endl; + } + if (m->IsRotation()) { + m_output << "\t\t\t\t<rotationref ref=\"" << n->GetName() << "_rot\"/>" << endl; + } } m_output << "\t\t\t</physvol>" << endl; } @@ -93,207 +95,184 @@ void* SimpleGDMLWriter::handleVolume(const string& name, const TGeoVolume* volum } /// Dump solid in GDML format to output stream -void* SimpleGDMLWriter::handleSolid(const string& name, const TGeoShape* shape) const { - if ( shape ) { - if ( shape->IsA() == TGeoBBox::Class() ) { - const TGeoBBox* s = (const TGeoBBox*)shape; - m_output << "\t\t<box name=\"" << name << "_shape\" x=\"" - << s->GetDX() << "\" y=\"" - << s->GetDY() << "\" z=\"" - << s->GetDZ() << "\" lunit=\"cm\"/>" << endl; +void* SimpleGDMLWriter::handleSolid(const string& name, const TGeoShape* shape) const { + if (shape) { + if (shape->IsA() == TGeoBBox::Class()) { + const TGeoBBox* s = (const TGeoBBox*) shape; + m_output << "\t\t<box name=\"" << name << "_shape\" x=\"" << s->GetDX() << "\" y=\"" << s->GetDY() << "\" z=\"" + << s->GetDZ() << "\" lunit=\"cm\"/>" << endl; } - else if ( shape->IsA() == TGeoTube::Class() ) { - const TGeoTube* s = (const TGeoTube*)shape; - m_output << "\t\t<tube name=\"" << name << "_shape\" rmin=\"" - << s->GetRmin() << "\" rmax=\"" - << s->GetRmax() << "\" z=\"" - << s->GetDz() << "\" startphi=\"0.0\" deltaphi=\"360.0\" aunit=\"deg\" lunit=\"cm\"/>" << endl; + else if (shape->IsA() == TGeoTube::Class()) { + const TGeoTube* s = (const TGeoTube*) shape; + m_output << "\t\t<tube name=\"" << name << "_shape\" rmin=\"" << s->GetRmin() << "\" rmax=\"" << s->GetRmax() << "\" z=\"" + << s->GetDz() << "\" startphi=\"0.0\" deltaphi=\"360.0\" aunit=\"deg\" lunit=\"cm\"/>" << endl; } - else if ( shape->IsA() == TGeoTubeSeg::Class() ) { - const TGeoTubeSeg* s = (const TGeoTubeSeg*)shape; - m_output << "\t\t<tube name=\"" << name << "_shape\" rmin=\"" - << s->GetRmin() << "\" rmax=\"" - << s->GetRmax() << "\" z=\"" - << s->GetDz() << "\" startphi=\"" - << s->GetPhi1() << "\" deltaphi=\"" - << s->GetPhi2() << "\" aunit=\"deg\" lunit=\"cm\"/>" << endl; + else if (shape->IsA() == TGeoTubeSeg::Class()) { + const TGeoTubeSeg* s = (const TGeoTubeSeg*) shape; + m_output << "\t\t<tube name=\"" << name << "_shape\" rmin=\"" << s->GetRmin() << "\" rmax=\"" << s->GetRmax() << "\" z=\"" + << s->GetDz() << "\" startphi=\"" << s->GetPhi1() << "\" deltaphi=\"" << s->GetPhi2() + << "\" aunit=\"deg\" lunit=\"cm\"/>" << endl; } - else if ( shape->IsA() == TGeoTrd1::Class() ) { - const TGeoTrd1* s = (const TGeoTrd1*)shape; - m_output << "\t\t<tube name=\"" << name << "_shape\" x1=\"" - << s->GetDx1() << "\" x2=\"" - << s->GetDx2() << "\" y1=\"" - << s->GetDy() << "\" y2=\"" - << s->GetDy() << "\" z=\"" - << s->GetDz() << "\" lunit=\"cm\"/>" << endl; + else if (shape->IsA() == TGeoTrd1::Class()) { + const TGeoTrd1* s = (const TGeoTrd1*) shape; + m_output << "\t\t<tube name=\"" << name << "_shape\" x1=\"" << s->GetDx1() << "\" x2=\"" << s->GetDx2() << "\" y1=\"" + << s->GetDy() << "\" y2=\"" << s->GetDy() << "\" z=\"" << s->GetDz() << "\" lunit=\"cm\"/>" << endl; } - else if ( shape->IsA() == TGeoTrd2::Class() ) { - const TGeoTrd2* s = (const TGeoTrd2*)shape; - m_output << "\t\t<tube name=\"" << name << "_shape\" x1=\"" - << s->GetDx1() << "\" x2=\"" - << s->GetDx2() << "\" y1=\"" - << s->GetDy1() << "\" y2=\"" - << s->GetDy2() << "\" z=\"" - << s->GetDz() << "\" lunit=\"cm\"/>" << endl; + else if (shape->IsA() == TGeoTrd2::Class()) { + const TGeoTrd2* s = (const TGeoTrd2*) shape; + m_output << "\t\t<tube name=\"" << name << "_shape\" x1=\"" << s->GetDx1() << "\" x2=\"" << s->GetDx2() << "\" y1=\"" + << s->GetDy1() << "\" y2=\"" << s->GetDy2() << "\" z=\"" << s->GetDz() << "\" lunit=\"cm\"/>" << endl; } - else if ( shape->IsA() == TGeoPgon::Class() ) { - const TGeoPgon* s = (const TGeoPgon*)shape; - m_output << "\t\t<polyhedra name=\"" << name << "_shape\" startphi=\"" - << s->GetPhi1() << "\" deltaphi=\"" - << s->GetDphi() << "\" numsides=\"" - << s->GetNedges() << "\" aunit=\"deg\" lunit=\"cm\">" << endl; - for(int i=0; i<s->GetNz(); ++i) { - m_output << "\t\t\t<zplane z=\"" << s->GetZ(i) - << "\" rmin=\"" << s->GetRmin(i) - << "\" rmax=\"" << s->GetRmax(i) - << "\" lunit=\"cm\"/>" << endl; + else if (shape->IsA() == TGeoPgon::Class()) { + const TGeoPgon* s = (const TGeoPgon*) shape; + m_output << "\t\t<polyhedra name=\"" << name << "_shape\" startphi=\"" << s->GetPhi1() << "\" deltaphi=\"" << s->GetDphi() + << "\" numsides=\"" << s->GetNedges() << "\" aunit=\"deg\" lunit=\"cm\">" << endl; + for (int i = 0; i < s->GetNz(); ++i) { + m_output << "\t\t\t<zplane z=\"" << s->GetZ(i) << "\" rmin=\"" << s->GetRmin(i) << "\" rmax=\"" << s->GetRmax(i) + << "\" lunit=\"cm\"/>" << endl; } m_output << "\t\t</polyhedra>" << endl; } - else if ( shape->IsA() == TGeoPcon::Class() ) { - const TGeoPcon* s = (const TGeoPcon*)shape; - m_output << "\t\t<polycone name=\"" << name << "_shape\" startphi=\"" - << s->GetPhi1() << "\" deltaphi=\"" - << s->GetDphi() << "\" aunit=\"deg\" lunit=\"cm\">" << endl; - for(int i=0; i<s->GetNz(); ++i) { - m_output << "\t\t\t<zplane z=\"" << s->GetZ(i) - << "\" rmin=\"" << s->GetRmin(i) - << "\" rmax=\"" << s->GetRmax(i) - << "\" lunit=\"cm\"/>" << endl; + else if (shape->IsA() == TGeoPcon::Class()) { + const TGeoPcon* s = (const TGeoPcon*) shape; + m_output << "\t\t<polycone name=\"" << name << "_shape\" startphi=\"" << s->GetPhi1() << "\" deltaphi=\"" << s->GetDphi() + << "\" aunit=\"deg\" lunit=\"cm\">" << endl; + for (int i = 0; i < s->GetNz(); ++i) { + m_output << "\t\t\t<zplane z=\"" << s->GetZ(i) << "\" rmin=\"" << s->GetRmin(i) << "\" rmax=\"" << s->GetRmax(i) + << "\" lunit=\"cm\"/>" << endl; } m_output << "\t\t</polycone>" << endl; } - else if ( shape->IsA() == TGeoCompositeShape::Class() ) { + else if (shape->IsA() == TGeoCompositeShape::Class()) { string nn = name; - const TGeoCompositeShape* s = (const TGeoCompositeShape*)shape; + const TGeoCompositeShape* s = (const TGeoCompositeShape*) shape; const TGeoBoolNode* boolean = s->GetBoolNode(); TGeoBoolNode::EGeoBoolType oper = boolean->GetBooleanOperator(); - handleSolid(name+"_left", boolean->GetLeftShape()); - handleSolid(name+"_right",boolean->GetRightShape()); + handleSolid(name + "_left", boolean->GetLeftShape()); + handleSolid(name + "_right", boolean->GetRightShape()); - if ( oper == TGeoBoolNode::kGeoSubtraction ) - m_output << "\t\t<subtraction name=\"" << nn << "\">" << endl; - else if ( oper == TGeoBoolNode::kGeoUnion ) - m_output << "\t\t<union name=\"" << nn << "\">" << endl; - else if ( oper == TGeoBoolNode::kGeoIntersection ) - m_output << "\t\t<intersection name=\"" << nn << "\">" << endl; + if (oper == TGeoBoolNode::kGeoSubtraction) + m_output << "\t\t<subtraction name=\"" << nn << "\">" << endl; + else if (oper == TGeoBoolNode::kGeoUnion) + m_output << "\t\t<union name=\"" << nn << "\">" << endl; + else if (oper == TGeoBoolNode::kGeoIntersection) + m_output << "\t\t<intersection name=\"" << nn << "\">" << endl; - m_output << "\t\t\t<first ref=\"" << nn << "_left\"/>" << endl; + m_output << "\t\t\t<first ref=\"" << nn << "_left\"/>" << endl; m_output << "\t\t\t<second ref=\"" << nn << "_right\"/>" << endl; indent = "\t"; handleTransformation("", boolean->GetRightMatrix()); indent = ""; - if ( oper == TGeoBoolNode::kGeoSubtraction ) - m_output << "\t\t</subtraction>" << endl; - else if ( oper == TGeoBoolNode::kGeoUnion ) - m_output << "\t\t</union>" << endl; - else if ( oper == TGeoBoolNode::kGeoIntersection ) - m_output << "\t\t</intersection>" << endl; + if (oper == TGeoBoolNode::kGeoSubtraction) + m_output << "\t\t</subtraction>" << endl; + else if (oper == TGeoBoolNode::kGeoUnion) + m_output << "\t\t</union>" << endl; + else if (oper == TGeoBoolNode::kGeoIntersection) + m_output << "\t\t</intersection>" << endl; } else { - cerr << "Failed to handle unknwon solid shape:" - << shape->IsA()->GetName() << endl; + cerr << "Failed to handle unknwon solid shape:" << shape->IsA()->GetName() << endl; } } return 0; } /// Dump structure information in GDML format to output stream -void SimpleGDMLWriter::handleStructure(const VolumeSet& volset) const { +void SimpleGDMLWriter::handleStructure(const VolumeSet& volset) const { m_output << "\t<structure>" << endl; - for(VolumeSet::const_iterator i=volset.begin(); i != volset.end(); ++i) - handleVolume((*i)->GetName(),(*i)); + for (VolumeSet::const_iterator i = volset.begin(); i != volset.end(); ++i) + handleVolume((*i)->GetName(), (*i)); m_output << "\t</structure>" << endl; } /// Dump single volume transformation in GDML format to output stream void* SimpleGDMLWriter::handleTransformation(const string& name, const TGeoMatrix* m) const { - if ( m ) { - if ( m->IsTranslation() ) { + if (m) { + if (m->IsTranslation()) { const Double_t* f = m->GetTranslation(); m_output << indent << "\t\t<position "; - if ( !name.empty() ) m_output << "name=\"" << name << "_pos\" "; - m_output << "x=\"" << f[0] << "\" " - << "y=\"" << f[1] << "\" " - << "z=\"" << f[2] << "\" unit=\"cm\"/>" << endl; + if (!name.empty()) + m_output << "name=\"" << name << "_pos\" "; + m_output << "x=\"" << f[0] << "\" " << "y=\"" << f[1] << "\" " << "z=\"" << f[2] << "\" unit=\"cm\"/>" << endl; } - if ( m->IsRotation() ) { + if (m->IsRotation()) { const Double_t* mat = m->GetRotationMatrix(); - Double_t theta=0.0, phi=0.0, psi=0.0; + Double_t theta = 0.0, phi = 0.0, psi = 0.0; getAngles(mat, theta, phi, psi); m_output << indent << "\t\t<rotation "; - if ( !name.empty() ) m_output << "name=\"" << name << "_rot\" "; - m_output << "x=\"" << theta << "\" " - << "y=\"" << psi << "\" " - << "z=\"" << phi << "\" unit=\"deg\"/>" << endl; + if (!name.empty()) + m_output << "name=\"" << name << "_rot\" "; + m_output << "x=\"" << theta << "\" " << "y=\"" << psi << "\" " << "z=\"" << phi << "\" unit=\"deg\"/>" << endl; } } return 0; } /// Dump Transformations in GDML format to output stream -void SimpleGDMLWriter::handleTransformations(const TransformSet& trafos) const { +void SimpleGDMLWriter::handleTransformations(const TransformSet& trafos) const { m_output << "\t<define>" << endl; - for(TransformSet::const_iterator i=trafos.begin(); i != trafos.end(); ++i) + for (TransformSet::const_iterator i = trafos.begin(); i != trafos.end(); ++i) handleTransformation((*i).first, (*i).second); m_output << "\t</define>" << endl; } /// Dump all solids in GDML format to output stream -void SimpleGDMLWriter::handleSolids(const SolidSet& solids) const { +void SimpleGDMLWriter::handleSolids(const SolidSet& solids) const { m_output << "\t<solids>" << endl; - for(SolidSet::const_iterator i=solids.begin(); i != solids.end(); ++i) + for (SolidSet::const_iterator i = solids.begin(); i != solids.end(); ++i) handleSolid((*i)->GetName(), (*i)); m_output << "\t</solids>" << endl; } /// Dump all constants in GDML format to output stream -void SimpleGDMLWriter::handleDefines(const LCDD::HandleMap& defs) const { +void SimpleGDMLWriter::handleDefines(const LCDD::HandleMap& defs) const { m_output << "\t<define>" << endl; - for(LCDD::HandleMap::const_iterator i=defs.begin(); i != defs.end(); ++i) - m_output << "\t\t<constant name=\"" << (*i).second->GetName() << "\" value=\"" << (*i).second->GetTitle() << "\" />" << endl; + for (LCDD::HandleMap::const_iterator i = defs.begin(); i != defs.end(); ++i) + m_output << "\t\t<constant name=\"" << (*i).second->GetName() << "\" value=\"" << (*i).second->GetTitle() << "\" />" + << endl; m_output << "\t</define>" << endl; } /// Dump all visualisation specs in LCDD format to output stream -void SimpleGDMLWriter::handleVisualisation(const VisRefs& vis) const { +void SimpleGDMLWriter::handleVisualisation(const VisRefs& vis) const { m_output << "\t<display>" << endl; - for(VisRefs::const_iterator i=vis.begin(); i != vis.end(); ++i) { + for (VisRefs::const_iterator i = vis.begin(); i != vis.end(); ++i) { VisAttr v = Ref_t(*i); - if ( v.isValid() ) { - float r=1., g=1., b=1., alpha=1.; + if (v.isValid()) { + float r = 1., g = 1., b = 1., alpha = 1.; TColor *color = gROOT->GetColor(v.color()); - if ( color ) { - color->GetRGB(r,g,b); - alpha = color->GetAlpha(); + if (color) { + color->GetRGB(r, g, b); + alpha = color->GetAlpha(); } - const char* line_style=0, *draw_style=0; - switch(v.lineStyle()) { + const char* line_style = 0, *draw_style = 0; + switch (v.lineStyle()) { case VisAttr::DASHED: - line_style = "broken"; - break; - case VisAttr::SOLID: + line_style = "broken"; + break; + case VisAttr::SOLID: default: - line_style = "unbroken"; - break; + line_style = "unbroken"; + break; } - switch(v.drawingStyle()) { + switch (v.drawingStyle()) { case VisAttr::WIREFRAME: - draw_style = "wireframe"; - break; + draw_style = "wireframe"; + break; default: - break; + break; } - m_output << "\t\t<vis name=\"" << v.name() << "\" "; - if ( line_style ) m_output << "linestyle=\"" << line_style << "\" "; - if ( draw_style ) m_output << "drawingStyle=\"" << draw_style << "\" "; - m_output << "show_daughters=\"" << (const char*)(v.showDaughters() ? "true" : "false") << "\" " - << "visible=\"" << (const char*)(v.visible() ? "true" : "false") << "\" >" << endl - << "\t\t\t<color R=\"" << r << "\" G=\"" << g << "\" B=\"" << b << "\" alpha=\"" << alpha << "\" />" << endl - << "\t\t</vis>" << endl; + m_output << "\t\t<vis name=\"" << v.name() << "\" "; + if (line_style) + m_output << "linestyle=\"" << line_style << "\" "; + if (draw_style) + m_output << "drawingStyle=\"" << draw_style << "\" "; + m_output << "show_daughters=\"" << (const char*) (v.showDaughters() ? "true" : "false") << "\" " << "visible=\"" + << (const char*) (v.visible() ? "true" : "false") << "\" >" << endl << "\t\t\t<color R=\"" << r << "\" G=\"" << g + << "\" B=\"" << b << "\" alpha=\"" << alpha << "\" />" << endl << "\t\t</vis>" << endl; } } m_output << "\t</display>" << endl; @@ -301,7 +280,7 @@ void SimpleGDMLWriter::handleVisualisation(const VisRefs& vis) const { void SimpleGDMLWriter::create(DetElement top) { GeometryInfo geo; - collect(top,geo); + collect(top, geo); //handleSetup(LCDD::getInstance().header()); //handleDefines(LCDD::getInstance().constants()); handleVisualisation(geo.vis); diff --git a/DDCore/src/SimpleGDMLWriter.h b/DDCore/src/SimpleGDMLWriter.h index b20d81b21..f51fb0e2d 100644 --- a/DDCore/src/SimpleGDMLWriter.h +++ b/DDCore/src/SimpleGDMLWriter.h @@ -32,14 +32,17 @@ namespace DD4hep { * @author M.Frank * @version 1.0 */ - struct SimpleGDMLWriter : public GeoHandler { + struct SimpleGDMLWriter: public GeoHandler { /// Reference to output stream std::ostream& m_output; - SimpleGDMLWriter(std::ostream& os) : m_output(os) {} + SimpleGDMLWriter(std::ostream& os) + : m_output(os) { + } /// Standard destructor - virtual ~SimpleGDMLWriter() {} + virtual ~SimpleGDMLWriter() { + } /// Main entry point: create required object(s) void create(DetElement top); @@ -53,16 +56,15 @@ namespace DD4hep { /// Dump all constants in GDML format to output stream virtual void handleDefines(const DefinitionSet& defs) const; /// Dump all visualisation specs in LCDD format to output stream - void handleVisualisation(const VisRefs& vis) const; + void handleVisualisation(const VisRefs& vis) const; /// Dump all solids in GDML format to output stream virtual void handleSolids(const SolidSet& solids) const; /// Dump Transformations in GDML format to output stream virtual void handleTransformations(const TransformSet& trafos) const; /// Dump structure information in GDML format to output stream - virtual void handleStructure(const VolumeSet& volset) const; + virtual void handleStructure(const VolumeSet& volset) const; }; } // End namespace Geometry } // End namespace DD4hep #endif // DD4HEP_SIMPLEGDMLWRITER_H - diff --git a/DDCore/src/VolumeManager.cpp b/DDCore/src/VolumeManager.cpp index 20c7aeeda..668db0445 100644 --- a/DDCore/src/VolumeManager.cpp +++ b/DDCore/src/VolumeManager.cpp @@ -26,170 +26,170 @@ using namespace DD4hep::Geometry; namespace { - struct Populator { + struct Populator { typedef vector<const TGeoNode*> Chain; /// Reference to the LCDD instance - LCDD& m_lcdd; + LCDD& m_lcdd; /// Reference to the volume manager to be populated VolumeManager m_volManager; /// Set of already added entries set<VolumeID> m_entries; /// Default constructor - Populator(LCDD& lcdd, VolumeManager vm) : m_lcdd(lcdd), m_volManager(vm) {} + Populator(LCDD& lcdd, VolumeManager vm) + : m_lcdd(lcdd), m_volManager(vm) { + } /// Populate the Volume manager - void populate(DetElement e) { + void populate(DetElement e) { const DetElement::Children& c = e.children(); - for(DetElement::Children::const_iterator i=c.begin(); i!=c.end(); ++i) { - DetElement de = (*i).second; - PlacedVolume pv = de.placement(); - if ( pv.isValid() ) { - Chain chain; - SensitiveDetector sd; - PlacedVolume::VolIDs ids; - m_entries.clear(); - scanPhysicalVolume(de, de, pv, ids, sd, chain); - continue; - } - printout(WARNING,"VolumeManager","++ Detector element %s of type %s has no placement.", - de.name(),de.type().c_str()); + for (DetElement::Children::const_iterator i = c.begin(); i != c.end(); ++i) { + DetElement de = (*i).second; + PlacedVolume pv = de.placement(); + if (pv.isValid()) { + Chain chain; + SensitiveDetector sd; + PlacedVolume::VolIDs ids; + m_entries.clear(); + scanPhysicalVolume(de, de, pv, ids, sd, chain); + continue; + } + printout(WARNING, "VolumeManager", "++ Detector element %s of type %s has no placement.", de.name(), de.type().c_str()); } } /// Find a detector element below with the corresponding placement - DetElement findElt(DetElement e, PlacedVolume pv) { + DetElement findElt(DetElement e, PlacedVolume pv) { const DetElement::Children& c = e.children(); - if ( e.placement().ptr() == pv.ptr() ) return e; - for(DetElement::Children::const_iterator i=c.begin(); i!=c.end(); ++i) { - DetElement de = (*i).second; - if ( de.placement().ptr() == pv.ptr() ) return de; + if (e.placement().ptr() == pv.ptr()) + return e; + for (DetElement::Children::const_iterator i = c.begin(); i != c.end(); ++i) { + DetElement de = (*i).second; + if (de.placement().ptr() == pv.ptr()) + return de; } - for(DetElement::Children::const_iterator i=c.begin(); i!=c.end(); ++i) { - DetElement de = findElt((*i).second,pv); - if ( de.isValid() ) return de; + for (DetElement::Children::const_iterator i = c.begin(); i != c.end(); ++i) { + DetElement de = findElt((*i).second, pv); + if (de.isValid()) + return de; } return DetElement(); } /// Scan a single physical volume and look for sensitive elements below - size_t scanPhysicalVolume(DetElement parent, DetElement e, PlacedVolume pv, - PlacedVolume::VolIDs ids, SensitiveDetector& sd, Chain& chain) - { + size_t scanPhysicalVolume(DetElement parent, DetElement e, PlacedVolume pv, PlacedVolume::VolIDs ids, SensitiveDetector& sd, + Chain& chain) { const TGeoNode* node = pv.ptr(); size_t count = 0; - if ( node ) { - Volume vol = pv.volume(); - chain.push_back(node); - PlacedVolume::VolIDs pv_ids = pv.volIDs(); - ids.PlacedVolume::VolIDs::Base::insert(ids.end(),pv_ids.begin(),pv_ids.end()); - if ( vol.isSensitive() ) { - sd = vol.sensitiveDetector(); - Readout ro = sd.readout(); - if ( ro.isValid() ) { - add_entry(sd, parent, e, node, ids, chain); - ++count; - } - else { - printout(WARNING,"VolumeManager", - "%s: Strange constellation volume %s is sensitive, but has no readout! sd:%p", - parent.name(), pv.volume().name(), sd.ptr()); - } - } - for(Int_t idau=0, ndau=node->GetNdaughters(); idau<ndau; ++idau) { - TGeoNode* daughter = node->GetDaughter(idau); - if ( dynamic_cast<const PlacedVolume::Object*>(daughter) ) { - size_t cnt; - PlacedVolume pv_dau = Ref_t(daughter); - DetElement de_dau = findElt(e,daughter); - if ( de_dau.isValid() ) { - Chain dau_chain; - cnt = scanPhysicalVolume(parent, de_dau, pv_dau, ids, sd, dau_chain); - } - else { - cnt = scanPhysicalVolume(parent, e, pv_dau, ids, sd, chain); - } - if ( count == 0 && cnt>0 && !pv_ids.empty() ) { - add_entry(sd, parent, e, node, ids, chain); - } - count += cnt; - } - } - chain.pop_back(); + if (node) { + Volume vol = pv.volume(); + chain.push_back(node); + PlacedVolume::VolIDs pv_ids = pv.volIDs(); + ids.PlacedVolume::VolIDs::Base::insert(ids.end(), pv_ids.begin(), pv_ids.end()); + if (vol.isSensitive()) { + sd = vol.sensitiveDetector(); + Readout ro = sd.readout(); + if (ro.isValid()) { + add_entry(sd, parent, e, node, ids, chain); + ++count; + } + else { + printout(WARNING, "VolumeManager", "%s: Strange constellation volume %s is sensitive, but has no readout! sd:%p", + parent.name(), pv.volume().name(), sd.ptr()); + } + } + for (Int_t idau = 0, ndau = node->GetNdaughters(); idau < ndau; ++idau) { + TGeoNode* daughter = node->GetDaughter(idau); + if (dynamic_cast<const PlacedVolume::Object*>(daughter)) { + size_t cnt; + PlacedVolume pv_dau = Ref_t(daughter); + DetElement de_dau = findElt(e, daughter); + if (de_dau.isValid()) { + Chain dau_chain; + cnt = scanPhysicalVolume(parent, de_dau, pv_dau, ids, sd, dau_chain); + } + else { + cnt = scanPhysicalVolume(parent, e, pv_dau, ids, sd, chain); + } + if (count == 0 && cnt > 0 && !pv_ids.empty()) { + add_entry(sd, parent, e, node, ids, chain); + } + count += cnt; + } + } + chain.pop_back(); } return count; } - pair<VolumeID,VolumeID> encoding(const IDDescriptor iddesc, const PlacedVolume::VolIDs& ids ) const { + pair<VolumeID, VolumeID> encoding(const IDDescriptor iddesc, const PlacedVolume::VolIDs& ids) const { //VolumeID volume_id = ~0x0ULL, mask = 0; VolumeID volume_id = 0, mask = 0; - for(PlacedVolume::VolIDs::const_iterator i=ids.begin(); i!=ids.end(); ++i) { - const PlacedVolume::VolID& id = (*i); - IDDescriptor::Field f = iddesc.field(id.first); - VolumeID msk = f->mask(); - int offset = f->offset(); - // This pads the unused bits with '1' instead of '0': - // volume_id &= ~msk; - volume_id |= f->value(id.second<<offset)<<offset; - mask |= msk; - //volume_id &= f.encode(id.second); - //mask |= f.mask; + for (PlacedVolume::VolIDs::const_iterator i = ids.begin(); i != ids.end(); ++i) { + const PlacedVolume::VolID& id = (*i); + IDDescriptor::Field f = iddesc.field(id.first); + VolumeID msk = f->mask(); + int offset = f->offset(); + // This pads the unused bits with '1' instead of '0': + // volume_id &= ~msk; + volume_id |= f->value(id.second << offset) << offset; + mask |= msk; + //volume_id &= f.encode(id.second); + //mask |= f.mask; } - return make_pair(volume_id,mask); + return make_pair(volume_id, mask); } - void add_entry(SensitiveDetector sd, - DetElement parent, DetElement e,const TGeoNode* n, - const PlacedVolume::VolIDs& ids, const Chain& nodes) - { - Readout ro = sd.readout(); - IDDescriptor iddesc = ro.idSpec(); - VolumeManager section = m_volManager.addSubdetector(parent,ro); - pair<VolumeID,VolumeID> code = encoding(iddesc, ids); - - if ( m_entries.find(code.first) == m_entries.end() ) { - // This is the block, we effectively have to save for each physical volume with a VolID - VolumeManager::Context* context = new VolumeManager::Context; - DetElement::Object& o = parent._data(); - context->identifier = code.first; - context->mask = code.second; - context->detector = parent; - context->element = e; - context->placement = Ref_t(n); - context->volID = ids; - context->path = nodes; - for(size_t i=nodes.size(); i>1; --i) { // Omit the placement of the parent DetElement - TGeoMatrix* m = nodes[i-1]->GetMatrix(); - context->toWorld.MultiplyLeft(m); - } - context->toDetector = context->toWorld; - context->toDetector.MultiplyLeft(nodes[0]->GetMatrix()); - context->toWorld.MultiplyLeft(o.worldTransformation()); - //if ( parent.id() == 8 ) print_node(sd,parent,e,n,ids,nodes); - if ( !section.adoptPlacement(context) ) { - print_node(sd,parent,e,n,ids,nodes); - } - m_entries.insert(code.first); + void add_entry(SensitiveDetector sd, DetElement parent, DetElement e, const TGeoNode* n, const PlacedVolume::VolIDs& ids, + const Chain& nodes) { + Readout ro = sd.readout(); + IDDescriptor iddesc = ro.idSpec(); + VolumeManager section = m_volManager.addSubdetector(parent, ro); + pair<VolumeID, VolumeID> code = encoding(iddesc, ids); + + if (m_entries.find(code.first) == m_entries.end()) { + // This is the block, we effectively have to save for each physical volume with a VolID + VolumeManager::Context* context = new VolumeManager::Context; + DetElement::Object& o = parent._data(); + context->identifier = code.first; + context->mask = code.second; + context->detector = parent; + context->element = e; + context->placement = Ref_t(n); + context->volID = ids; + context->path = nodes; + for (size_t i = nodes.size(); i > 1; --i) { // Omit the placement of the parent DetElement + TGeoMatrix* m = nodes[i - 1]->GetMatrix(); + context->toWorld.MultiplyLeft(m); + } + context->toDetector = context->toWorld; + context->toDetector.MultiplyLeft(nodes[0]->GetMatrix()); + context->toWorld.MultiplyLeft(o.worldTransformation()); + //if ( parent.id() == 8 ) print_node(sd,parent,e,n,ids,nodes); + if (!section.adoptPlacement(context)) { + print_node(sd, parent, e, n, ids, nodes); + } + m_entries.insert(code.first); } } #if 0 - void add_entry(DetElement parent, DetElement e,const TGeoNode* n, - const PlacedVolume::VolIDs& ids, const Chain& nodes) + void add_entry(DetElement parent, DetElement e,const TGeoNode* n, + const PlacedVolume::VolIDs& ids, const Chain& nodes) { - Volume vol = PlacedVolume(n).volume(); - SensitiveDetector sd = vol.sensitiveDetector(); + Volume vol = PlacedVolume(n).volume(); + SensitiveDetector sd = vol.sensitiveDetector(); add_entry(sd, parent,e,n,ids,nodes); } - void find_entry(DetElement parent, DetElement e,const TGeoNode* n, - const PlacedVolume::VolIDs& ids, const Chain& nodes) + void find_entry(DetElement parent, DetElement e,const TGeoNode* n, + const PlacedVolume::VolIDs& ids, const Chain& nodes) { - Volume vol = PlacedVolume(n).volume(); - SensitiveDetector sd = vol.sensitiveDetector(); - Readout ro = sd.readout(); - IDDescriptor iddesc = ro.idSpec(); + Volume vol = PlacedVolume(n).volume(); + SensitiveDetector sd = vol.sensitiveDetector(); + Readout ro = sd.readout(); + IDDescriptor iddesc = ro.idSpec(); pair<VolumeID,VolumeID> code = encoding(iddesc, ids); #if 0 - VolumeID id = (VolumeID(rand())<<32) + VolumeID(rand()); + VolumeID id = (VolumeID(rand())<<32) + VolumeID(rand()); id &= ~code.second; - id |= code.second; + id |= code.second; VolumeID volID = id&code.first; #else VolumeID volID = code.first; @@ -197,71 +197,69 @@ namespace { VolumeManager::Context* context = m_volManager.lookupContext(volID); stringstream log; - if ( !context ) { - log << "CANNOT FIND volume:" - << " Ptr:" << (void*)n - << " [" << n->GetName() << "]" - << " ID:" << (void*)volID - << " Mask:" << (void*)code.second; - printout(ERROR,"VolumeManager",log.str().c_str()); - return; + if ( !context ) { + log << "CANNOT FIND volume:" + << " Ptr:" << (void*)n + << " [" << n->GetName() << "]" + << " ID:" << (void*)volID + << " Mask:" << (void*)code.second; + printout(ERROR,"VolumeManager",log.str().c_str()); + return; } - else if ( context->placement.ptr() != n ) { - log << "FOUND WRONG volume:" - << " Ptr:" << (void*)context->placement.ptr() - << " instead of " << (void*)n - << " [" << context->placement.name() - << " instead of " << n->GetName() << "]" - << " ID:" << (void*)context->identifier - << " instead of " << (void*)volID; - printout(ERROR,"VolumeManager",log.str().c_str()); - return; + else if ( context->placement.ptr() != n ) { + log << "FOUND WRONG volume:" + << " Ptr:" << (void*)context->placement.ptr() + << " instead of " << (void*)n + << " [" << context->placement.name() + << " instead of " << n->GetName() << "]" + << " ID:" << (void*)context->identifier + << " instead of " << (void*)volID; + printout(ERROR,"VolumeManager",log.str().c_str()); + return; } - log << "Found volume:" - << " Ptr:" << (void*)context->placement.ptr() - << " [" << context->placement.name() << "]" - << " ID:" << (void*)context->identifier - << " Mask:" << (void*)context->mask; + log << "Found volume:" + << " Ptr:" << (void*)context->placement.ptr() + << " [" << context->placement.name() << "]" + << " ID:" << (void*)context->identifier + << " Mask:" << (void*)context->mask; printout(DEBUG,"VolumeManager",log.str().c_str()); } - void print_node(DetElement parent, DetElement e, const TGeoNode* n, - const PlacedVolume::VolIDs& ids, const Chain& nodes) + void print_node(DetElement parent, DetElement e, const TGeoNode* n, + const PlacedVolume::VolIDs& ids, const Chain& nodes) { - Volume vol = PlacedVolume(n).volume(); - SensitiveDetector sd = vol.sensitiveDetector(); + Volume vol = PlacedVolume(n).volume(); + SensitiveDetector sd = vol.sensitiveDetector(); print_node(sd, parent, e, n, ids, nodes); } #endif - void print_node(SensitiveDetector sd, DetElement parent, DetElement e, const TGeoNode* n, - const PlacedVolume::VolIDs& ids, const Chain& nodes) - { + void print_node(SensitiveDetector sd, DetElement parent, DetElement e, const TGeoNode* n, const PlacedVolume::VolIDs& ids, + const Chain& nodes) { static int s_count = 0; - Readout ro = sd.readout(); + Readout ro = sd.readout(); const IDDescriptor& en = ro.idSpec(); - PlacedVolume pv = Ref_t(n); - bool sensitive = pv.volume().isSensitive(); - pair<VolumeID,VolumeID> code = encoding(en, ids); + PlacedVolume pv = Ref_t(n); + bool sensitive = pv.volume().isSensitive(); + pair<VolumeID, VolumeID> code = encoding(en, ids); VolumeID volume_id = code.first; //if ( !sensitive ) return; ++s_count; stringstream log; - log << s_count << ": " << e.name() << " de:" << e.ptr() << " ro:" << ro.ptr() - << " pv:" << n->GetName() << " id:" << (void*)volume_id << " : "; - for(PlacedVolume::VolIDs::const_iterator i=ids.begin(); i!=ids.end(); ++i) { - const PlacedVolume::VolID& id = (*i); - IDDescriptor::Field f = ro.idSpec().field(id.first); - VolumeID value = f->value(volume_id); - log << id.first << "=" << id.second << "," << value - << " [" << f->offset() << "," << f->width() << "] "; + log << s_count << ": " << e.name() << " de:" << e.ptr() << " ro:" << ro.ptr() << " pv:" << n->GetName() << " id:" + << (void*) volume_id << " : "; + for (PlacedVolume::VolIDs::const_iterator i = ids.begin(); i != ids.end(); ++i) { + const PlacedVolume::VolID& id = (*i); + IDDescriptor::Field f = ro.idSpec().field(id.first); + VolumeID value = f->value(volume_id); + log << id.first << "=" << id.second << "," << value << " [" << f->offset() << "," << f->width() << "] "; } log << " Sensitive:" << (sensitive ? "YES" : "NO"); - printout(INFO,"VolumeManager",log.str().c_str()); + printout(INFO, "VolumeManager", log.str().c_str()); #if 0 log.str(""); log << s_count << ": " << e.name() << " Detector GeoNodes:"; for(vector<const TGeoNode*>::const_iterator j=nodes.begin(); j!=nodes.end();++j) - log << (void*)(*j) << " "; + log << (void*)(*j) << " "; printout(INFO,"VolumeManager",log.str().c_str()); #endif } @@ -269,41 +267,41 @@ namespace { } /// Default constructor -VolumeManager::Context::Context() : identifier(0), mask(~0x0ULL) { +VolumeManager::Context::Context() + : identifier(0), mask(~0x0ULL) { } /// Default destructor -VolumeManager::Context::~Context() { +VolumeManager::Context::~Context() { } /// Default constructor -VolumeManager::Object::Object(LCDD& l) -: lcdd(l), top(0), sysID(0), detMask(~0x0ULL), flags(VolumeManager::NONE) -{ +VolumeManager::Object::Object(LCDD& l) + : lcdd(l), top(0), sysID(0), detMask(~0x0ULL), flags(VolumeManager::NONE) { } /// Default destructor -VolumeManager::Object::~Object() { - Object* obj = dynamic_cast<Object*>(top); - bool isTop = obj == this; - bool hasTop = (flags&VolumeManager::ONE)==VolumeManager::ONE; - bool isSdet = (flags&VolumeManager::TREE)==VolumeManager::TREE && obj != this; +VolumeManager::Object::~Object() { + Object* obj = dynamic_cast<Object*>(top); + bool isTop = obj == this; + bool hasTop = (flags & VolumeManager::ONE) == VolumeManager::ONE; + bool isSdet = (flags & VolumeManager::TREE) == VolumeManager::TREE && obj != this; /// Cleanup volume tree - for_each(volumes.begin(),volumes.end(),destroyObjects(volumes)); + for_each(volumes.begin(), volumes.end(), destroyObjects(volumes)); volumes.clear(); /// Cleanup dependent managers - for_each(managers.begin(),managers.end(),destroyHandles(managers)); + for_each(managers.begin(), managers.end(), destroyHandles(managers)); managers.clear(); subdetectors.clear(); } /// Search the locally cached volumes for a matching ID -VolumeManager::Context* VolumeManager::Object::search(const VolIdentifier& id) const { +VolumeManager::Context* VolumeManager::Object::search(const VolIdentifier& id) const { Context* context = 0; VolIdentifier volume_id(id); volume_id &= detMask; Volumes::const_iterator i = volumes.find(volume_id); - if ( i != volumes.end() ) + if (i != volumes.end()) context = (*i).second; //else if ( sysID == 8 ) { // for(i=volumes.begin(); i!=volumes.end();++i) @@ -313,84 +311,83 @@ VolumeManager::Context* VolumeManager::Object::search(const VolIdentifier& id) } /// Search the locally cached volumes for a matching physical volume -VolumeManager::Context* VolumeManager::Object::search(const PlacedVolume pv) const { +VolumeManager::Context* VolumeManager::Object::search(const PlacedVolume pv) const { PhysVolumes::const_iterator i = phys_volumes.find(pv.ptr()); - if ( i != phys_volumes.end() ) + if (i != phys_volumes.end()) return (*i).second; return 0; } /// Initializing constructor to create a new object -VolumeManager::VolumeManager(LCDD& lcdd, const string& nam, DetElement elt, Readout ro, int flags) -{ +VolumeManager::VolumeManager(LCDD& lcdd, const string& nam, DetElement elt, Readout ro, int flags) { Object* ptr = new Object(lcdd); - assign(ptr,nam,"VolumeManager"); - if ( elt.isValid() ) { + assign(ptr, nam, "VolumeManager"); + if (elt.isValid()) { Populator p(lcdd, *this); setDetector(elt, ro); - ptr->top = ptr; + ptr->top = ptr; ptr->flags = flags; p.populate(elt); } } /// Add a new Volume manager section according to a new subdetector -VolumeManager VolumeManager::addSubdetector(DetElement detector, Readout ro) { - if ( isValid() ) { +VolumeManager VolumeManager::addSubdetector(DetElement detector, Readout ro) { + if (isValid()) { Object& o = _data(); - Detectors::const_iterator i=o.subdetectors.find(detector); - if ( i == o.subdetectors.end() ) { + Detectors::const_iterator i = o.subdetectors.find(detector); + if (i == o.subdetectors.end()) { string det_name = detector.name(); // First check all pre-conditions - if ( !ro.isValid() ) { - throw runtime_error("DD4hep: VolumeManager::addSubdetector: Only subdetectors with a " - "valid readout descriptor are allowed. [Invalid DetElement:"+det_name+"]"); + if (!ro.isValid()) { + throw runtime_error("DD4hep: VolumeManager::addSubdetector: Only subdetectors with a " + "valid readout descriptor are allowed. [Invalid DetElement:" + det_name + "]"); } PlacedVolume pv = detector.placement(); - if ( !pv.isValid() ) { - throw runtime_error("DD4hep: VolumeManager::addSubdetector: Only subdetectors with a " - "valid placement are allowed. [Invalid DetElement:"+det_name+"]"); + if (!pv.isValid()) { + throw runtime_error("DD4hep: VolumeManager::addSubdetector: Only subdetectors with a " + "valid placement are allowed. [Invalid DetElement:" + det_name + "]"); } PlacedVolume::VolIDs::Base::const_iterator vit = pv.volIDs().find("system"); - if ( vit == pv.volIDs().end() ) { - throw runtime_error("DD4hep: VolumeManager::addSubdetector: Only subdetectors with " - "valid placement VolIDs are allowed. [Invalid DetElement:"+det_name+"]"); + if (vit == pv.volIDs().end()) { + throw runtime_error("DD4hep: VolumeManager::addSubdetector: Only subdetectors with " + "valid placement VolIDs are allowed. [Invalid DetElement:" + det_name + "]"); } - i = o.subdetectors.insert(make_pair(detector,VolumeManager(o.lcdd,detector.name()))).first; + i = o.subdetectors.insert(make_pair(detector, VolumeManager(o.lcdd, detector.name()))).first; const PlacedVolume::VolID& id = (*vit); VolumeManager m = (*i).second; IDDescriptor::Field field = ro.idSpec().field(id.first); - if ( !field ) { - throw runtime_error("DD4hep: VolumeManager::addSubdetector: IdDescriptor of "+ - string(detector.name())+" has no field "+id.first); + if (!field) { + throw runtime_error( + "DD4hep: VolumeManager::addSubdetector: IdDescriptor of " + string(detector.name()) + " has no field " + id.first); } Object& mo = m._data(); - m.setDetector(detector,ro); - mo.top = o.top; - mo.flags = o.flags; - mo.system = field; - mo.sysID = id.second; + m.setDetector(detector, ro); + mo.top = o.top; + mo.flags = o.flags; + mo.system = field; + mo.sysID = id.second; mo.detMask = mo.sysID; o.managers[mo.sysID] = m; } return (*i).second; } throw runtime_error("DD4hep: VolumeManager::addSubdetector: " - "Failed to add subdetector section. [Invalid Manager Handle]"); + "Failed to add subdetector section. [Invalid Manager Handle]"); } /// Access the volume manager by cell id -VolumeManager VolumeManager::subdetector(VolumeID id) const { - if ( isValid() ) { - const Object& o = _data(); +VolumeManager VolumeManager::subdetector(VolumeID id) const { + if (isValid()) { + const Object& o = _data(); /// Need to perform a linear search, because the "system" tag width may vary between subdetectors - for(Detectors::const_iterator j=o.subdetectors.begin(); j != o.subdetectors.end(); ++j) { + for (Detectors::const_iterator j = o.subdetectors.begin(); j != o.subdetectors.end(); ++j) { const Object& mo = (*j).second._data(); //VolumeID sys_id = mo.system.decode(id); - VolumeID sys_id = mo.system->value(id<<mo.system->offset()); - if ( sys_id == mo.sysID ) - return (*j).second; + VolumeID sys_id = mo.system->value(id << mo.system->offset()); + if (sys_id == mo.sysID) + return (*j).second; } throw runtime_error("DD4hep: VolumeManager::subdetector(VolID): Attempt to access unknown subdetector section."); } @@ -398,11 +395,11 @@ VolumeManager VolumeManager::subdetector(VolumeID id) const { } /// Assign the top level detector element to this manager -void VolumeManager::setDetector(DetElement e, Readout ro) { - if ( isValid() ) { - if ( e.isValid() ) { - Object& o = _data(); - o.id = ro.isValid() ? ro.idSpec() : IDDescriptor(); +void VolumeManager::setDetector(DetElement e, Readout ro) { + if (isValid()) { + if (e.isValid()) { + Object& o = _data(); + o.id = ro.isValid() ? ro.idSpec() : IDDescriptor(); o.detector = e; return; } @@ -412,17 +409,17 @@ void VolumeManager::setDetector(DetElement e, Readout ro) { } /// Access the top level detector element -DetElement VolumeManager::detector() const { - if ( isValid() ) { +DetElement VolumeManager::detector() const { + if (isValid()) { return _data().detector; } throw runtime_error("DD4hep: VolumeManager::detector: Cannot access DetElement [Invalid Handle]"); } /// Assign IDDescription to VolumeManager structure -void VolumeManager::setIDDescriptor(IDDescriptor new_descriptor) const { - if ( isValid() ) { - if ( new_descriptor.isValid() ) { // Do NOT delete! +void VolumeManager::setIDDescriptor(IDDescriptor new_descriptor) const { + if (isValid()) { + if (new_descriptor.isValid()) { // Do NOT delete! _data().id = new_descriptor; return; } @@ -431,83 +428,77 @@ void VolumeManager::setIDDescriptor(IDDescriptor new_descriptor) const { } /// Access IDDescription structure -IDDescriptor VolumeManager::idSpec() const { +IDDescriptor VolumeManager::idSpec() const { return _data().id; } /// Register physical volume with the manager (normally: section manager) -bool VolumeManager::adoptPlacement(VolumeID sys_id, Context* context) { +bool VolumeManager::adoptPlacement(VolumeID sys_id, Context* context) { stringstream err; - Object& o = _data(); + Object& o = _data(); PlacedVolume pv = context->placement; VolIdentifier vid(VOLUME_IDENTIFIER(context->identifier,context->mask)); Volumes::iterator i = o.volumes.find(vid); #if 0 - if ( (context->identifier&context->mask) != context->identifier ) { + if ( (context->identifier&context->mask) != context->identifier ) { err << "Bad context mask:" << (void*)context->mask << " id:" << (void*)context->identifier - << " pv:" << pv.name() << " Sensitive:" - << (pv.volume().isSensitive() ? "YES" : "NO") << endl; + << " pv:" << pv.name() << " Sensitive:" + << (pv.volume().isSensitive() ? "YES" : "NO") << endl; goto Fail; } #endif - if ( i == o.volumes.end() ) { + if (i == o.volumes.end()) { o.volumes[vid] = context; o.detMask |= context->mask; //o.phys_volumes[pv.ptr()] = context; - err << "Inserted new volume:" << setw(6) << left << o.volumes.size() - << " Ptr:" << (void*)context->placement.ptr() - << " [" << context->placement.name() << "]" - << " ID:" << (void*)context->identifier - << " Mask:" << (void*)context->mask; - printout(DEBUG,"VolumeManager",err.str().c_str()); + err << "Inserted new volume:" << setw(6) << left << o.volumes.size() << " Ptr:" << (void*) context->placement.ptr() << " [" + << context->placement.name() << "]" << " ID:" << (void*) context->identifier << " Mask:" << (void*) context->mask; + printout(DEBUG, "VolumeManager", err.str().c_str()); return true; } - err << "Attempt to register twice volume with identical volID " - << (void*)context->identifier << " Mask:" << (void*)context->mask - << " to detector " << o.detector.name() - << " ptr:" << (void*)pv.ptr() << " -- " << (*i).second->placement.ptr() - << " pv:" << pv.name() << " clashes with " << (*i).second->placement.name() + err << "Attempt to register twice volume with identical volID " << (void*) context->identifier << " Mask:" + << (void*) context->mask << " to detector " << o.detector.name() << " ptr:" << (void*) pv.ptr() << " -- " + << (*i).second->placement.ptr() << " pv:" << pv.name() << " clashes with " << (*i).second->placement.name() << " Sensitive:" << (pv.volume().isSensitive() ? "YES" : "NO") << endl; goto Fail; - Fail: - { + Fail: { err << "++++ VolIDS:"; const PlacedVolume::VolIDs::Base& ids = context->volID; - for(PlacedVolume::VolIDs::Base::const_iterator vit = ids.begin(); vit != ids.end(); ++vit) + for (PlacedVolume::VolIDs::Base::const_iterator vit = ids.begin(); vit != ids.end(); ++vit) err << (*vit).first << "=" << (*vit).second << "; "; } - printout(ERROR,"VolumeManager","++++[!!!] adoptPlacement: %s",err.str().c_str()); + printout(ERROR, "VolumeManager", "++++[!!!] adoptPlacement: %s", err.str().c_str()); // throw runtime_error(err.str()); return false; } /// Register physical volume with the manager (normally: section manager) -bool VolumeManager::adoptPlacement(Context* context) { +bool VolumeManager::adoptPlacement(Context* context) { stringstream err; - if ( isValid() ) { + if (isValid()) { Object& o = _data(); - if ( context ) { - if ( (o.flags&ONE) == ONE ) { - VolumeManager top(Ref_t(o.top)); - return top.adoptPlacement(context); + if (context) { + if ((o.flags & ONE) == ONE) { + VolumeManager top(Ref_t(o.top)); + return top.adoptPlacement(context); } - if ( (o.flags&TREE) == TREE ) { - bool isTop = ptr() == o.top; - if ( !isTop ) { - VolumeID sys_id = o.system->value(context->identifier); - if ( sys_id == o.sysID ) { - return adoptPlacement(sys_id,context); - } - VolumeManager top(Ref_t(o.top)); - return top.adoptPlacement(context); - } - for(Managers::iterator j=o.managers.begin(); j != o.managers.end(); ++j) { - Object& m = (*j).second._data(); - VolumeID sid = m.system->value(context->identifier); - if ( (*j).first == sid ) { - return (*j).second.adoptPlacement(sid,context); - } - } + if ((o.flags & TREE) == TREE) { + bool isTop = ptr() == o.top; + if (!isTop) { + VolumeID sys_id = o.system->value(context->identifier); + if (sys_id == o.sysID) { + return adoptPlacement(sys_id, context); + } + VolumeManager top(Ref_t(o.top)); + return top.adoptPlacement(context); + } + for (Managers::iterator j = o.managers.begin(); j != o.managers.end(); ++j) { + Object& m = (*j).second._data(); + VolumeID sid = m.system->value(context->identifier); + if ((*j).first == sid) { + return (*j).second.adoptPlacement(sid, context); + } + } } return false; } @@ -516,131 +507,123 @@ bool VolumeManager::adoptPlacement(Context* context) { } err << "Failed to add new physical volume [Invalid Manager Handle]"; goto Fail; - Fail: - throw runtime_error("DD4hep: "+err.str()); + Fail: throw runtime_error("DD4hep: " + err.str()); return false; } /// Lookup the context, which belongs to a registered physical volume. -VolumeManager::Context* VolumeManager::lookupContext(VolumeID volume_id) const { - if ( isValid() ) { +VolumeManager::Context* VolumeManager::lookupContext(VolumeID volume_id) const { + if (isValid()) { Context* c = 0; const Object& o = _data(); bool is_top = o.top == ptr(); - bool one_tree = (o.flags&ONE) == ONE; - if ( !is_top && one_tree ) { + bool one_tree = (o.flags & ONE) == ONE; + if (!is_top && one_tree) { return VolumeManager(Ref_t(o.top)).lookupContext(volume_id); } VolIdentifier id(VOLUME_IDENTIFIER(volume_id,~0x0ULL)); /// First look in our own volume cache if the entry is found. c = o.search(id); - if ( c ) return c; + if (c) + return c; /// Second: look in the subdetector volume cache if the entry is found. - if ( !one_tree ) { - for(Detectors::const_iterator j=o.subdetectors.begin(); j != o.subdetectors.end(); ++j) { - if ( (c=(*j).second._data().search(id)) != 0 ) - return c; + if (!one_tree) { + for (Detectors::const_iterator j = o.subdetectors.begin(); j != o.subdetectors.end(); ++j) { + if ((c = (*j).second._data().search(id)) != 0) + return c; } } stringstream err; - err << "VolumeManager::lookupContext: Failed to search Volume context [Unknown identifier]" - << (void*)volume_id; - throw runtime_error("DD4hep: "+err.str()); + err << "VolumeManager::lookupContext: Failed to search Volume context [Unknown identifier]" << (void*) volume_id; + throw runtime_error("DD4hep: " + err.str()); } throw runtime_error("DD4hep: VolumeManager::lookupContext: Failed to search Volume context [Invalid Manager Handle]"); } /// Lookup a physical (placed) volume identified by its 64 bit hit ID -PlacedVolume VolumeManager::lookupPlacement(VolumeID volume_id) const { +PlacedVolume VolumeManager::lookupPlacement(VolumeID volume_id) const { Context* c = lookupContext(volume_id); return c->placement; } /// Lookup a top level subdetector detector element according to a contained 64 bit hit ID -DetElement VolumeManager::lookupDetector(VolumeID volume_id) const { +DetElement VolumeManager::lookupDetector(VolumeID volume_id) const { Context* c = lookupContext(volume_id); return c->detector; } /// Lookup the closest subdetector detector element in the hierarchy according to a contained 64 bit hit ID -DetElement VolumeManager::lookupDetElement(VolumeID volume_id) const { +DetElement VolumeManager::lookupDetElement(VolumeID volume_id) const { Context* c = lookupContext(volume_id); return c->element; } /// Access the transformation of a physical volume to the world coordinate system -const TGeoMatrix& VolumeManager::worldTransformation(VolumeID volume_id) const { +const TGeoMatrix& VolumeManager::worldTransformation(VolumeID volume_id) const { Context* c = lookupContext(volume_id); return c->toWorld; } /// Enable printouts for debugging -std::ostream& DD4hep::Geometry::operator<<(std::ostream& os, const VolumeManager& m) { +std::ostream& DD4hep::Geometry::operator<<(std::ostream& os, const VolumeManager& m) { const VolumeManager::Object& o = *m.data<VolumeManager::Object>(); - VolumeManager::Object* top = dynamic_cast<VolumeManager::Object*>(o.top); - bool isTop = top == &o; - bool hasTop = (o.flags&VolumeManager::ONE)==VolumeManager::ONE; - bool isSdet = (o.flags&VolumeManager::TREE)==VolumeManager::TREE && top != &o; + VolumeManager::Object* top = dynamic_cast<VolumeManager::Object*>(o.top); + bool isTop = top == &o; + bool hasTop = (o.flags & VolumeManager::ONE) == VolumeManager::ONE; + bool isSdet = (o.flags & VolumeManager::TREE) == VolumeManager::TREE && top != &o; string prefix(isTop ? "" : "++ "); - os << prefix - << (isTop ? "TOP Level " : "Secondary ") - << "Volume manager:" << &o << " " << o.detector.name() - << " IDD:" << o.id.toString() - << " SysID:" << (void*)o.sysID << " " - << o.managers.size() << " subsections " - << o.volumes.size() << " placements "; - if ( !(o.managers.empty() && o.volumes.empty()) ) os << endl; - for(VolumeManager::Volumes::const_iterator i = o.volumes.begin(); i!=o.volumes.end(); ++i) { + os << prefix << (isTop ? "TOP Level " : "Secondary ") << "Volume manager:" << &o << " " << o.detector.name() << " IDD:" + << o.id.toString() << " SysID:" << (void*) o.sysID << " " << o.managers.size() << " subsections " << o.volumes.size() + << " placements "; + if (!(o.managers.empty() && o.volumes.empty())) + os << endl; + for (VolumeManager::Volumes::const_iterator i = o.volumes.begin(); i != o.volumes.end(); ++i) { const VolumeManager::Context* c = (*i).second; PlacedVolume pv = c->placement; - os << prefix - << "PV:" << setw(32) << left << pv.name() - << " id:" << setw(18) << left << (void*)c->identifier - << " mask:" << setw(18) << left << (void*) c->mask << endl; + os << prefix << "PV:" << setw(32) << left << pv.name() << " id:" << setw(18) << left << (void*) c->identifier << " mask:" + << setw(18) << left << (void*) c->mask << endl; } - for(VolumeManager::Managers::const_iterator i = o.managers.begin(); i!=o.managers.end(); ++i) + for (VolumeManager::Managers::const_iterator i = o.managers.begin(); i != o.managers.end(); ++i) os << prefix << (*i).second << endl; return os; } - #if 0 - It was wishful thinking, the implementation of the reverse lookups would be as simple. - Hence the folling calls are removed for the time being. +It was wishful thinking, the implementation of the reverse lookups would be as simple. +Hence the folling calls are removed for the time being. - Markus Frank +Markus Frank - - /** This set of functions is required when reading/analyzing - * already created hits which have a VolumeID attached. - */ - /// Lookup the context, which belongs to a registered physical volume. - Context* lookupContext(PlacedVolume vol) const throw(); - /// Access the physical volume identifier from the placed volume - VolumeID lookupID(PlacedVolume vol) const; - /// Lookup a top level subdetector detector element according to a contained 64 bit hit ID - DetElement lookupDetector(PlacedVolume vol) const; - /// Lookup the closest subdetector detector element in the hierarchy according to a contained 64 bit hit ID - DetElement lookupDetElement(PlacedVolume vol) const; - /// Access the transformation of a physical volume to the world coordinate system - const TGeoMatrix& worldTransformation(PlacedVolume vol) const; +/** This set of functions is required when reading/analyzing + * already created hits which have a VolumeID attached. + */ +/// Lookup the context, which belongs to a registered physical volume. +Context* lookupContext(PlacedVolume vol) const throw(); +/// Access the physical volume identifier from the placed volume +VolumeID lookupID(PlacedVolume vol) const; +/// Lookup a top level subdetector detector element according to a contained 64 bit hit ID +DetElement lookupDetector(PlacedVolume vol) const; +/// Lookup the closest subdetector detector element in the hierarchy according to a contained 64 bit hit ID +DetElement lookupDetElement(PlacedVolume vol) const; +/// Access the transformation of a physical volume to the world coordinate system +const TGeoMatrix& worldTransformation(PlacedVolume vol) const; /// Lookup the context, which belongs to a registered physical volume. -VolumeManager::Context* VolumeManager::lookupContext(PlacedVolume pv) const throw() { - if ( isValid() ) { +VolumeManager::Context* VolumeManager::lookupContext(PlacedVolume pv) const throw() { + if ( isValid() ) { Context* c = 0; const Object& o = _data(); - if ( o.top != ptr() && (o.flags&ONE) == ONE ) { + if ( o.top != ptr() && (o.flags&ONE) == ONE ) { return VolumeManager(Ref_t(o.top)).lookupContext(pv); } /// First look in our own volume cache if the entry is found. c = o.search(pv); if ( c ) return c; /// Second: look in the subdetector volume cache if the entry is found. - for(Detectors::const_iterator j=o.subdetectors.begin(); j != o.subdetectors.end(); ++j) { + for(Detectors::const_iterator j=o.subdetectors.begin(); j != o.subdetectors.end(); ++j) { if ( (c=(*j).second._data().search(pv)) != 0 ) - return c; + return c; } throw runtime_error("VolumeManager::lookupContext: Failed to search Volume context [Unknown identifier]"); } @@ -648,25 +631,25 @@ VolumeManager::Context* VolumeManager::lookupContext(PlacedVolume pv) const thro } /// Access the physical volume identifier from the placed volume -VolumeManager::VolumeID VolumeManager::lookupID(PlacedVolume vol) const { +VolumeManager::VolumeID VolumeManager::lookupID(PlacedVolume vol) const { Context* c = lookupContext(vol); return c->identifier; } /// Lookup a top level subdetector detector element according to a contained 64 bit hit ID -DetElement VolumeManager::lookupDetector(PlacedVolume vol) const { +DetElement VolumeManager::lookupDetector(PlacedVolume vol) const { Context* c = lookupContext(vol); return c->detector; } /// Lookup the closest subdetector detector element in the hierarchy according to a contained 64 bit hit ID -DetElement VolumeManager::lookupDetElement(PlacedVolume vol) const { +DetElement VolumeManager::lookupDetElement(PlacedVolume vol) const { Context* c = lookupContext(vol); return c->element; } /// Access the transformation of a physical volume to the world coordinate system -const TGeoMatrix& VolumeManager::worldTransformation(PlacedVolume vol) const { +const TGeoMatrix& VolumeManager::worldTransformation(PlacedVolume vol) const { Context* c = lookupContext(vol); return c->toWorld; } diff --git a/DDCore/src/Volumes.cpp b/DDCore/src/Volumes.cpp index b04cfbba2..944007fe7 100644 --- a/DDCore/src/Volumes.cpp +++ b/DDCore/src/Volumes.cpp @@ -31,286 +31,306 @@ using namespace std; using namespace DD4hep::Geometry; -namespace DD4hep { namespace Geometry { - - template <> struct Value<TGeoNodeMatrix,PlacedVolume::Object> - : public TGeoNodeMatrix, public PlacedVolume::Object - { - Value(const TGeoVolume* v, const TGeoMatrix* m) : TGeoNodeMatrix(v,m), PlacedVolume::Object() { - magic = magic_word(); - InstanceCount::increment(this); - } - Value(const Value& c) : TGeoNodeMatrix(c.GetVolume(),c.GetMatrix()), PlacedVolume::Object(c) { - InstanceCount::increment(this); - } - virtual ~Value() { - InstanceCount::decrement(this); - } - virtual TGeoNode *MakeCopyNode() const { - TGeoNodeMatrix *node = new Value<TGeoNodeMatrix,PlacedVolume::Object>(*this); - node->SetName(GetName()); - // set the mother - node->SetMotherVolume(fMother); - // set the copy number - node->SetNumber(fNumber); - // copy overlaps - if (fNovlp>0) { - if (fOverlaps) { - Int_t *ovlps = new Int_t[fNovlp]; - memcpy(ovlps, fOverlaps, fNovlp*sizeof(Int_t)); - node->SetOverlaps(ovlps, fNovlp); - } else { - node->SetOverlaps(fOverlaps, fNovlp); - } +namespace DD4hep { + namespace Geometry { + + template <> struct Value<TGeoNodeMatrix, PlacedVolume::Object> : public TGeoNodeMatrix, public PlacedVolume::Object { + Value(const TGeoVolume* v, const TGeoMatrix* m) + : TGeoNodeMatrix(v, m), PlacedVolume::Object() { + magic = magic_word(); + InstanceCount::increment(this); } - // copy VC - if (IsVirtual()) node->SetVirtual(); - return node; - } - }; - - template <class T> struct _VolWrap : public T { - _VolWrap(const char* name, TGeoShape* s=0, TGeoMedium* m=0); - virtual ~_VolWrap() {} - virtual void AddNode(const TGeoVolume *vol, Int_t copy_no, TGeoMatrix *mat, Option_t* = "") { - TGeoMatrix *matrix = mat; - if ( matrix == 0 ) matrix = gGeoIdentity; - else matrix->RegisterYourself(); - if (!vol) { - this->T::Error("AddNode", "Volume is NULL"); - return; + Value(const Value& c) + : TGeoNodeMatrix(c.GetVolume(), c.GetMatrix()), PlacedVolume::Object(c) { + InstanceCount::increment(this); } - if (!vol->IsValid()) { - this->T::Error("AddNode", "Won't add node with invalid shape"); - printf("### invalid volume was : %s\n", vol->GetName()); - return; + virtual ~Value() { + InstanceCount::decrement(this); } - if ( !this->T::fNodes ) this->T::fNodes = new TObjArray(); - - if ( this->T::fFinder ) { - // volume already divided. - this->T::Error("AddNode", "Cannot add node %s_%i into divided volume %s", vol->GetName(), copy_no, this->T::GetName()); - return; + virtual TGeoNode *MakeCopyNode() const { + TGeoNodeMatrix *node = new Value<TGeoNodeMatrix, PlacedVolume::Object>(*this); + node->SetName(GetName()); + // set the mother + node->SetMotherVolume(fMother); + // set the copy number + node->SetNumber(fNumber); + // copy overlaps + if (fNovlp > 0) { + if (fOverlaps) { + Int_t *ovlps = new Int_t[fNovlp]; + memcpy(ovlps, fOverlaps, fNovlp * sizeof(Int_t)); + node->SetOverlaps(ovlps, fNovlp); + } + else { + node->SetOverlaps(fOverlaps, fNovlp); + } + } + // copy VC + if (IsVirtual()) + node->SetVirtual(); + return node; } - - TGeoNodeMatrix *node = new Value<TGeoNodeMatrix,PlacedVolume::Object>(vol, matrix); - //node = new TGeoNodeMatrix(vol, matrix); - node->SetMotherVolume(this); - this->T::fNodes->Add(node); - TString name = TString::Format("%s_%d", vol->GetName(), copy_no); - if (this->T::fNodes->FindObject(name)) - this->T::Warning("AddNode", "Volume %s : added node %s with same name", this->T::GetName(), name.Data()); - node->SetName(name); - node->SetNumber(copy_no); - } - }; - - template <> _VolWrap<TGeoVolume>::_VolWrap(const char* name, TGeoShape* s, TGeoMedium* m) - : TGeoVolume(name,s,m) {} - template <> _VolWrap<TGeoVolumeAssembly>::_VolWrap(const char* name, TGeoShape* /* s */, TGeoMedium* /* m */) - : TGeoVolumeAssembly(name) {} - - template <> struct Value<TGeoVolume,Volume::Object> - : public _VolWrap<TGeoVolume>, public Volume::Object { - Value(const char* name, TGeoShape* s=0, TGeoMedium* m=0) - : _VolWrap<TGeoVolume>(name,s,m) { - magic = magic_word(); - InstanceCount::increment(this); - } - virtual ~Value() { - InstanceCount::decrement(this); - } - TGeoVolume *_copyVol(TGeoShape *newshape) const { - typedef Value<TGeoVolume,Volume::Object> _Vol; - _Vol *vol = new _Vol(GetName(), newshape, fMedium); - vol->copy(*this); - return vol; - } - virtual TGeoVolume* MakeCopyVolume(TGeoShape *newshape) { - // make a copy of this volume. build a volume with same name, shape and medium - TGeoVolume *vol = _copyVol(newshape); - vol->SetVisibility(IsVisible()); - vol->SetLineColor(GetLineColor()); - vol->SetLineStyle(GetLineStyle()); - vol->SetLineWidth(GetLineWidth()); - vol->SetFillColor(GetFillColor()); - vol->SetFillStyle(GetFillStyle()); - vol->SetField(fField); - if (fFinder) vol->SetFinder(fFinder); - CloneNodesAndConnect(vol); - ((TObject*)vol)->SetBit(kVolumeClone); - return vol; - } - virtual TGeoVolume* CloneVolume() const { - TGeoVolume *vol = _copyVol(fShape); - Int_t i; - // copy volume attributes - vol->SetLineColor(GetLineColor()); - vol->SetLineStyle(GetLineStyle()); - vol->SetLineWidth(GetLineWidth()); - vol->SetFillColor(GetFillColor()); - vol->SetFillStyle(GetFillStyle()); - // copy other attributes - Int_t nbits = 8*sizeof(UInt_t); - for (i=0; i<nbits; i++) - vol->SetAttBit(1<<i, TGeoAtt::TestAttBit(1<<i)); - for (i=14; i<24; i++) - vol->SetBit(1<<i, TestBit(1<<i)); - - // copy field - vol->SetField(fField); - // Set bits - for (i=0; i<nbits; i++) - vol->SetBit(1<<i, TObject::TestBit(1<<i)); - vol->SetBit(kVolumeClone); - // copy nodes - // CloneNodesAndConnect(vol); - vol->MakeCopyNodes(this); - // if volume is divided, copy finder - vol->SetFinder(fFinder); - // copy voxels - TGeoVoxelFinder *voxels = 0; - if (fVoxels) { - voxels = new TGeoVoxelFinder(vol); - vol->SetVoxelFinder(voxels); - } - // copy option, uid - vol->SetOption(fOption); - vol->SetNumber(fNumber); - vol->SetNtotal(fNtotal); - return vol; - } - }; - - template <> struct Value<TGeoVolumeAssembly,Assembly::Object> - : public _VolWrap<TGeoVolumeAssembly>, public Assembly::Object { - Value(const char* name) : _VolWrap<TGeoVolumeAssembly>(name,0,0) { - magic = magic_word(); - InstanceCount::increment(this); - } - virtual ~Value() { - InstanceCount::decrement(this); + }; + + template <class T> struct _VolWrap: public T { + _VolWrap(const char* name, TGeoShape* s = 0, TGeoMedium* m = 0); + virtual ~_VolWrap() { + } + virtual void AddNode(const TGeoVolume *vol, Int_t copy_no, TGeoMatrix *mat, Option_t* = "") { + TGeoMatrix *matrix = mat; + if (matrix == 0) + matrix = gGeoIdentity; + else + matrix->RegisterYourself(); + if (!vol) { + this->T::Error("AddNode", "Volume is NULL"); + return; + } + if (!vol->IsValid()) { + this->T::Error("AddNode", "Won't add node with invalid shape"); + printf("### invalid volume was : %s\n", vol->GetName()); + return; + } + if (!this->T::fNodes) + this->T::fNodes = new TObjArray(); + + if (this->T::fFinder) { + // volume already divided. + this->T::Error("AddNode", "Cannot add node %s_%i into divided volume %s", vol->GetName(), copy_no, + this->T::GetName()); + return; + } + + TGeoNodeMatrix *node = new Value<TGeoNodeMatrix, PlacedVolume::Object>(vol, matrix); + //node = new TGeoNodeMatrix(vol, matrix); + node->SetMotherVolume(this); + this->T::fNodes->Add(node); + TString name = TString::Format("%s_%d", vol->GetName(), copy_no); + if (this->T::fNodes->FindObject(name)) + this->T::Warning("AddNode", "Volume %s : added node %s with same name", this->T::GetName(), name.Data()); + node->SetName(name); + node->SetNumber(copy_no); + } + }; + + template <> _VolWrap<TGeoVolume>::_VolWrap(const char* name, TGeoShape* s, TGeoMedium* m) + : TGeoVolume(name, s, m) { } - TGeoVolume *CloneVolume() const { - TGeoVolume *vol = new Value<TGeoVolumeAssembly,Assembly::Object>(GetName()); - Int_t i; - // copy other attributes - Int_t nbits = 8*sizeof(UInt_t); - for (i=0; i<nbits; i++) - vol->SetAttBit(1<<i, TGeoAtt::TestAttBit(1<<i)); - for (i=14; i<24; i++) - vol->SetBit(1<<i, TestBit(1<<i)); - - // copy field - vol->SetField(fField); - // Set bits - for (i=0; i<nbits; i++) - vol->SetBit(1<<i, TObject::TestBit(1<<i)); - vol->SetBit(kVolumeClone); - // make copy nodes - vol->MakeCopyNodes(this); - ((TGeoShapeAssembly*)vol->GetShape())->NeedsBBoxRecompute(); - // copy voxels - TGeoVoxelFinder *voxels = 0; - if (fVoxels) { - voxels = new TGeoVoxelFinder(vol); - vol->SetVoxelFinder(voxels); - } - // copy option, uid - vol->SetOption(fOption); - vol->SetNumber(fNumber); - vol->SetNtotal(fNtotal); - return vol; + template <> _VolWrap<TGeoVolumeAssembly>::_VolWrap(const char* name, TGeoShape* /* s */, TGeoMedium* /* m */) + : TGeoVolumeAssembly(name) { } - }; -}} + template <> struct Value<TGeoVolume, Volume::Object> : public _VolWrap<TGeoVolume>, public Volume::Object { + Value(const char* name, TGeoShape* s = 0, TGeoMedium* m = 0) + : _VolWrap<TGeoVolume>(name, s, m) { + magic = magic_word(); + InstanceCount::increment(this); + } + virtual ~Value() { + InstanceCount::decrement(this); + } + TGeoVolume *_copyVol(TGeoShape *newshape) const { + typedef Value<TGeoVolume, Volume::Object> _Vol; + _Vol *vol = new _Vol(GetName(), newshape, fMedium); + vol->copy(*this); + return vol; + } + virtual TGeoVolume* MakeCopyVolume(TGeoShape *newshape) { + // make a copy of this volume. build a volume with same name, shape and medium + TGeoVolume *vol = _copyVol(newshape); + vol->SetVisibility(IsVisible()); + vol->SetLineColor(GetLineColor()); + vol->SetLineStyle(GetLineStyle()); + vol->SetLineWidth(GetLineWidth()); + vol->SetFillColor(GetFillColor()); + vol->SetFillStyle(GetFillStyle()); + vol->SetField(fField); + if (fFinder) + vol->SetFinder(fFinder); + CloneNodesAndConnect(vol); + ((TObject*) vol)->SetBit(kVolumeClone); + return vol; + } + virtual TGeoVolume* CloneVolume() const { + TGeoVolume *vol = _copyVol(fShape); + Int_t i; + // copy volume attributes + vol->SetLineColor(GetLineColor()); + vol->SetLineStyle(GetLineStyle()); + vol->SetLineWidth(GetLineWidth()); + vol->SetFillColor(GetFillColor()); + vol->SetFillStyle(GetFillStyle()); + // copy other attributes + Int_t nbits = 8 * sizeof(UInt_t); + for (i = 0; i < nbits; i++) + vol->SetAttBit(1 << i, TGeoAtt::TestAttBit(1 << i)); + for (i = 14; i < 24; i++) + vol->SetBit(1 << i, TestBit(1 << i)); + + // copy field + vol->SetField(fField); + // Set bits + for (i = 0; i < nbits; i++) + vol->SetBit(1 << i, TObject::TestBit(1 << i)); + vol->SetBit(kVolumeClone); + // copy nodes + // CloneNodesAndConnect(vol); + vol->MakeCopyNodes(this); + // if volume is divided, copy finder + vol->SetFinder(fFinder); + // copy voxels + TGeoVoxelFinder *voxels = 0; + if (fVoxels) { + voxels = new TGeoVoxelFinder(vol); + vol->SetVoxelFinder(voxels); + } + // copy option, uid + vol->SetOption(fOption); + vol->SetNumber(fNumber); + vol->SetNtotal(fNtotal); + return vol; + } + }; + + template <> struct Value<TGeoVolumeAssembly, Assembly::Object> : public _VolWrap<TGeoVolumeAssembly>, + public Assembly::Object { + Value(const char* name) + : _VolWrap<TGeoVolumeAssembly>(name, 0, 0) { + magic = magic_word(); + InstanceCount::increment(this); + } + virtual ~Value() { + InstanceCount::decrement(this); + } + TGeoVolume *CloneVolume() const { + TGeoVolume *vol = new Value<TGeoVolumeAssembly, Assembly::Object>(GetName()); + Int_t i; + // copy other attributes + Int_t nbits = 8 * sizeof(UInt_t); + for (i = 0; i < nbits; i++) + vol->SetAttBit(1 << i, TGeoAtt::TestAttBit(1 << i)); + for (i = 14; i < 24; i++) + vol->SetBit(1 << i, TestBit(1 << i)); + + // copy field + vol->SetField(fField); + // Set bits + for (i = 0; i < nbits; i++) + vol->SetBit(1 << i, TObject::TestBit(1 << i)); + vol->SetBit(kVolumeClone); + // make copy nodes + vol->MakeCopyNodes(this); + ((TGeoShapeAssembly*) vol->GetShape())->NeedsBBoxRecompute(); + // copy voxels + TGeoVoxelFinder *voxels = 0; + if (fVoxels) { + voxels = new TGeoVoxelFinder(vol); + vol->SetVoxelFinder(voxels); + } + // copy option, uid + vol->SetOption(fOption); + vol->SetNumber(fNumber); + vol->SetNtotal(fNtotal); + return vol; + } + }; + + } +} /// Default constructor -PlacedVolume::Object::Object() : magic(0), volIDs() { +PlacedVolume::Object::Object() + : magic(0), volIDs() { InstanceCount::increment(this); } /// Copy constructor -PlacedVolume::Object::Object(const Object& c) : magic(c.magic), volIDs(c.volIDs) { +PlacedVolume::Object::Object(const Object& c) + : magic(c.magic), volIDs(c.volIDs) { InstanceCount::increment(this); } /// Default destructor -PlacedVolume::Object::~Object() { +PlacedVolume::Object::~Object() { InstanceCount::decrement(this); } /// Lookup volume ID -vector<PlacedVolume::VolID>::const_iterator -PlacedVolume::VolIDs::find(const string& name) const { - for(Base::const_iterator i=this->Base::begin(); i!=this->Base::end(); ++i) - if ( name == (*i).first ) return i; +vector<PlacedVolume::VolID>::const_iterator PlacedVolume::VolIDs::find(const string& name) const { + for (Base::const_iterator i = this->Base::begin(); i != this->Base::end(); ++i) + if (name == (*i).first) + return i; return this->end(); } /// Insert a new value into the volume ID container -std::pair<vector<PlacedVolume::VolID>::iterator,bool> -PlacedVolume::VolIDs::insert(const string& name, int value) { +std::pair<vector<PlacedVolume::VolID>::iterator, bool> PlacedVolume::VolIDs::insert(const string& name, int value) { Base::iterator i = this->Base::begin(); - for(; i!=this->Base::end(); ++i) - if ( name == (*i).first ) break; + for (; i != this->Base::end(); ++i) + if (name == (*i).first) + break; // - if ( i != this->Base::end() ) { - return make_pair(i,false); + if (i != this->Base::end()) { + return make_pair(i, false); } - i = this->Base::insert(this->Base::end(),make_pair(name,value)); - return make_pair(i,true); + i = this->Base::insert(this->Base::end(), make_pair(name, value)); + return make_pair(i, true); } -static PlacedVolume::Object* _data(const PlacedVolume& v) { - PlacedVolume::Object* o = dynamic_cast<PlacedVolume::Object*>(v.ptr()); - if ( o ) return o; - throw runtime_error("DD4hep: Attempt to access invalid handle of type: PlacedVolume"); +static PlacedVolume::Object* _data(const PlacedVolume& v) { + PlacedVolume::Object* o = dynamic_cast<PlacedVolume::Object*>(v.ptr()); + if (o) + return o; + throw runtime_error("DD4hep: Attempt to access invalid handle of type: PlacedVolume"); } /// Add identifier -PlacedVolume& PlacedVolume::addPhysVolID(const string& name, int value) { +PlacedVolume& PlacedVolume::addPhysVolID(const string& name, int value) { Object* obj = _data(*this); - obj->volIDs.push_back(VolID(name,value)); + obj->volIDs.push_back(VolID(name, value)); return *this; } /// Volume material -Material PlacedVolume::material() const -{ return Material::handle_t(m_element ? m_element->GetMedium() : 0); } +Material PlacedVolume::material() const { + return Material::handle_t(m_element ? m_element->GetMedium() : 0); +} /// Logical volume of this placement -Volume PlacedVolume::volume() const -{ return Volume::handle_t(m_element ? m_element->GetVolume() : 0); } +Volume PlacedVolume::volume() const { + return Volume::handle_t(m_element ? m_element->GetVolume() : 0); +} /// Parent volume (envelope) -Volume PlacedVolume::motherVol() const -{ return Volume::handle_t(m_element ? m_element->GetMotherVolume() : 0); } +Volume PlacedVolume::motherVol() const { + return Volume::handle_t(m_element ? m_element->GetMotherVolume() : 0); +} /// Access to the volume IDs -const PlacedVolume::VolIDs& PlacedVolume::volIDs() const -{ return _data(*this)->volIDs; } +const PlacedVolume::VolIDs& PlacedVolume::volIDs() const { + return _data(*this)->volIDs; +} /// String dump string PlacedVolume::toString() const { stringstream s; Object* obj = _data(*this); - s << m_element->GetName() << ": vol='" << m_element->GetVolume()->GetName() - << "' mat:'" << m_element->GetMatrix()->GetName() << "' volID[" << obj->volIDs.size() << "] "; - for(VolIDs::const_iterator i=obj->volIDs.begin(); i!=obj->volIDs.end();++i) + s << m_element->GetName() << ": vol='" << m_element->GetVolume()->GetName() << "' mat:'" << m_element->GetMatrix()->GetName() + << "' volID[" << obj->volIDs.size() << "] "; + for (VolIDs::const_iterator i = obj->volIDs.begin(); i != obj->volIDs.end(); ++i) s << (*i).first << "=" << (*i).second << " "; s << ends; return s.str(); } /// Default constructor -Volume::Object::Object() : magic(0), region(), limits(), vis(), sens_det(), referenced(0) { +Volume::Object::Object() + : magic(0), region(), limits(), vis(), sens_det(), referenced(0) { InstanceCount::increment(this); } /// Default destructor -Volume::Object::~Object() { +Volume::Object::~Object() { region.clear(); limits.clear(); vis.clear(); @@ -322,19 +342,21 @@ Volume::Object::~Object() { Volume::Object* _data(const Volume& v, bool throw_exception = true) { //if ( v.ptr() && v.ptr()->IsA() == TGeoVolume::Class() ) return v.data<Volume::Object>(); Volume::Object* o = dynamic_cast<Volume::Object*>(v.ptr()); - if ( o ) return o; - else if ( !throw_exception ) return 0; + if (o) + return o; + else if (!throw_exception) + return 0; throw runtime_error("DD4hep: Attempt to access invalid handle of type: PlacedVolume"); } /// Constructor to be used when creating a new geometry tree. -Volume::Volume(const string& name) { - m_element = new Value<TGeoVolume,Volume::Object>(name.c_str()); +Volume::Volume(const string& name) { + m_element = new Value<TGeoVolume, Volume::Object>(name.c_str()); } /// Constructor to be used when creating a new geometry tree. Also sets materuial and solid attributes Volume::Volume(const string& name, const Solid& s, const Material& m) { - m_element = new Value<TGeoVolume,Volume::Object>(name.c_str(),s); + m_element = new Value<TGeoVolume, Volume::Object>(name.c_str(), s); setMaterial(m); } @@ -342,101 +364,101 @@ static PlacedVolume _addNode(TGeoVolume* par, TGeoVolume* daughter, TGeoMatrix* TGeoVolume* parent = par; TObjArray* a = parent->GetNodes(); Int_t id = a ? a->GetEntries() : 0; - if ( transform && transform != identityTransform() ) { - string nam = string(daughter->GetName())+"_placement"; + if (transform && transform != identityTransform()) { + string nam = string(daughter->GetName()) + "_placement"; transform->SetName(nam.c_str()); } - parent->AddNode(daughter,id,transform); + parent->AddNode(daughter, id, transform); TGeoNode* n = parent->GetNode(id); return PlacedVolume(n); } /// Place daughter volume according to generic Transform3D -PlacedVolume Volume::placeVolume(const Volume& volume, const Transform3D& trans) const { - if ( volume.isValid() ) { - return _addNode(m_element,volume,_transform(trans)); +PlacedVolume Volume::placeVolume(const Volume& volume, const Transform3D& trans) const { + if (volume.isValid()) { + return _addNode(m_element, volume, _transform(trans)); } throw runtime_error("DD4hep: Volume: Attempt to assign an invalid physical volume."); } /// Place daughter volume. The position and rotation are the identity -PlacedVolume Volume::placeVolume(const Volume& volume) const { - if ( volume.isValid() ) { - return _addNode(m_element,volume,identityTransform()); +PlacedVolume Volume::placeVolume(const Volume& volume) const { + if (volume.isValid()) { + return _addNode(m_element, volume, identityTransform()); } throw runtime_error("DD4hep: Volume: Attempt to assign an invalid physical volume."); } /// Place un-rotated daughter volume at the given position. -PlacedVolume Volume::placeVolume(const Volume& volume, const Position& pos) const { - if ( volume.isValid() ) { - return _addNode(m_element,volume,_translation(pos)); +PlacedVolume Volume::placeVolume(const Volume& volume, const Position& pos) const { + if (volume.isValid()) { + return _addNode(m_element, volume, _translation(pos)); } throw runtime_error("DD4hep: Volume: Attempt to assign an invalid physical volume."); } /// Place rotated daughter volume. The position is automatically the identity position -PlacedVolume Volume::placeVolume(const Volume& volume, const RotationZYX& rot) const { - if ( volume.isValid() ) { - return _addNode(m_element,volume,_rotationZYX(rot)); +PlacedVolume Volume::placeVolume(const Volume& volume, const RotationZYX& rot) const { + if (volume.isValid()) { + return _addNode(m_element, volume, _rotationZYX(rot)); } throw runtime_error("DD4hep: Volume: Attempt to assign an invalid physical volume."); } /// Place rotated daughter volume. The position is automatically the identity position -PlacedVolume Volume::placeVolume(const Volume& volume, const Rotation3D& rot) const { - if ( volume.isValid() ) { - return _addNode(m_element,volume,_rotation3D(rot)); +PlacedVolume Volume::placeVolume(const Volume& volume, const Rotation3D& rot) const { + if (volume.isValid()) { + return _addNode(m_element, volume, _rotation3D(rot)); } throw runtime_error("DD4hep: Volume: Attempt to assign an invalid physical volume."); } /// Set the volume's material -const Volume& Volume::setMaterial(const Material& m) const { - if ( m.isValid() ) { +const Volume& Volume::setMaterial(const Material& m) const { + if (m.isValid()) { TGeoMedium* medium = m._ptr<TGeoMedium>(); - if ( medium ) { + if (medium) { m_element->SetMedium(medium); return *this; } - throw runtime_error("DD4hep: Volume: Medium "+string(m.name())+" is not registered with geometry manager."); + throw runtime_error("DD4hep: Volume: Medium " + string(m.name()) + " is not registered with geometry manager."); } throw runtime_error("DD4hep: Volume: Attempt to assign invalid material."); } /// Access to the Volume material -Material Volume::material() const { +Material Volume::material() const { return Ref_t(m_element->GetMedium()); } /// Set Visualization attributes to the volume -const Volume& Volume::setVisAttributes(const VisAttr& attr) const { - if ( attr.isValid() ) { +const Volume& Volume::setVisAttributes(const VisAttr& attr) const { + if (attr.isValid()) { VisAttr::Object* vis = attr.data<VisAttr::Object>(); Color_t bright = TColor::GetColorBright(vis->color); - Color_t dark = TColor::GetColorDark(vis->color); + Color_t dark = TColor::GetColorDark(vis->color); int draw_style = vis->drawingStyle; int line_style = vis->lineStyle; m_element->SetLineColor(dark); - if ( draw_style == VisAttr::SOLID ) { + if (draw_style == VisAttr::SOLID) { m_element->SetFillColor(bright); - m_element->SetFillStyle(1001); // Root: solid + m_element->SetFillStyle(1001); // Root: solid } else { m_element->SetFillColor(0); m_element->SetFillStyle(0); // Root: hollow } - if ( line_style == VisAttr::SOLID ) + if (line_style == VisAttr::SOLID) m_element->SetFillStyle(1); - else if ( line_style == VisAttr::DASHED ) + else if (line_style == VisAttr::DASHED) m_element->SetFillStyle(2); else m_element->SetFillStyle(line_style); m_element->SetLineWidth(10); m_element->SetVisibility(vis->visible ? kTRUE : kFALSE); - m_element->SetAttBit(TGeoAtt::kVisContainers,kTRUE); + m_element->SetAttBit(TGeoAtt::kVisContainers, kTRUE); m_element->SetVisDaughters(vis->showDaughters ? kTRUE : kFALSE); } _data(*this)->vis = attr; @@ -444,13 +466,13 @@ const Volume& Volume::setVisAttributes(const VisAttr& attr) const { } /// Set Visualization attributes to the volume -const Volume& Volume::setVisAttributes(const LCDD& lcdd, const string& name) const { - if ( !name.empty() ) { +const Volume& Volume::setVisAttributes(const LCDD& lcdd, const string& name) const { + if (!name.empty()) { VisAttr attr = lcdd.visAttributes(name); _data(*this)->vis = attr; setVisAttributes(attr); } - else { + else { /* string tag = this->name(); if ( ::strstr(tag.c_str(),"_slice") ) // Slices turned off by default @@ -467,93 +489,92 @@ const Volume& Volume::setVisAttributes(const LCDD& lcdd, const string& name) co } /// Attach attributes to the volume -const Volume& Volume::setAttributes(const LCDD& lcdd, - const string& region, - const string& limits, - const string& vis) const -{ - if ( !region.empty() ) setRegion(lcdd.region(region)); - if ( !limits.empty() ) setLimitSet(lcdd.limitSet(limits)); - setVisAttributes(lcdd,vis); +const Volume& Volume::setAttributes(const LCDD& lcdd, const string& region, const string& limits, const string& vis) const { + if (!region.empty()) + setRegion(lcdd.region(region)); + if (!limits.empty()) + setLimitSet(lcdd.limitSet(limits)); + setVisAttributes(lcdd, vis); return *this; } /// Access the visualisation attributes -VisAttr Volume::visAttributes() const { - Object* o = _data(*this,false); - if ( o ) return o->vis; +VisAttr Volume::visAttributes() const { + Object* o = _data(*this, false); + if (o) + return o->vis; return VisAttr(); } /// Set the volume's solid shape -const Volume& Volume::setSolid(const Solid& solid) const { +const Volume& Volume::setSolid(const Solid& solid) const { m_element->SetShape(solid); return *this; } /// Access to Solid (Shape) -Solid Volume::solid() const { +Solid Volume::solid() const { return Solid((*this)->GetShape()); } /// Set the regional attributes to the volume -const Volume& Volume::setRegion(const LCDD& lcdd, const string& name) const { - if ( !name.empty() ) { +const Volume& Volume::setRegion(const LCDD& lcdd, const string& name) const { + if (!name.empty()) { return setRegion(lcdd.region(name)); } return *this; } /// Set the regional attributes to the volume -const Volume& Volume::setRegion(const Region& obj) const { +const Volume& Volume::setRegion(const Region& obj) const { _data(*this)->region = obj; return *this; } /// Access to the handle to the region structure -Region Volume::region() const { +Region Volume::region() const { return _data(*this)->region; } /// Set the limits to the volume -const Volume& Volume::setLimitSet(const LCDD& lcdd, const string& name) const { - if ( !name.empty() ) { +const Volume& Volume::setLimitSet(const LCDD& lcdd, const string& name) const { + if (!name.empty()) { return setLimitSet(lcdd.limitSet(name)); } return *this; } /// Set the limits to the volume -const Volume& Volume::setLimitSet(const LimitSet& obj) const { +const Volume& Volume::setLimitSet(const LimitSet& obj) const { _data(*this)->limits = obj; return *this; } /// Access to the limit set -LimitSet Volume::limitSet() const { +LimitSet Volume::limitSet() const { return _data(*this)->limits; } /// Assign the sensitive detector structure -const Volume& Volume::setSensitiveDetector(const SensitiveDetector& obj) const { +const Volume& Volume::setSensitiveDetector(const SensitiveDetector& obj) const { //cout << "Setting sensitive detector '" << obj.name() << "' to volume:" << ptr() << " " << name() << endl; - _data(*this)->sens_det = obj; + _data(*this)->sens_det = obj; return *this; } /// Access to the handle to the sensitive detector -Ref_t Volume::sensitiveDetector() const { +Ref_t Volume::sensitiveDetector() const { const Object* o = _data(*this); - return o->sens_det; + return o->sens_det; } /// Accessor if volume is sensitive (ie. is attached to a sensitive detector) -bool Volume::isSensitive() const { +bool Volume::isSensitive() const { return _data(*this)->sens_det.isValid(); } /// Constructor to be used when creating a new geometry tree. Assembly::Assembly(const string& name) { - m_element = new Value<TGeoVolumeAssembly,Volume::Object>(name.c_str()); + m_element = new Value<TGeoVolumeAssembly, Volume::Object>(name.c_str()); } diff --git a/DDCore/src/XML/DocumentHandler.cpp b/DDCore/src/XML/DocumentHandler.cpp index afe4198bd..a9e3e5fc6 100644 --- a/DDCore/src/XML/DocumentHandler.cpp +++ b/DDCore/src/XML/DocumentHandler.cpp @@ -25,167 +25,171 @@ using namespace DD4hep::XML; #include "xercesc/sax/ErrorHandler.hpp" using namespace xercesc; -namespace DD4hep { namespace XML { - namespace { - XercesDOMParser* make_parser(xercesc::ErrorHandler* err_handler=0) { - XercesDOMParser* parser = new XercesDOMParser; - parser->setValidationScheme(XercesDOMParser::Val_Auto); - parser->setValidationSchemaFullChecking(true); - if ( err_handler ) { - parser->setErrorHandler(err_handler); +namespace DD4hep { + namespace XML { + namespace { + XercesDOMParser* make_parser(xercesc::ErrorHandler* err_handler = 0) { + XercesDOMParser* parser = new XercesDOMParser; + parser->setValidationScheme(XercesDOMParser::Val_Auto); + parser->setValidationSchemaFullChecking(true); + if (err_handler) { + parser->setErrorHandler(err_handler); + } + parser->setDoNamespaces(true); + parser->setDoSchema(true); + return parser; } - parser->setDoNamespaces(true); - parser->setDoSchema(true); - return parser; - } - Document parse_document(const void* bytes, size_t length, xercesc::ErrorHandler* err_handler) { - auto_ptr<XercesDOMParser> parser(make_parser(err_handler)); - MemBufInputSource src((const XMLByte*)bytes,length,"memory"); - parser->setValidationSchemaFullChecking(true); - parser->parse(src); - DOMDocument* doc = parser->adoptDocument(); - doc->setXmlStandalone(true); - doc->setStrictErrorChecking(true); - return (XmlDocument*)doc; + Document parse_document(const void* bytes, size_t length, xercesc::ErrorHandler* err_handler) { + auto_ptr<XercesDOMParser> parser(make_parser(err_handler)); + MemBufInputSource src((const XMLByte*) bytes, length, "memory"); + parser->setValidationSchemaFullChecking(true); + parser->parse(src); + DOMDocument* doc = parser->adoptDocument(); + doc->setXmlStandalone(true); + doc->setStrictErrorChecking(true); + return (XmlDocument*) doc; + } } - } - struct DocumentErrorHandler : public ErrorHandler, public DOMErrorHandler { - /// Constructor - DocumentErrorHandler() {} - /// Reset errors (Noop) - void resetErrors() { } - /// Warnings callback. Ignore them - void warning(const SAXParseException& /* e */) { } - /// Error handler - void error(const SAXParseException& e); - /// Fatal error handler - void fatalError(const SAXParseException& e); - virtual bool handleError(const DOMError& domError); - }; - bool DocumentErrorHandler::handleError(const DOMError& domError) { - switch(domError.getSeverity()) { - case DOMError::DOM_SEVERITY_WARNING: - cout << "DOM WARNING: "; - break; - case DOMError::DOM_SEVERITY_ERROR: - cout << "DOM ERROR: "; - break; - case DOMError::DOM_SEVERITY_FATAL_ERROR: - cout << "DOM FATAL: "; - break; - default: - cout << "DOM UNKNOWN: "; + struct DocumentErrorHandler: public ErrorHandler, public DOMErrorHandler { + /// Constructor + DocumentErrorHandler() { + } + /// Reset errors (Noop) + void resetErrors() { + } + /// Warnings callback. Ignore them + void warning(const SAXParseException& /* e */) { + } + /// Error handler + void error(const SAXParseException& e); + /// Fatal error handler + void fatalError(const SAXParseException& e); + virtual bool handleError(const DOMError& domError); + }; + bool DocumentErrorHandler::handleError(const DOMError& domError) { + switch (domError.getSeverity()) { + case DOMError::DOM_SEVERITY_WARNING: + cout << "DOM WARNING: "; + break; + case DOMError::DOM_SEVERITY_ERROR: + cout << "DOM ERROR: "; + break; + case DOMError::DOM_SEVERITY_FATAL_ERROR: + cout << "DOM FATAL: "; + break; + default: + cout << "DOM UNKNOWN: "; + return false; + } + cout << _toString(domError.getType()) << ": " << _toString(domError.getMessage()) << endl; + DOMLocator* loc = domError.getLocation(); + if (loc) { + cout << "Location: Line:" << loc->getLineNumber() << " Column:" << loc->getColumnNumber() << endl; + } return false; } - cout << _toString(domError.getType()) << ": " << _toString(domError.getMessage()) << endl; - DOMLocator* loc = domError.getLocation(); - if ( loc ) { - cout << "Location: Line:" << loc->getLineNumber() - << " Column:" << loc->getColumnNumber() << endl; + void DocumentErrorHandler::error(const SAXParseException& e) { + string m(_toString(e.getMessage())); + if (m.find("The values for attribute 'name' must be names or name tokens") != string::npos + || m.find("The values for attribute 'ID' must be names or name tokens") != string::npos + || m.find("for attribute 'name' must be Name or Nmtoken") != string::npos + || m.find("for attribute 'ID' must be Name or Nmtoken") != string::npos + || m.find("for attribute 'name' is invalid Name or NMTOKEN value") != string::npos + || m.find("for attribute 'ID' is invalid Name or NMTOKEN value") != string::npos) + return; + string sys(_toString(e.getSystemId())); + cout << "Error at file \"" << sys << "\", line " << e.getLineNumber() << ", column " << e.getColumnNumber() << endl + << "Message: " << m << endl; + } + void DocumentErrorHandler::fatalError(const SAXParseException& e) { + string m(_toString(e.getMessage())); + string sys(_toString(e.getSystemId())); + cout << "Fatal Error at file \"" << sys << "\", line " << e.getLineNumber() << ", column " << e.getColumnNumber() << endl + << "Message: " << m << endl; + //throw runtime_error( "Standard pool exception : Fatal Error on the DOM Parser" ); } - return false; - } - void DocumentErrorHandler::error(const SAXParseException& e) { - string m(_toString(e.getMessage())); - if (m.find("The values for attribute 'name' must be names or name tokens")!=string::npos || - m.find("The values for attribute 'ID' must be names or name tokens")!=string::npos || - m.find("for attribute 'name' must be Name or Nmtoken")!=string::npos || - m.find("for attribute 'ID' must be Name or Nmtoken")!=string::npos || - m.find("for attribute 'name' is invalid Name or NMTOKEN value")!=string::npos || - m.find("for attribute 'ID' is invalid Name or NMTOKEN value")!=string::npos ) - return; - string sys(_toString(e.getSystemId())); - cout << "Error at file \"" << sys - << "\", line " << e.getLineNumber() << ", column " << e.getColumnNumber() << endl - << "Message: " << m << endl; - } - void DocumentErrorHandler::fatalError(const SAXParseException& e) { - string m(_toString(e.getMessage())); - string sys(_toString(e.getSystemId())); - cout << "Fatal Error at file \"" << sys - << "\", line " << e.getLineNumber() << ", column " << e.getColumnNumber() << endl - << "Message: " << m << endl; - //throw runtime_error( "Standard pool exception : Fatal Error on the DOM Parser" ); - } - void dumpTree(xercesc::DOMDocument* doc) { - DOMImplementation *imp = DOMImplementationRegistry::getDOMImplementation(Strng_t("LS")); - XMLFormatTarget *tar = new StdOutFormatTarget(); - DOMLSOutput *out = imp->createLSOutput(); - DOMLSSerializer *wrt = imp->createLSSerializer(); - out->setByteStream(tar); - wrt->getDomConfig()->setParameter(Strng_t("format-pretty-print"), true); - wrt->write(doc, out); - out->release(); - wrt->release(); + void dumpTree(xercesc::DOMDocument* doc) { + DOMImplementation *imp = DOMImplementationRegistry::getDOMImplementation(Strng_t("LS")); + XMLFormatTarget *tar = new StdOutFormatTarget(); + DOMLSOutput *out = imp->createLSOutput(); + DOMLSSerializer *wrt = imp->createLSSerializer(); + out->setByteStream(tar); + wrt->getDomConfig()->setParameter(Strng_t("format-pretty-print"), true); + wrt->write(doc, out); + out->release(); + wrt->release(); + } } -}} +} /// Default constructor of a document handler using XercesC -DocumentHandler::DocumentHandler() : m_errHdlr(new DocumentErrorHandler()) { +DocumentHandler::DocumentHandler() + : m_errHdlr(new DocumentErrorHandler()) { } /// Default destructor of a document handler using XercesC -DocumentHandler::~DocumentHandler() { +DocumentHandler::~DocumentHandler() { } -Document DocumentHandler::load(Handle_t base, const XMLCh* fname) const { - xercesc::DOMElement* e = (xercesc::DOMElement*)base.ptr(); +Document DocumentHandler::load(Handle_t base, const XMLCh* fname) const { + xercesc::DOMElement* e = (xercesc::DOMElement*) base.ptr(); xercesc::XMLURL base_url(e->getBaseURI()); - xercesc::XMLURL ref_url(base_url,fname); + xercesc::XMLURL ref_url(base_url, fname); return load(_toString(ref_url.getURLText())); } -Document DocumentHandler::load(const string& fname) const { +Document DocumentHandler::load(const string& fname) const { cout << "Loading document URI:" << fname << endl; - XMLURL xerurl = (const XMLCh*)Strng_t(fname); - string path = _toString(xerurl.getPath()); - string proto = _toString(xerurl.getProtocolName()); - auto_ptr<XercesDOMParser> parser(make_parser(m_errHdlr.get())); - cout << " protocol:" << proto << endl - << " path:" << path << endl; + XMLURL xerurl = (const XMLCh*) Strng_t(fname); + string path = _toString(xerurl.getPath()); + string proto = _toString(xerurl.getProtocolName()); + auto_ptr < XercesDOMParser > parser(make_parser(m_errHdlr.get())); + cout << " protocol:" << proto << endl << " path:" << path << endl; try { parser->parse(path.c_str()); } - catch(exception& e) { + catch (exception& e) { cout << "parse(path):" << e.what() << endl; try { parser->parse(fname.c_str()); } - catch(exception& ex) { - cout << "parse(URI):" << ex.what() << endl; + catch (exception& ex) { + cout << "parse(URI):" << ex.what() << endl; } } cout << "Document succesfully parsed....." << endl; - return (XmlDocument*)parser->adoptDocument(); + return (XmlDocument*) parser->adoptDocument(); } /// Parse a standalong XML string into a document. -Document DocumentHandler::parse(const char* bytes, size_t length) const { - auto_ptr<XercesDOMParser> parser(make_parser(m_errHdlr.get())); - MemBufInputSource src((const XMLByte*)bytes,length,"memory"); +Document DocumentHandler::parse(const char* bytes, size_t length) const { + auto_ptr < XercesDOMParser > parser(make_parser(m_errHdlr.get())); + MemBufInputSource src((const XMLByte*) bytes, length, "memory"); parser->setValidationSchemaFullChecking(true); parser->parse(src); - DOMDocument* doc = parser->adoptDocument(); + DOMDocument* doc = parser->adoptDocument(); doc->setXmlStandalone(true); doc->setStrictErrorChecking(true); - return (XmlDocument*)doc; + return (XmlDocument*) doc; } /// Write xml document to output file (stdout if file name empty) int DocumentHandler::output(Document doc, const string& fname) const { - XMLFormatTarget *tar = 0; + XMLFormatTarget *tar = 0; DOMImplementation *imp = DOMImplementationRegistry::getDOMImplementation(Strng_t("LS")); - DOMLSOutput *out = imp->createLSOutput(); - DOMLSSerializer *wrt = imp->createLSSerializer(); + DOMLSOutput *out = imp->createLSOutput(); + DOMLSSerializer *wrt = imp->createLSSerializer(); - if ( fname.empty() ) tar = new StdOutFormatTarget(); - else tar = new LocalFileFormatTarget(Strng_t(fname)); + if (fname.empty()) + tar = new StdOutFormatTarget(); + else + tar = new LocalFileFormatTarget(Strng_t(fname)); out->setByteStream(tar); wrt->getDomConfig()->setParameter(Strng_t("format-pretty-print"), true); - wrt->write((xercesc::DOMDocument*)doc.ptr(), out); + wrt->write((xercesc::DOMDocument*) doc.ptr(), out); out->release(); wrt->release(); delete tar; @@ -200,23 +204,23 @@ int DocumentHandler::output(Document doc, const string& fname) const { #endif #include <sys/stat.h> -namespace DD4hep { namespace XML { - struct DocumentErrorHandler {}; - union Xml { - Xml(void* ptr) : p(ptr) {} - Xml(const void* ptr) : cp(ptr) {} - void* p; - const void* cp; - TiXmlElement* e; - XmlElement* xe; - TiXmlAttribute* a; - Attribute attr; - TiXmlNode* n; - TiXmlDocument* d; - XmlDocument* xd; - }; +namespace DD4hep {namespace XML { + struct DocumentErrorHandler {}; + union Xml { + Xml(void* ptr) : p(ptr) {} + Xml(const void* ptr) : cp(ptr) {} + void* p; + const void* cp; + TiXmlElement* e; + XmlElement* xe; + TiXmlAttribute* a; + Attribute attr; + TiXmlNode* n; + TiXmlDocument* d; + XmlDocument* xd; + }; -}} + }} namespace { static string _clean_fname(const string& s) { @@ -229,10 +233,10 @@ namespace { DocumentHandler::DocumentHandler() {} /// Default destructor of a document handler using TiXml -DocumentHandler::~DocumentHandler() {} +DocumentHandler::~DocumentHandler() {} /// Load a document based on the relative URI of the parent document -Document DocumentHandler::load(Handle_t base, const XmlChar* fname) const { +Document DocumentHandler::load(Handle_t base, const XmlChar* fname) const { string fn, clean = _clean_fname(fname); struct stat st; Element elt(base); @@ -254,28 +258,28 @@ Document DocumentHandler::load(Handle_t base, const XmlChar* fname) const { fn += _clean_fname(fname); } if ( ::stat(fn.c_str(),&st)==0 ) - return load(fn); + return load(fn); else if ( ::stat(clean.c_str(),&st)==0 ) - return load(clean); + return load(clean); return load(fname); } -Document DocumentHandler::load(const string& fname) const { +Document DocumentHandler::load(const string& fname) const { cout << "Loading document URI:" << fname << endl; TiXmlDocument* doc = new TiXmlDocument(_clean_fname(fname).c_str()); bool result = false; - try { + try { result = doc->LoadFile(); if ( !result ) { if ( doc->Error() ) { - cout << "Unknown error whaile parsing XML document with TiXml:" << endl; - cout << "Document:" << doc->Value() << endl; - cout << "Location: Line:" << doc->ErrorRow() - << " Column:" << doc->ErrorCol() << endl; - throw runtime_error(string("DD4hep: ")+doc->ErrorDesc()); + cout << "Unknown error whaile parsing XML document with TiXml:" << endl; + cout << "Document:" << doc->Value() << endl; + cout << "Location: Line:" << doc->ErrorRow() + << " Column:" << doc->ErrorCol() << endl; + throw runtime_error(string("DD4hep: ")+doc->ErrorDesc()); } else - throw runtime_error("DD4hep: Unknown error whaile parsing XML document with TiXml."); + throw runtime_error("DD4hep: Unknown error whaile parsing XML document with TiXml."); } } catch(exception& e) { @@ -292,15 +296,15 @@ Document DocumentHandler::load(const string& fname) const { /// Parse a standalong XML string into a document. Document DocumentHandler::parse(const char* doc_string, size_t /* length */) const { TiXmlDocument* doc = new TiXmlDocument(); - try { + try { if ( 0 == doc->Parse(doc_string) ) { return (XmlDocument*)doc; } if ( doc->Error() ) { cout << "Unknown error whaile parsing XML document with TiXml:" << endl; cout << "Document:" << doc->Value() << endl; - cout << "Location: Line:" << doc->ErrorRow() - << " Column:" << doc->ErrorCol() << endl; + cout << "Location: Line:" << doc->ErrorRow() + << " Column:" << doc->ErrorCol() << endl; throw runtime_error(string("DD4hep: ")+doc->ErrorDesc()); } throw runtime_error("DD4hep: Unknown error whaile parsing XML document with TiXml."); @@ -326,14 +330,14 @@ int DocumentHandler::output(Document doc, const string& fname) const { } #endif - + /// Create new XML document by parsing empty xml buffer -Document DocumentHandler::create(const char* tag, const char* comment) const { +Document DocumentHandler::create(const char* tag, const char* comment) const { string top(tag); string empty = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"; - empty += "<"+top+"/>\0\0"; - Document doc = parse(empty.c_str(),empty.length()+1); - if ( comment ) { + empty += "<" + top + "/>\0\0"; + Document doc = parse(empty.c_str(), empty.length() + 1); + if (comment) { Element top_elt = doc.root(); top_elt.addComment(comment); } diff --git a/DDCore/src/XML/Layering.cpp b/DDCore/src/XML/Layering.cpp index 467e6180d..70e93c9d9 100644 --- a/DDCore/src/XML/Layering.cpp +++ b/DDCore/src/XML/Layering.cpp @@ -19,22 +19,21 @@ using namespace std; using namespace DD4hep; using namespace DD4hep::XML; -LayerSlice& LayerSlice::operator=(const LayerSlice& c) { - if ( &c != this ) { - _sensitive = c._sensitive; +LayerSlice& LayerSlice::operator=(const LayerSlice& c) { + if (&c != this) { + _sensitive = c._sensitive; _thickness = c._thickness; - _material = c._material; + _material = c._material; } return *this; } -Layer::Layer(const Layer& c) -: _thickness(c._thickness), _preOffset(c._preOffset), _slices(c._slices) -{ +Layer::Layer(const Layer& c) + : _thickness(c._thickness), _preOffset(c._preOffset), _slices(c._slices) { } -Layer& Layer::operator=(const Layer& c) { - if ( this != &c ) { +Layer& Layer::operator=(const Layer& c) { + if (this != &c) { _thickness = c._thickness; _preOffset = c._preOffset; _slices = c._slices; @@ -42,52 +41,54 @@ Layer& Layer::operator=(const Layer& c) { return *this; } -void Layer::compute() { +void Layer::compute() { _thickness = 0.; - for(vector<LayerSlice>::const_iterator i=_slices.begin(); i!=_slices.end(); ++i) + for (vector<LayerSlice>::const_iterator i = _slices.begin(); i != _slices.end(); ++i) _thickness += (*i)._thickness; } -double LayerStack::sectionThickness(size_t is, size_t ie) const { +double LayerStack::sectionThickness(size_t is, size_t ie) const { double thick = 0.; - if ( is > ie ) - throw runtime_error("LayerStack::sectionThickness: First index ("+_toString(is)+ - ") must be <= second index ("+_toString(ie)+")!"); - else if( is > _layers.size() ) - throw runtime_error("LayerStack::sectionThickness: First index ("+_toString(is)+ - ") out of range. #layers="+_toString(_layers.size())+")."); - else if( ie > _layers.size() ) - throw runtime_error("LayerStack::sectionThickness: Second index ("+_toString(is)+ - ") out of range. #layers="+_toString(_layers.size())+")."); - for(size_t i=is; i<=ie; ++i) + if (is > ie) + throw runtime_error( + "LayerStack::sectionThickness: First index (" + _toString(is) + ") must be <= second index (" + _toString(ie) + ")!"); + else if (is > _layers.size()) + throw runtime_error( + "LayerStack::sectionThickness: First index (" + _toString(is) + ") out of range. #layers=" + _toString(_layers.size()) + + ")."); + else if (ie > _layers.size()) + throw runtime_error( + "LayerStack::sectionThickness: Second index (" + _toString(is) + ") out of range. #layers=" + _toString(_layers.size()) + + ")."); + for (size_t i = is; i <= ie; ++i) thick += _layers[i]->thicknessWithPreOffset(); return thick; } -Layering::Layering() { +Layering::Layering() { } -Layering::Layering(Element e) { +Layering::Layering(Element e) { LayeringCnv(e).fromCompact(*this); } -Layering::~Layering() { +Layering::~Layering() { } -const Layer* Layering::layer(size_t which) const { +const Layer* Layering::layer(size_t which) const { return _stack.layers()[which]; } -void LayeringCnv::fromCompact(Layering& layering) const { +void LayeringCnv::fromCompact(Layering& layering) const { vector<Layer*>& layers = layering.layers(); int count = 0; - for_each(layers.begin(),layers.end(),deletePtr<Layer>); - for(Collection_t c(m_element,_U(layer)); c; ++c) { + for_each(layers.begin(), layers.end(), deletePtr<Layer>); + for (Collection_t c(m_element, _U (layer)); c; ++c) { Layer lay; Component layer = c; int repeat = layer.hasAttr(_U(repeat)) ? layer.repeat() : 1; ++count; - for(Collection_t s(c,_U(slice)); s; ++s) { + for (Collection_t s(c, _U(slice)); s; ++s) { Component slice = s; string mat = slice.materialStr(); LayerSlice lslice(slice.isSensitive(), slice.thickness(), mat); @@ -95,20 +96,20 @@ void LayeringCnv::fromCompact(Layering& layering) const { } lay.compute(); // Add layer to stack once for each repetition - for(int k=0; k<repeat; ++k) + for (int k = 0; k < repeat; ++k) layers.push_back(new Layer(lay)); } - if ( 0 == count ) { + if (0 == count) { throw runtime_error("LayeringCnv::fromCompact: No layer children to be build!"); } } -double Layering::singleLayerThickness(XML::Element e) const { +double Layering::singleLayerThickness(XML::Element e) const { Component layer = e; double thickness = 0e0; - for(Collection_t s(layer,_U(slice)); s; ++s) { + for (Collection_t s(layer, _U(slice)); s; ++s) { Component slice = s; thickness += slice.thickness(); - } + } return thickness; } diff --git a/DDCore/src/XML/XMLDetector.cpp b/DDCore/src/XML/XMLDetector.cpp index 4cddd3658..4d68e56be 100644 --- a/DDCore/src/XML/XMLDetector.cpp +++ b/DDCore/src/XML/XMLDetector.cpp @@ -12,58 +12,58 @@ using namespace std; using namespace DD4hep::XML; -string Component::materialStr() const { - return m_element.attr<string>(_U(material)); +string Component::materialStr() const { + return m_element.attr < string > (_U(material)); } -bool Component::isSensitive() const { - char val = m_element.hasAttr(_U(sensitive)) ? m_element.attr<string>(_U(sensitive))[0] : 'f'; +bool Component::isSensitive() const { + char val = m_element.hasAttr(_U(sensitive)) ? m_element.attr < string > (_U(sensitive))[0] : 'f'; val = ::toupper(val); return val == 'T' || val == 'Y'; } -int DetElement::id() const { +int DetElement::id() const { return m_element.hasAttr(_U(id)) ? m_element.attr<int>(_U(id)) : -1; } -string DetElement::materialStr() const { +string DetElement::materialStr() const { Handle_t h = m_element.child(_U(material)); - if ( h && h.hasAttr(_U(name)) ) { - return h.attr<string>(_U(name)); + if (h && h.hasAttr(_U(name))) { + return h.attr < string > (_U(name)); } return ""; } -void DetElement::check(bool condition, const string& msg) const { - if ( condition ) { +void DetElement::check(bool condition, const string& msg) const { + if (condition) { throw runtime_error(msg); } } -bool DetElement::isTracker() const { - if ( m_element ) { - string type = attr<string>(_U(type)); - if ( type.find("Tracker") != string::npos && hasAttr(_U(readout)) ) { +bool DetElement::isTracker() const { + if (m_element) { + string type = attr < string > (_U(type)); + if (type.find("Tracker") != string::npos && hasAttr(_U(readout))) { return true; } } return false; } -bool DetElement::isCalorimeter() const { - if ( m_element ) { - string type = attr<string>(_U(type)); - if ( type.find("Calorimeter") != string::npos && hasAttr(_U(readout)) ) { +bool DetElement::isCalorimeter() const { + if (m_element) { + string type = attr < string > (_U(type)); + if (type.find("Calorimeter") != string::npos && hasAttr(_U(readout))) { return true; } } return false; } -bool DetElement::isInsideTrackingVolume() const { - if ( m_element && hasAttr(_U(insideTrackingVolume)) ) - return attr<bool>(_U(insideTrackingVolume)); +bool DetElement::isInsideTrackingVolume() const { + if (m_element && hasAttr(_U(insideTrackingVolume)) ) + return attr<bool>(_U(insideTrackingVolume)); else if ( isTracker() ) - return true; + return true; return false; } diff --git a/DDCore/src/XML/XMLDimension.cpp b/DDCore/src/XML/XMLDimension.cpp index b5274b661..330b49f8f 100644 --- a/DDCore/src/XML/XMLDimension.cpp +++ b/DDCore/src/XML/XMLDimension.cpp @@ -30,180 +30,178 @@ using namespace DD4hep::XML; Dimension Dimension::name(bool throw_if_not_present) const { \ return m_element.child(Unicode_##name,throw_if_not_present); } -XML_ATTR_ACCESSOR(int,id) - XML_ATTR_ACCESSOR_INT(id) - XML_ATTR_ACCESSOR(bool,combineHits) - - XML_ATTR_ACCESSOR(double,x) - XML_ATTR_ACCESSOR_DOUBLE(x) - XML_ATTR_ACCESSOR(double,X) - XML_ATTR_ACCESSOR(double,dx) - XML_ATTR_ACCESSOR_DOUBLE(dx) - XML_ATTR_ACCESSOR(double,x0) - XML_ATTR_ACCESSOR(double,x1) - XML_ATTR_ACCESSOR(double,x2) - XML_ATTR_ACCESSOR(double,xmin) - XML_ATTR_ACCESSOR(double,xmax) - XML_ATTR_ACCESSOR(double,x_offset) - XML_ATTR_ACCESSOR(double,dim_x) - - XML_ATTR_ACCESSOR(double,y) - XML_ATTR_ACCESSOR_DOUBLE(y) - XML_ATTR_ACCESSOR(double,Y) - XML_ATTR_ACCESSOR(double,dy) - XML_ATTR_ACCESSOR_DOUBLE(dy) - XML_ATTR_ACCESSOR(double,y0) - XML_ATTR_ACCESSOR(double,y1) - XML_ATTR_ACCESSOR(double,y2) - XML_ATTR_ACCESSOR(double,ymin) - XML_ATTR_ACCESSOR(double,ymax) - XML_ATTR_ACCESSOR(double,y_offset) - XML_ATTR_ACCESSOR(double,dim_y) - - XML_ATTR_ACCESSOR(double,z) - XML_ATTR_ACCESSOR_DOUBLE(z) - XML_ATTR_ACCESSOR(double,Z) - XML_ATTR_ACCESSOR(double,dz) - XML_ATTR_ACCESSOR_DOUBLE(dz) - XML_ATTR_ACCESSOR(double,z0) - XML_ATTR_ACCESSOR(double,z1) - XML_ATTR_ACCESSOR(double,z2) - XML_ATTR_ACCESSOR(double,zmin) - XML_ATTR_ACCESSOR(double,zmax) - XML_ATTR_ACCESSOR(double,z_offset) - XML_ATTR_ACCESSOR(double,dim_z) - XML_ATTR_ACCESSOR(double,outer_z) - XML_ATTR_ACCESSOR(double,inner_z) - - XML_ATTR_ACCESSOR(double,b) - XML_ATTR_ACCESSOR(double,g) - XML_ATTR_ACCESSOR(double,B) - XML_ATTR_ACCESSOR(double,G) - XML_ATTR_ACCESSOR(double,r) - XML_ATTR_ACCESSOR_DOUBLE(r) - XML_ATTR_ACCESSOR(double,R) - XML_ATTR_ACCESSOR(double,dr) - XML_ATTR_ACCESSOR(double,rmin) - XML_ATTR_ACCESSOR(double,rmax) - XML_ATTR_ACCESSOR(double,radius) - XML_ATTR_ACCESSOR(double,outer_r) - XML_ATTR_ACCESSOR(double,outer_radius) - XML_ATTR_ACCESSOR(double,inner_r) - XML_ATTR_ACCESSOR(double,inner_radius) - - XML_ATTR_ACCESSOR(double,angle) - XML_ATTR_ACCESSOR(double,alpha) - XML_ATTR_ACCESSOR(double,beta) - XML_ATTR_ACCESSOR(double,gamma) - XML_ATTR_ACCESSOR(double,delta) - XML_ATTR_ACCESSOR(double,epsilon) - XML_ATTR_ACCESSOR(double,theta) - XML_ATTR_ACCESSOR(int,thetaBins) - XML_ATTR_ACCESSOR(double,psi) - XML_ATTR_ACCESSOR(double,phi) - XML_ATTR_ACCESSOR(int,phiBins) - XML_ATTR_ACCESSOR(double,phi0) - XML_ATTR_ACCESSOR_DOUBLE(phi0) - XML_ATTR_ACCESSOR(double,phi1) - XML_ATTR_ACCESSOR_DOUBLE(phi1) - XML_ATTR_ACCESSOR(double,deltaphi) - - - XML_ATTR_ACCESSOR(double,length) - XML_ATTR_ACCESSOR(double,width) - XML_ATTR_ACCESSOR(double,height) - XML_ATTR_ACCESSOR(double,depth) - XML_ATTR_ACCESSOR(double,offset) - XML_ATTR_ACCESSOR_DOUBLE(offset) - XML_ATTR_ACCESSOR(double,crossing_angle) - XML_ATTR_ACCESSOR(double,incoming_r) - XML_ATTR_ACCESSOR(double,outgoing_r) - XML_ATTR_ACCESSOR(double,phi_size_max) - XML_ATTR_ACCESSOR(double,r_size) - - XML_ATTR_ACCESSOR(double,gap) - XML_ATTR_ACCESSOR(double,z_length) - XML_ATTR_ACCESSOR(double,zhalf) - XML_ATTR_ACCESSOR(double,phi_tilt) - XML_ATTR_ACCESSOR(int,nphi) - XML_ATTR_ACCESSOR(double,rc) - XML_ATTR_ACCESSOR(int,nz) - XML_ATTR_ACCESSOR(double,zstart) - XML_ATTR_ACCESSOR(double,start) - XML_ATTR_ACCESSOR(double,end) - XML_ATTR_ACCESSOR(double,thickness) - XML_ATTR_ACCESSOR(int,numsides) - XML_ATTR_ACCESSOR(int,number) - XML_ATTR_ACCESSOR(int,repeat) - XML_ATTR_ACCESSOR(bool,reflect) - XML_ATTR_ACCESSOR_BOOL(reflect) - - XML_ATTR_ACCESSOR(int,nmodules) - XML_ATTR_ACCESSOR(int,nModules) - XML_ATTR_ACCESSOR(int,RowID) - XML_ATTR_ACCESSOR(int,nPads) - XML_ATTR_ACCESSOR(double,moduleHeight) - XML_ATTR_ACCESSOR(double,moduleWidth) - XML_ATTR_ACCESSOR(double,modulePosX) - XML_ATTR_ACCESSOR(double,modulePosY) - XML_ATTR_ACCESSOR(double,modulePitch) - XML_ATTR_ACCESSOR(double,rowPitch) - XML_ATTR_ACCESSOR(double,padPitch) - XML_ATTR_ACCESSOR(double,rowHeight) - XML_ATTR_ACCESSOR(double,inner_field) - XML_ATTR_ACCESSOR(double,outer_field) - XML_ATTR_ACCESSOR(int,type) - - XML_ATTR_ACCESSOR(bool,visible) - XML_ATTR_ACCESSOR(bool,show_daughters) +XML_ATTR_ACCESSOR(int, id) +XML_ATTR_ACCESSOR_INT(id) +XML_ATTR_ACCESSOR(bool, combineHits) + +XML_ATTR_ACCESSOR(double, x) +XML_ATTR_ACCESSOR_DOUBLE(x) +XML_ATTR_ACCESSOR(double, X) +XML_ATTR_ACCESSOR(double, dx) +XML_ATTR_ACCESSOR_DOUBLE(dx) +XML_ATTR_ACCESSOR(double, x0) +XML_ATTR_ACCESSOR(double, x1) +XML_ATTR_ACCESSOR(double, x2) +XML_ATTR_ACCESSOR(double, xmin) +XML_ATTR_ACCESSOR(double, xmax) +XML_ATTR_ACCESSOR(double, x_offset) +XML_ATTR_ACCESSOR(double, dim_x) + +XML_ATTR_ACCESSOR(double, y) +XML_ATTR_ACCESSOR_DOUBLE(y) +XML_ATTR_ACCESSOR(double, Y) +XML_ATTR_ACCESSOR(double, dy) +XML_ATTR_ACCESSOR_DOUBLE(dy) +XML_ATTR_ACCESSOR(double, y0) +XML_ATTR_ACCESSOR(double, y1) +XML_ATTR_ACCESSOR(double, y2) +XML_ATTR_ACCESSOR(double, ymin) +XML_ATTR_ACCESSOR(double, ymax) +XML_ATTR_ACCESSOR(double, y_offset) +XML_ATTR_ACCESSOR(double, dim_y) + +XML_ATTR_ACCESSOR(double, z) +XML_ATTR_ACCESSOR_DOUBLE(z) +XML_ATTR_ACCESSOR(double, Z) +XML_ATTR_ACCESSOR(double, dz) +XML_ATTR_ACCESSOR_DOUBLE(dz) +XML_ATTR_ACCESSOR(double, z0) +XML_ATTR_ACCESSOR(double, z1) +XML_ATTR_ACCESSOR(double, z2) +XML_ATTR_ACCESSOR(double, zmin) +XML_ATTR_ACCESSOR(double, zmax) +XML_ATTR_ACCESSOR(double, z_offset) +XML_ATTR_ACCESSOR(double, dim_z) +XML_ATTR_ACCESSOR(double, outer_z) +XML_ATTR_ACCESSOR(double, inner_z) + +XML_ATTR_ACCESSOR(double, b) +XML_ATTR_ACCESSOR(double, g) +XML_ATTR_ACCESSOR(double, B) +XML_ATTR_ACCESSOR(double, G) +XML_ATTR_ACCESSOR(double, r) +XML_ATTR_ACCESSOR_DOUBLE(r) +XML_ATTR_ACCESSOR(double, R) +XML_ATTR_ACCESSOR(double, dr) +XML_ATTR_ACCESSOR(double, rmin) +XML_ATTR_ACCESSOR(double, rmax) +XML_ATTR_ACCESSOR(double, radius) +XML_ATTR_ACCESSOR(double, outer_r) +XML_ATTR_ACCESSOR(double, outer_radius) +XML_ATTR_ACCESSOR(double, inner_r) +XML_ATTR_ACCESSOR(double, inner_radius) + +XML_ATTR_ACCESSOR(double, angle) +XML_ATTR_ACCESSOR(double, alpha) +XML_ATTR_ACCESSOR(double, beta) +XML_ATTR_ACCESSOR(double, gamma) +XML_ATTR_ACCESSOR(double, delta) +XML_ATTR_ACCESSOR(double, epsilon) +XML_ATTR_ACCESSOR(double, theta) +XML_ATTR_ACCESSOR(int, thetaBins) +XML_ATTR_ACCESSOR(double, psi) +XML_ATTR_ACCESSOR(double, phi) +XML_ATTR_ACCESSOR(int, phiBins) +XML_ATTR_ACCESSOR(double, phi0) +XML_ATTR_ACCESSOR_DOUBLE(phi0) +XML_ATTR_ACCESSOR(double, phi1) +XML_ATTR_ACCESSOR_DOUBLE(phi1) +XML_ATTR_ACCESSOR(double, deltaphi) + +XML_ATTR_ACCESSOR(double, length) +XML_ATTR_ACCESSOR(double, width) +XML_ATTR_ACCESSOR(double, height) +XML_ATTR_ACCESSOR(double, depth) +XML_ATTR_ACCESSOR(double, offset) +XML_ATTR_ACCESSOR_DOUBLE(offset) +XML_ATTR_ACCESSOR(double, crossing_angle) +XML_ATTR_ACCESSOR(double, incoming_r) +XML_ATTR_ACCESSOR(double, outgoing_r) +XML_ATTR_ACCESSOR(double, phi_size_max) +XML_ATTR_ACCESSOR(double, r_size) + +XML_ATTR_ACCESSOR(double, gap) +XML_ATTR_ACCESSOR(double, z_length) +XML_ATTR_ACCESSOR(double, zhalf) +XML_ATTR_ACCESSOR(double, phi_tilt) +XML_ATTR_ACCESSOR(int, nphi) +XML_ATTR_ACCESSOR(double, rc) +XML_ATTR_ACCESSOR(int, nz) +XML_ATTR_ACCESSOR(double, zstart) +XML_ATTR_ACCESSOR(double, start) +XML_ATTR_ACCESSOR(double, end) +XML_ATTR_ACCESSOR(double, thickness) +XML_ATTR_ACCESSOR(int, numsides) +XML_ATTR_ACCESSOR(int, number) +XML_ATTR_ACCESSOR(int, repeat) +XML_ATTR_ACCESSOR(bool, reflect) +XML_ATTR_ACCESSOR_BOOL(reflect) + +XML_ATTR_ACCESSOR(int, nmodules) +XML_ATTR_ACCESSOR(int, nModules) +XML_ATTR_ACCESSOR(int, RowID) +XML_ATTR_ACCESSOR(int, nPads) +XML_ATTR_ACCESSOR(double, moduleHeight) +XML_ATTR_ACCESSOR(double, moduleWidth) +XML_ATTR_ACCESSOR(double, modulePosX) +XML_ATTR_ACCESSOR(double, modulePosY) +XML_ATTR_ACCESSOR(double, modulePitch) +XML_ATTR_ACCESSOR(double, rowPitch) +XML_ATTR_ACCESSOR(double, padPitch) +XML_ATTR_ACCESSOR(double, rowHeight) +XML_ATTR_ACCESSOR(double, inner_field) +XML_ATTR_ACCESSOR(double, outer_field) +XML_ATTR_ACCESSOR(int, type) + +XML_ATTR_ACCESSOR(bool, visible) +XML_ATTR_ACCESSOR(bool, show_daughters) #if 0 - XML_ATTR_ACCESSOR(double,) - XML_ATTR_ACCESSOR(double,) - XML_ATTR_ACCESSOR(double,) - XML_ATTR_ACCESSOR(double,) +XML_ATTR_ACCESSOR(double,) +XML_ATTR_ACCESSOR(double,) +XML_ATTR_ACCESSOR(double,) +XML_ATTR_ACCESSOR(double,) #endif - XML_CHILD_ACCESSOR_XML_DIM(dimensions) - XML_CHILD_ACCESSOR_XML_DIM(position) - XML_CHILD_ACCESSOR_XML_DIM(rotation) - XML_CHILD_ACCESSOR_XML_DIM(trd) - XML_CHILD_ACCESSOR_XML_DIM(tubs) - XML_CHILD_ACCESSOR_XML_DIM(staves) - XML_CHILD_ACCESSOR_XML_DIM(beampipe) +XML_CHILD_ACCESSOR_XML_DIM(dimensions) +XML_CHILD_ACCESSOR_XML_DIM(position) +XML_CHILD_ACCESSOR_XML_DIM(rotation) +XML_CHILD_ACCESSOR_XML_DIM(trd) +XML_CHILD_ACCESSOR_XML_DIM(tubs) +XML_CHILD_ACCESSOR_XML_DIM(staves) +XML_CHILD_ACCESSOR_XML_DIM(beampipe) - - string Dimension::padType() const { - return m_element.attr<string>(_U(pads)); +string Dimension::padType() const { + return m_element.attr < string > (_U(pads)); } -string Dimension::nameStr() const { - return m_element.attr<string>(_U(name)); +string Dimension::nameStr() const { + return m_element.attr < string > (_U(name)); } -string Dimension::refStr() const { - return m_element.attr<string>(_U(ref)); +string Dimension::refStr() const { + return m_element.attr < string > (_U(ref)); } -string Dimension::typeStr() const { - return m_element.attr<string>(_U(type)); +string Dimension::typeStr() const { + return m_element.attr < string > (_U(type)); } string Dimension::regionStr() const { - return m_element.hasAttr(_U(region)) ? m_element.attr<string>(_U(region)) : string(); + return m_element.hasAttr(_U(region)) ? m_element.attr < string > (_U(region)) : string(); } string Dimension::limitsStr() const { - return m_element.hasAttr(_U(limits)) ? m_element.attr<string>(_U(limits)) : string(); + return m_element.hasAttr(_U(limits)) ? m_element.attr < string > (_U(limits)) : string(); } -string Dimension::visStr() const { - return m_element.hasAttr(_U(vis)) ? m_element.attr<string>(_U(vis)) : string(); +string Dimension::visStr() const { + return m_element.hasAttr(_U(vis)) ? m_element.attr < string > (_U(vis)) : string(); } -string Dimension::readoutStr() const { - return m_element.hasAttr(_U(readout)) ? m_element.attr<string>(_U(readout)) : string(); +string Dimension::readoutStr() const { + return m_element.hasAttr(_U(readout)) ? m_element.attr < string > (_U(readout)) : string(); } -string Dimension::moduleStr() const { - return m_element.hasAttr(_U(module)) ? m_element.attr<string>(_U(module)) : string(); +string Dimension::moduleStr() const { + return m_element.hasAttr(_U(module)) ? m_element.attr < string > (_U(module)) : string(); } diff --git a/DDCore/src/XML/XMLElements.cpp b/DDCore/src/XML/XMLElements.cpp index d0ede732f..4f7bc1607 100644 --- a/DDCore/src/XML/XMLElements.cpp +++ b/DDCore/src/XML/XMLElements.cpp @@ -22,7 +22,7 @@ using namespace DD4hep::XML; static const size_t INVALID_NODE = ~0U; // Forward declarations -namespace DD4hep { +namespace DD4hep { XmlTools::Evaluator& evaluator(); } // Static storage @@ -49,33 +49,33 @@ namespace { #define setNodeValue SetValue #define getParentNode Parent()->ToElement #define getAttributeNode(x) AttributeNode(x) -#define appendChild LinkEndChild -#define getOwnerDocument GetDocument +#define appendChild LinkEndChild +#define getOwnerDocument GetDocument #define getDocumentElement RootElement -union Xml { +union Xml { Xml(const void* ptr) : p(ptr) {} - const void* p; - TiXmlNode* n; - TiXmlElement* e; + const void* p; + TiXmlNode* n; + TiXmlElement* e; TiXmlAttribute* a; - TiXmlDocument* d; - XmlElement* xe; + TiXmlDocument* d; + XmlElement* xe; }; namespace { - XmlElement* node_first(XmlElement* e, const XmlChar* t) { + XmlElement* node_first(XmlElement* e, const XmlChar* t) { return e ? (XmlElement*)_E(e)->FirstChildElement(t) : 0; } - size_t node_count(XmlElement* elt, const XmlChar* t) { + size_t node_count(XmlElement* elt, const XmlChar* t) { size_t cnt = 0; TiXmlElement* e = Xml(elt).e; for(e=e->FirstChildElement(t);e; e=e->NextSiblingElement(t)) ++cnt; return cnt; } } -XmlChar* DD4hep::XML::XmlString::replicate(const XmlChar* c) { return c ? ::strdup(c) : 0; } -XmlChar* DD4hep::XML::XmlString::transcode(const char* c) { return c ? ::strdup(c) : 0; } -void DD4hep::XML::XmlString::release(char** p) { if(p && *p) { ::free(*p); *p=0;} } +XmlChar* DD4hep::XML::XmlString::replicate(const XmlChar* c) {return c ? ::strdup(c) : 0;} +XmlChar* DD4hep::XML::XmlString::transcode(const char* c) {return c ? ::strdup(c) : 0;} +void DD4hep::XML::XmlString::release(char** p) {if(p && *p) {::free(*p); *p=0;}} #else #include "xercesc/util/XMLString.hpp" @@ -84,240 +84,297 @@ void DD4hep::XML::XmlString::release(char** p) { if(p && *p) { : #include "xercesc/dom/DOMNodeList.hpp" #include "xercesc/dom/DOM.hpp" #define ELEMENT_NODE_TYPE xercesc::DOMNode::ELEMENT_NODE -union Xml { - Xml(const void* ptr) : p(ptr) {} - const void* p; - xercesc::DOMNode* n; - xercesc::DOMAttr* a; - xercesc::DOMElement* e; +union Xml { + Xml(const void* ptr) + : p(ptr) { + } + const void* p; + xercesc::DOMNode* n; + xercesc::DOMAttr* a; + xercesc::DOMElement* e; xercesc::DOMDocument* d; xercesc::DOMNodeList* l; - XmlElement* xe; + XmlElement* xe; }; -XmlChar* DD4hep::XML::XmlString::replicate(const XmlChar* c) { return xercesc::XMLString::replicate(c); } -char* DD4hep::XML::XmlString::transcode(const XmlChar* c) { return xercesc::XMLString::transcode(c); } -XmlChar* DD4hep::XML::XmlString::transcode(const char* c) { return xercesc::XMLString::transcode(c); } -void DD4hep::XML::XmlString::release(XmlChar** p) { return xercesc::XMLString::release(p); } -void DD4hep::XML::XmlString::release(char** p) { return xercesc::XMLString::release(p); } +XmlChar* DD4hep::XML::XmlString::replicate(const XmlChar* c) { + return xercesc::XMLString::replicate(c); +} +char* DD4hep::XML::XmlString::transcode(const XmlChar* c) { + return xercesc::XMLString::transcode(c); +} +XmlChar* DD4hep::XML::XmlString::transcode(const char* c) { + return xercesc::XMLString::transcode(c); +} +void DD4hep::XML::XmlString::release(XmlChar** p) { + return xercesc::XMLString::release(p); +} +void DD4hep::XML::XmlString::release(char** p) { + return xercesc::XMLString::release(p); +} namespace { - size_t node_count(XmlElement* e, const XmlChar* t) { + size_t node_count(XmlElement* e, const XmlChar* t) { xercesc::DOMNodeList* l = e ? Xml(e).e->getElementsByTagName(t) : 0; - return l ? l->getLength() : INVALID_NODE; + return l ? l->getLength() : INVALID_NODE; } - XmlElement* node_first(XmlElement* e, const XmlChar* t) { + XmlElement* node_first(XmlElement* e, const XmlChar* t) { xercesc::DOMNodeList* l = e ? Xml(e).e->getElementsByTagName(t) : 0; return Xml(l ? l->item(0) : 0).xe; } } -string DD4hep::XML::_toString(const XmlChar *toTranscode) { +string DD4hep::XML::_toString(const XmlChar *toTranscode) { char *buff = XmlString::transcode(toTranscode); - string tmp(buff==0 ? "" : buff); + string tmp(buff == 0 ? "" : buff); XmlString::release(&buff); return tmp; } #endif namespace { - Attribute attribute_node(XmlElement* n, const XmlChar* t) { return Attribute(_E(n)->getAttributeNode(t)); } - const XmlChar* attribute_value(Attribute a) { return Xml(a).a->getValue(); } - int node_type(XmlNode* n) { return Xml(n).n->getNodeType(); } - int node_type(Handle_t n) { return Xml(n.ptr()).n->getNodeType(); } + Attribute attribute_node(XmlElement* n, const XmlChar* t) { + return Attribute(_E(n)->getAttributeNode(t)); + } + const XmlChar* attribute_value(Attribute a) { + return Xml(a).a->getValue(); + } + int node_type(XmlNode* n) { + return Xml(n).n->getNodeType(); + } + int node_type(Handle_t n) { + return Xml(n.ptr()).n->getNodeType(); + } } -string DD4hep::XML::_toString(Attribute attr) { - if ( attr ) return _toString(attribute_value(attr)); +string DD4hep::XML::_toString(Attribute attr) { + if (attr) + return _toString(attribute_value(attr)); return ""; } -template <typename T> static inline string __to_string(T value, const char* fmt) { +template <typename T> static inline string __to_string(T value, const char* fmt) { char text[128]; - ::snprintf(text,sizeof(text),fmt,value); + ::snprintf(text, sizeof(text), fmt, value); return text; } /// Do-nothing version. Present for completeness and argument interchangeability -std::string DD4hep::XML::_toString(const char* s) { return string(s ? s : ""); } +std::string DD4hep::XML::_toString(const char* s) { + return string(s ? s : ""); +} /// Do-nothing version. Present for completeness and argument interchangeability -std::string DD4hep::XML::_toString(const std::string& s) { return s; } +std::string DD4hep::XML::_toString(const std::string& s) { + return s; +} /// Format unsigned long integer to string with atrbitrary format -string DD4hep::XML::_toString(unsigned long v,const char* fmt) { return __to_string(v,fmt); } +string DD4hep::XML::_toString(unsigned long v, const char* fmt) { + return __to_string(v, fmt); +} /// Format unsigned integer (32 bits) to string with atrbitrary format -string DD4hep::XML::_toString(unsigned int v, const char* fmt) { return __to_string(v,fmt); } +string DD4hep::XML::_toString(unsigned int v, const char* fmt) { + return __to_string(v, fmt); +} /// Format signed integer (32 bits) to string with atrbitrary format -string DD4hep::XML::_toString(int v, const char* fmt) { return __to_string(v,fmt); } +string DD4hep::XML::_toString(int v, const char* fmt) { + return __to_string(v, fmt); +} /// Format single procision float number (32 bits) to string with atrbitrary format -string DD4hep::XML::_toString(float v, const char* fmt) { return __to_string(v,fmt); } +string DD4hep::XML::_toString(float v, const char* fmt) { + return __to_string(v, fmt); +} /// Format double procision float number (64 bits) to string with atrbitrary format -string DD4hep::XML::_toString(double v, const char* fmt) { return __to_string(v,fmt); } +string DD4hep::XML::_toString(double v, const char* fmt) { + return __to_string(v, fmt); +} -int DD4hep::XML::_toInt(const XmlChar* value) { - if ( value ) { +int DD4hep::XML::_toInt(const XmlChar* value) { + if (value) { string s = _toString(value); size_t idx = s.find("(int)"); - if ( idx != string::npos ) - s.erase(idx,5); - while(s[0]==' ')s.erase(0,1); + if (idx != string::npos) + s.erase(idx, 5); + while (s[0] == ' ') + s.erase(0, 1); double result = eval.evaluate(s.c_str()); if (eval.status() != XmlTools::Evaluator::OK) { cerr << s << ": "; eval.print_error(); - throw runtime_error("DD4hep: Severe error during expression evaluation of "+s); + throw runtime_error("DD4hep: Severe error during expression evaluation of " + s); } - return (int)result; + return (int) result; } return -1; } -bool DD4hep::XML::_toBool(const XmlChar* value) { - if ( value ) { +bool DD4hep::XML::_toBool(const XmlChar* value) { + if (value) { string s = _toString(value); return s == "true"; } return false; } -float DD4hep::XML::_toFloat(const XmlChar* value) { - if ( value ) { +float DD4hep::XML::_toFloat(const XmlChar* value) { + if (value) { string s = _toString(value); double result = eval.evaluate(s.c_str()); if (eval.status() != XmlTools::Evaluator::OK) { cerr << s << ": "; eval.print_error(); - throw runtime_error("DD4hep: Severe error during expression evaluation of "+s); + throw runtime_error("DD4hep: Severe error during expression evaluation of " + s); } - return (float)result; + return (float) result; } return 0.0; } -double DD4hep::XML::_toDouble(const XmlChar* value) { - if ( value ) { +double DD4hep::XML::_toDouble(const XmlChar* value) { + if (value) { string s = _toString(value); double result = eval.evaluate(s.c_str()); if (eval.status() != XmlTools::Evaluator::OK) { cerr << s << ": "; eval.print_error(); - throw runtime_error("DD4hep: Severe error during expression evaluation of "+s); + throw runtime_error("DD4hep: Severe error during expression evaluation of " + s); } return result; } return 0.0; } -void DD4hep::XML::_toDictionary(const XmlChar* name, const XmlChar* value) { - string n=_toString(name).c_str(), v=_toString(value); +void DD4hep::XML::_toDictionary(const XmlChar* name, const XmlChar* value) { + string n = _toString(name).c_str(), v = _toString(value); size_t idx = v.find("(int)"); - if ( idx != string::npos ) - v.erase(idx,5); - while(v[0]==' ')v.erase(0,1); + if (idx != string::npos) + v.erase(idx, 5); + while (v[0] == ' ') + v.erase(0, 1); double result = eval.evaluate(v.c_str()); if (eval.status() != XmlTools::Evaluator::OK) { cerr << v << ": "; eval.print_error(); - throw runtime_error("DD4hep: Severe error during expression evaluation of "+v); + throw runtime_error("DD4hep: Severe error during expression evaluation of " + v); } - eval.setVariable(n.c_str(),result); + eval.setVariable(n.c_str(), result); } -template <typename B> -static inline string i_add(const string& a, B b) { - string r=a; +template <typename B> +static inline string i_add(const string& a, B b) { + string r = a; r += b; return r; } -Strng_t DD4hep::XML::operator+(const Strng_t& a, const string& b) -{ return _toString(a.ptr()) + b; } +Strng_t DD4hep::XML::operator+(const Strng_t& a, const string& b) { + return _toString(a.ptr()) + b; +} -Strng_t DD4hep::XML::operator+(const string& a, const Strng_t& b) -{ return a + _toString(b.ptr()); } +Strng_t DD4hep::XML::operator+(const string& a, const Strng_t& b) { + return a + _toString(b.ptr()); +} -Strng_t DD4hep::XML::operator+(const Strng_t& a, const char* b) -{ return _toString(a.ptr()) + b; } +Strng_t DD4hep::XML::operator+(const Strng_t& a, const char* b) { + return _toString(a.ptr()) + b; +} -Strng_t DD4hep::XML::operator+(const char* a, const Strng_t& b) -{ return string(a) + _toString(b.ptr()); } +Strng_t DD4hep::XML::operator+(const char* a, const Strng_t& b) { + return string(a) + _toString(b.ptr()); +} -Strng_t DD4hep::XML::operator+(const Strng_t& a, const Strng_t& b) -{ return _toString(a.ptr()) + _toString(b.ptr()); } +Strng_t DD4hep::XML::operator+(const Strng_t& a, const Strng_t& b) { + return _toString(a.ptr()) + _toString(b.ptr()); +} -Tag_t DD4hep::XML::operator+(const Tag_t& a, const char* b) -{ return a.str() + b; } +Tag_t DD4hep::XML::operator+(const Tag_t& a, const char* b) { + return a.str() + b; +} -Tag_t DD4hep::XML::operator+(const char* a, const Tag_t& b) -{ return a + b.str(); } +Tag_t DD4hep::XML::operator+(const char* a, const Tag_t& b) { + return a + b.str(); +} -Tag_t DD4hep::XML::operator+(const Tag_t& a, const Strng_t& b) -{ return a.str() + _toString(b); } +Tag_t DD4hep::XML::operator+(const Tag_t& a, const Strng_t& b) { + return a.str() + _toString(b); +} -Tag_t DD4hep::XML::operator+(const Tag_t& a, const string& b) -{ return a.str() + b; } +Tag_t DD4hep::XML::operator+(const Tag_t& a, const string& b) { + return a.str() + b; +} #ifndef DD4HEP_USE_TINYXML -Strng_t DD4hep::XML::operator+(const Strng_t& a, const XmlChar* b) -{ return _toString(a.ptr()) + _toString(b); } +Strng_t DD4hep::XML::operator+(const Strng_t& a, const XmlChar* b) { + return _toString(a.ptr()) + _toString(b); +} -Strng_t DD4hep::XML::operator+(const XmlChar* a, const Strng_t& b) -{ return _toString(a) + _toString(b.ptr()); } +Strng_t DD4hep::XML::operator+(const XmlChar* a, const Strng_t& b) { + return _toString(a) + _toString(b.ptr()); +} -Strng_t DD4hep::XML::operator+(const XmlChar* a, const string& b) -{ return _toString(a) + b; } +Strng_t DD4hep::XML::operator+(const XmlChar* a, const string& b) { + return _toString(a) + b; +} -Strng_t DD4hep::XML::operator+(const string& a, const XmlChar* b) -{ return a + _toString(b); } +Strng_t DD4hep::XML::operator+(const string& a, const XmlChar* b) { + return a + _toString(b); +} -Tag_t DD4hep::XML::operator+(const Tag_t& a, const XmlChar* b) -{ return a.str() + _toString(b); } +Tag_t DD4hep::XML::operator+(const Tag_t& a, const XmlChar* b) { + return a.str() + _toString(b); +} -Strng_t& Strng_t::operator=(const XmlChar* s) { - if (m_xml) XmlString::release(&m_xml); +Strng_t& Strng_t::operator=(const XmlChar* s) { + if (m_xml) + XmlString::release (&m_xml); m_xml = s ? XmlString::replicate(s) : 0; return *this; } #endif -Strng_t& Strng_t::operator=(const char* s) { - if (m_xml) XmlString::release(&m_xml); +Strng_t& Strng_t::operator=(const char* s) { + if (m_xml) + XmlString::release (&m_xml); m_xml = s ? XmlString::transcode(s) : 0; return *this; } -Strng_t& Strng_t::operator=(const Strng_t& s) { - if ( this != &s ) { - if (m_xml) XmlString::release(&m_xml); +Strng_t& Strng_t::operator=(const Strng_t& s) { + if (this != &s) { + if (m_xml) + XmlString::release (&m_xml); m_xml = XmlString::replicate(s.m_xml); } return *this; } -Strng_t& Strng_t::operator=(const string& s) { - if (m_xml) XmlString::release(&m_xml); +Strng_t& Strng_t::operator=(const string& s) { + if (m_xml) + XmlString::release (&m_xml); m_xml = XmlString::transcode(s.c_str()); return *this; } -Tag_t& Tag_t::operator=(const Tag_t& s) { - if ( this != &s ) { +Tag_t& Tag_t::operator=(const Tag_t& s) { + if (this != &s) { m_str = s.m_str; - if (m_xml) XmlString::release(&m_xml); + if (m_xml) + XmlString::release (&m_xml); m_xml = XmlString::transcode(m_str.c_str()); } return *this; } Tag_t& Tag_t::operator=(const char* s) { - if (m_xml) XmlString::release(&m_xml); - if ( s ) { - m_xml=XmlString::transcode(s); + if (m_xml) + XmlString::release (&m_xml); + if (s) { + m_xml = XmlString::transcode(s); m_str = s; } else { @@ -327,15 +384,17 @@ Tag_t& Tag_t::operator=(const char* s) { return *this; } -Tag_t& Tag_t::operator=(const Strng_t& s) { - if (m_xml) XmlString::release(&m_xml); +Tag_t& Tag_t::operator=(const Strng_t& s) { + if (m_xml) + XmlString::release (&m_xml); m_str = s.m_xml ? XmlString::transcode(s.m_xml) : ""; m_xml = XmlString::transcode(m_str.c_str()); return *this; } Tag_t& Tag_t::operator=(const string& s) { - if (m_xml) XmlString::release(&m_xml); + if (m_xml) + XmlString::release (&m_xml); m_xml = XmlString::transcode(s.c_str()); m_str = s; return *this; @@ -343,20 +402,20 @@ Tag_t& Tag_t::operator=(const string& s) { /// Copy constructor NodeList::NodeList(const NodeList& copy) - : m_node(copy.m_node), m_ptr(0) + : m_node(copy.m_node), m_ptr(0) #ifndef DD4HEP_USE_TINYXML -, m_index(0) + , m_index(0) #endif { - m_tag = XmlString::replicate(copy.m_tag); + m_tag = XmlString::replicate(copy.m_tag); reset(); } /// Initializing constructor NodeList::NodeList(XmlElement* node, const XmlChar* tag) - : m_node(node), m_ptr(0) + : m_node(node), m_ptr(0) #ifndef DD4HEP_USE_TINYXML -, m_index(0) + , m_index(0) #endif { m_tag = XmlString::replicate(tag); @@ -364,8 +423,9 @@ NodeList::NodeList(XmlElement* node, const XmlChar* tag) } /// Default destructor -NodeList::~NodeList() { - if ( m_tag ) XmlString::release(&m_tag); +NodeList::~NodeList() { + if (m_tag) + XmlString::release (&m_tag); } /// Reset the nodelist @@ -374,13 +434,13 @@ XmlElement* NodeList::reset() { return m_ptr=node_first(m_node,m_tag); #else xercesc::DOMNodeList* l = Xml(m_node).e->getElementsByTagName(m_tag); - m_ptr = (XmlNodeList*)l; + m_ptr = (XmlNodeList*) l; return _XE(l->item(m_index=0)); #endif } /// Advance to next element -XmlElement* NodeList::next() const { +XmlElement* NodeList::next() const { #ifdef DD4HEP_USE_TINYXML return m_ptr = _XE(m_ptr ? _E(m_ptr)->NextSiblingElement(m_tag) : 0); #else @@ -389,7 +449,7 @@ XmlElement* NodeList::next() const { } /// Go back to previous element -XmlElement* NodeList::previous() const { +XmlElement* NodeList::previous() const { #ifdef DD4HEP_USE_TINYXML return m_ptr = _XE(m_ptr ? _E(m_ptr)->PreviousSiblingElement(m_tag) : 0); #else @@ -399,8 +459,9 @@ XmlElement* NodeList::previous() const { /// Assignment operator NodeList& NodeList::operator=(const NodeList& l) { - if ( this != &l ) { - if ( m_tag ) XmlString::release(&m_tag); + if (this != &l) { + if (m_tag) + XmlString::release (&m_tag); m_tag = XmlString::replicate(l.m_tag); m_node = l.m_node; reset(); @@ -409,23 +470,23 @@ NodeList& NodeList::operator=(const NodeList& l) { } /// Unicode text access to the element's tag. Tis must be wrong .... -const XmlChar* Handle_t::rawTag() const { +const XmlChar* Handle_t::rawTag() const { return _E(m_node)->getTagName(); } /// Unicode text access to the element's text -const XmlChar* Handle_t::rawText() const { +const XmlChar* Handle_t::rawText() const { return _E(m_node)->getTextContent(); } /// Unicode text access to the element's value -const XmlChar* Handle_t::rawValue() const { +const XmlChar* Handle_t::rawValue() const { return _N(m_node)->getNodeValue(); } /// Clone the DOMelement - with the option of a deep copy -Handle_t Handle_t::clone(XmlDocument* new_doc) const { - if ( m_node ) { +Handle_t Handle_t::clone(XmlDocument* new_doc) const { + if (m_node) { #ifdef DD4HEP_USE_TINYXML if ( new_doc ) {} if ( _N(m_node)->Type() == ELEMENT_NODE_TYPE ) { @@ -434,37 +495,37 @@ Handle_t Handle_t::clone(XmlDocument* new_doc) const { } throw runtime_error("TiXml: Handle_t::clone: Invalid source handle type [No element type]."); #else - return Elt_t(_D(new_doc)->importNode(_E(m_node),true)); + return Elt_t(_D(new_doc)->importNode(_E(m_node), true)); #endif } throw runtime_error("Xml: Handle_t::clone: Invalid source handle."); } /// Access the element's parent element -Handle_t Handle_t::parent() const { +Handle_t Handle_t::parent() const { return Elt_t(m_node ? _N(m_node)->getParentNode() : 0); } /// Access attribute pointer by the attribute's unicode name (no exception thrown if not present) -Attribute Handle_t::attr_nothrow(const XmlChar* tag) const { - return attribute_node(m_node,tag); +Attribute Handle_t::attr_nothrow(const XmlChar* tag) const { + return attribute_node(m_node, tag); } /// Check for the existence of a named attribute -bool Handle_t::hasAttr(const XmlChar* tag) const { +bool Handle_t::hasAttr(const XmlChar* tag) const { return m_node && 0 != _E(m_node)->getAttributeNode(tag); } /// Retrieve a collection of all attributes of this DOM element vector<Attribute> Handle_t::attributes() const { - vector<Attribute> attrs; - if ( m_node ) { + vector < Attribute > attrs; + if (m_node) { #ifdef DD4HEP_USE_TINYXML for(TiXmlAttribute* a=_E(m_node)->FirstAttribute(); a; a=a->Next()) - attrs.push_back(Attribute(a)); + attrs.push_back(Attribute(a)); #else xercesc::DOMNamedNodeMap* l = _E(m_node)->getAttributes(); - for(XmlSize_t i=0, n=l->getLength(); i<n; ++i) { + for (XmlSize_t i = 0, n = l->getLength(); i < n; ++i) { xercesc::DOMNode* attr_node = l->item(i); attrs.push_back(Attribute(attr_node)); } @@ -473,82 +534,86 @@ vector<Attribute> Handle_t::attributes() const { return attrs; } -size_t Handle_t::numChildren(const XmlChar* t, bool throw_exception) const { - size_t n = node_count(m_node,t); - if ( n == INVALID_NODE && !throw_exception ) return 0; - else if ( n != INVALID_NODE ) return n; +size_t Handle_t::numChildren(const XmlChar* t, bool throw_exception) const { + size_t n = node_count(m_node, t); + if (n == INVALID_NODE && !throw_exception) + return 0; + else if (n != INVALID_NODE) + return n; string msg = "Handle_t::numChildren: "; - if ( m_node ) - msg += "Element ["+tag()+"] has no children of type '"+_toString(t)+"'"; + if (m_node) + msg += "Element [" + tag() + "] has no children of type '" + _toString(t) + "'"; else - msg += "Element [INVALID] has no children of type '"+_toString(t)+"'"; + msg += "Element [INVALID] has no children of type '" + _toString(t) + "'"; throw runtime_error(msg); } /// Remove a single child node identified by it's handle from the tree of the element -Handle_t Handle_t::child(const XmlChar* t, bool throw_exception) const { - Elt_t e = node_first(m_node,t); - if ( e || !throw_exception ) return e; +Handle_t Handle_t::child(const XmlChar* t, bool throw_exception) const { + Elt_t e = node_first(m_node, t); + if (e || !throw_exception) + return e; string msg = "Handle_t::child: "; - if ( m_node ) - msg += "Element ["+tag()+"] has no child of type '"+_toString(t)+"'"; + if (m_node) + msg += "Element [" + tag() + "] has no child of type '" + _toString(t) + "'"; else - msg += "Element [INVALID]. Cannot remove child of type: '"+_toString(t)+"'"; + msg += "Element [INVALID]. Cannot remove child of type: '" + _toString(t) + "'"; throw runtime_error(msg); } NodeList Handle_t::children(const XmlChar* tag) const { - return NodeList(m_node,tag); + return NodeList(m_node, tag); } /// Append a DOM element to the current node -void Handle_t::append(Handle_t e) const { +void Handle_t::append(Handle_t e) const { _N(m_node)->appendChild(_N(e.ptr())); } /// Remove a single child node identified by it's handle from the tree of the element -Handle_t Handle_t::remove(Handle_t node) const { +Handle_t Handle_t::remove(Handle_t node) const { #ifdef DD4HEP_USE_TINYXML - bool e = (m_node && node.ptr() ? _N(m_node)->RemoveChild(_N(node.ptr())) : false); + bool e = (m_node && node.ptr() ? _N(m_node)->RemoveChild(_N(node.ptr())) : false); #else - Elt_t e = Elt_t(m_node && node.ptr() ? _N(m_node)->removeChild(_N(node.ptr())) : 0); + Elt_t e = Elt_t(m_node && node.ptr() ? _N(m_node)->removeChild(_N(node.ptr())) : 0); #endif - if ( e ) return node.ptr(); + if (e) + return node.ptr(); string msg = "Handle_t::remove: "; - if ( m_node && node.ptr() ) - msg += "Element ["+tag()+"] has no child of type '"+node.tag()+"'"; - else if ( node ) - msg += "Element [INVALID]. Cannot remove child of type: '"+node.tag()+"'"; - else if ( node ) + if (m_node && node.ptr()) + msg += "Element [" + tag() + "] has no child of type '" + node.tag() + "'"; + else if (node) + msg += "Element [INVALID]. Cannot remove child of type: '" + node.tag() + "'"; + else if (node) msg += "Element [INVALID]. Cannot remove [INVALID] child. Big Shit!!!!"; throw runtime_error(msg); } /// Remove children with a given tag name from the DOM node -void Handle_t::removeChildren(const XmlChar* tag) const { +void Handle_t::removeChildren(const XmlChar* tag) const { #ifdef DD4HEP_USE_TINYXML for(TiXmlNode* n=_E(m_node)->FirstChildElement(tag);n;n=_E(m_node)->FirstChildElement(tag)) - n->RemoveChild(n); + n->RemoveChild(n); #else - xercesc::DOMElement* e = _E(m_node); + xercesc::DOMElement* e = _E(m_node); xercesc::DOMNodeList* l = e->getElementsByTagName(tag); - for(XmlSize_t i=0, n=l->getLength(); i<n; ++i) + for (XmlSize_t i = 0, n = l->getLength(); i < n; ++i) e->removeChild(l->item(i)); #endif } -bool Handle_t::hasChild(const XmlChar* tag) const { - return node_first(m_node,tag) != 0; +bool Handle_t::hasChild(const XmlChar* tag) const { + return node_first(m_node, tag) != 0; } /// Set the element's value -void Handle_t::setValue(const XmlChar* text) const { +void Handle_t::setValue(const XmlChar* text) const { _N(m_node)->setNodeValue(text); } /// Set the element's value -void Handle_t::setValue(const string& text) const { +void Handle_t::setValue(const string& text) const { #ifdef DD4HEP_USE_TINYXML _N(m_node)->setNodeValue(text.c_str()); #else @@ -557,7 +622,7 @@ void Handle_t::setValue(const string& text) const { } /// Set the element's text -void Handle_t::setText(const XmlChar* text) const { +void Handle_t::setText(const XmlChar* text) const { #ifdef DD4HEP_USE_TINYXML _N(m_node)->LinkEndChild(new TiXmlText(text)); #else @@ -566,7 +631,7 @@ void Handle_t::setText(const XmlChar* text) const { } /// Set the element's text -void Handle_t::setText(const string& text) const { +void Handle_t::setText(const string& text) const { #ifdef DD4HEP_USE_TINYXML _N(m_node)->LinkEndChild(new TiXmlText(text.c_str())); #else @@ -575,129 +640,130 @@ void Handle_t::setText(const string& text) const { } /// Remove all attributes of this element -void Handle_t::removeAttrs() const { +void Handle_t::removeAttrs() const { #ifdef DD4HEP_USE_TINYXML _E(m_node)->ClearAttributes(); #else - xercesc::DOMElement* e = _E(m_node); + xercesc::DOMElement* e = _E(m_node); xercesc::DOMNamedNodeMap* l = e->getAttributes(); - for(XmlSize_t i=0, n=l->getLength(); i<n; ++i) { - xercesc::DOMAttr* a = (xercesc::DOMAttr*)l->item(i); + for (XmlSize_t i = 0, n = l->getLength(); i < n; ++i) { + xercesc::DOMAttr* a = (xercesc::DOMAttr*) l->item(i); e->removeAttributeNode(a); } #endif } /// Set attributes as in argument handle -void Handle_t::setAttrs(Handle_t elt) const { +void Handle_t::setAttrs(Handle_t elt) const { removeAttrs(); #ifdef DD4HEP_USE_TINYXML TiXmlElement* e = Xml(elt).e; for(TiXmlAttribute* a=e->FirstAttribute(); a; a=a->Next()) - e->SetAttribute(a->Name(),a->Value()); + e->SetAttribute(a->Name(),a->Value()); #else - xercesc::DOMElement* e = _E(m_node); + xercesc::DOMElement* e = _E(m_node); xercesc::DOMNamedNodeMap* l = e->getAttributes(); - for(XmlSize_t i=0, len=l->getLength(); i<len; ++i) { + for (XmlSize_t i = 0, len = l->getLength(); i < len; ++i) { xercesc::DOMNode* n = l->item(i); - if ( n->getNodeType() == xercesc::DOMNode::ATTRIBUTE_NODE ) { - xercesc::DOMAttr* a = (xercesc::DOMAttr*)n; - e->setAttribute(a->getName(),a->getValue()); + if (n->getNodeType() == xercesc::DOMNode::ATTRIBUTE_NODE) { + xercesc::DOMAttr* a = (xercesc::DOMAttr*) n; + e->setAttribute(a->getName(), a->getValue()); } } #endif } /// Access attribute pointer by the attribute's unicode name (throws exception if not present) -Attribute Handle_t::attr_ptr(const XmlChar* t) const { - Attribute a = attribute_node(m_node,t); - if ( 0 != a ) return a; +Attribute Handle_t::attr_ptr(const XmlChar* t) const { + Attribute a = attribute_node(m_node, t); + if (0 != a) + return a; string msg = "Handle_t::attr_ptr: "; - if ( m_node ) - msg += "Element ["+tag()+"] has no attribute of type '"+_toString(t)+"'"; + if (m_node) + msg += "Element [" + tag() + "] has no attribute of type '" + _toString(t) + "'"; else - msg += "Element [INVALID] has no attribute of type '"+_toString(t)+"'"; + msg += "Element [INVALID] has no attribute of type '" + _toString(t) + "'"; throw runtime_error(msg); } /// Access attribute name (throws exception if not present) -const XmlChar* Handle_t::attr_name(const Attribute a) const { - if ( a ) { +const XmlChar* Handle_t::attr_name(const Attribute a) const { + if (a) { return Xml(a).a->getName(); } throw runtime_error("Attempt to access invalid XML attribute object!"); } /// Access attribute value by the attribute's unicode name (throws exception if not present) -const XmlChar* Handle_t::attr_value(const XmlChar* attr) const { +const XmlChar* Handle_t::attr_value(const XmlChar* attr) const { return attribute_value(attr_ptr(attr)); } /// Access attribute value by the attribute (throws exception if not present) -const XmlChar* Handle_t::attr_value(const Attribute attr) const { +const XmlChar* Handle_t::attr_value(const Attribute attr) const { return attribute_value(attr); } /// Access attribute value by the attribute's unicode name (no exception thrown if not present) -const XmlChar* Handle_t::attr_value_nothrow(const XmlChar* attr) const { +const XmlChar* Handle_t::attr_value_nothrow(const XmlChar* attr) const { Attribute a = attr_nothrow(attr); return a ? attribute_value(a) : 0; } /// Generic attribute setter with integer value -Attribute Handle_t::setAttr(const XmlChar* name, int val) const { +Attribute Handle_t::setAttr(const XmlChar* name, int val) const { char txt[32]; - ::snprintf(txt,sizeof(txt),"%d",val); + ::snprintf(txt, sizeof(txt), "%d", val); return setAttr(name, Strng_t(txt)); } /// Generic attribute setter with boolen value -Attribute Handle_t::setAttr(const XmlChar* name, bool val) const { +Attribute Handle_t::setAttr(const XmlChar* name, bool val) const { char txt[32]; - ::snprintf(txt,sizeof(txt),"%s",val ? "true" : "false"); + ::snprintf(txt, sizeof(txt), "%s", val ? "true" : "false"); return setAttr(name, Strng_t(txt)); } /// Generic attribute setter with floating point value -Attribute Handle_t::setAttr(const XmlChar* name, float val) const { +Attribute Handle_t::setAttr(const XmlChar* name, float val) const { char txt[32]; - ::snprintf(txt,sizeof(txt),"%f",val); + ::snprintf(txt, sizeof(txt), "%f", val); return setAttr(name, Strng_t(txt)); } /// Generic attribute setter with double precision floating point value -Attribute Handle_t::setAttr(const XmlChar* name, double val) const { +Attribute Handle_t::setAttr(const XmlChar* name, double val) const { char txt[32]; - ::snprintf(txt,sizeof(txt),"%f",val); + ::snprintf(txt, sizeof(txt), "%f", val); return setAttr(name, Strng_t(txt)); } /// Generic attribute setter with string value -Attribute Handle_t::setAttr(const XmlChar* name, const string& val) const { +Attribute Handle_t::setAttr(const XmlChar* name, const string& val) const { return setAttr(name, Strng_t(val.c_str())); } #ifndef DD4HEP_USE_TINYXML -Attribute Handle_t::setAttr(const XmlChar* name, const char* v) const { +Attribute Handle_t::setAttr(const XmlChar* name, const char* v) const { return setAttr(name, Strng_t(v)); } #endif /// Generic attribute setter with XmlAttr value -Attribute Handle_t::setAttr(const XmlChar* name, const Attribute v) const { - return v ? setAttr(name,attribute_value(v)) : 0; +Attribute Handle_t::setAttr(const XmlChar* name, const Attribute v) const { + return v ? setAttr(name, attribute_value(v)) : 0; } /// Generic attribute setter with unicode value -Attribute Handle_t::setAttr(const XmlChar* name, const XmlChar* value) const { +Attribute Handle_t::setAttr(const XmlChar* name, const XmlChar* value) const { #ifdef DD4HEP_USE_TINYXML TiXmlElement* e = Xml(m_node).e; e->SetAttribute(name,value); return Attribute(e->AttributeNode(name)); #else xercesc::DOMElement* e = _E(m_node); - xercesc::DOMAttr* a = e->getAttributeNode(name); - if ( !a ) { + xercesc::DOMAttr* a = e->getAttributeNode(name); + if (!a) { a = e->getOwnerDocument()->createAttribute(name); e->setAttributeNode(a); } @@ -709,46 +775,48 @@ Attribute Handle_t::setAttr(const XmlChar* name, const XmlChar* value) const { /// Add reference child as a new child node. The obj must have the "name" attribute! Handle_t Handle_t::setRef(const XmlChar* tag, const XmlChar* ref_name) { Element me(*this); - Element ref(me.document(),tag); - ref.setAttr(Unicode_ref,ref_name); + Element ref(me.document(), tag); + ref.setAttr(Unicode_ref, ref_name); me.append(ref); return ref; } /// Add reference child as a new child node. The obj must have the "name" attribute! Handle_t Handle_t::setRef(const XmlChar* tag, const string& ref_name) { - return setRef(tag,Strng_t(ref_name).ptr()); + return setRef(tag, Strng_t(ref_name).ptr()); } /// Checksum (sub-)tree of a xml document/tree -static unsigned int adler32(unsigned int adler,const char* buf,size_t len) { +static unsigned int adler32(unsigned int adler, const char* buf, size_t len) { #define DO1(buf,i) {s1 +=(unsigned char)buf[i]; s2 += s1;} #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1); #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2); #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4); #define DO16(buf) DO8(buf,0); DO8(buf,8); - static const unsigned int BASE = 65521; /* largest prime smaller than 65536 */ + static const unsigned int BASE = 65521; /* largest prime smaller than 65536 */ /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */ static const unsigned int NMAX = 5550; unsigned int s1 = adler & 0xffff; unsigned int s2 = (adler >> 16) & 0xffff; int k; - if (buf == NULL) return 1; + if (buf == NULL) + return 1; while (len > 0) { - k = len < NMAX ? (int)len : NMAX; + k = len < NMAX ? (int) len : NMAX; len -= k; while (k >= 16) { DO16(buf); buf += 16; k -= 16; } - if (k != 0) do { - s1 += (unsigned char)*buf++; - s2 += s1; - } while (--k); + if (k != 0) + do { + s1 += (unsigned char) *buf++; + s2 += s1; + } while (--k); s1 %= BASE; s2 %= BASE; } @@ -757,37 +825,37 @@ static unsigned int adler32(unsigned int adler,const char* buf,size_t len) { } /// Checksum (sub-)tree of a xml document/tree -unsigned int Handle_t::checksum(unsigned int param,unsigned int (fcn)(unsigned int,const XmlChar*,size_t)) const { - typedef std::map<std::string,std::string> StringMap; +unsigned int Handle_t::checksum(unsigned int param, unsigned int (fcn)(unsigned int, const XmlChar*, size_t)) const { + typedef std::map<std::string, std::string> StringMap; #ifdef DD4HEP_USE_TINYXML TiXmlNode* n = Xml(m_node).n; - if ( n ) { + if ( n ) { if ( 0 == fcn ) fcn = adler32; - switch (n->Type()) { - case TiXmlNode::ELEMENT: { - map<string,string> m; - TiXmlElement* e = n->ToElement(); - TiXmlAttribute* p=e->FirstAttribute(); - for(; p; p=p->Next()) m.insert(make_pair(p->Name(),p->Value())); - param = (*fcn)(param,e->Value(),::strlen(e->Value())); - for(StringMap::const_iterator i=m.begin();i!=m.end();++i) { - param = (*fcn)(param,(*i).first.c_str(),(*i).first.length()); - param = (*fcn)(param,(*i).second.c_str(),(*i).second.length()); + switch (n->Type()) { + case TiXmlNode::ELEMENT: { + map<string,string> m; + TiXmlElement* e = n->ToElement(); + TiXmlAttribute* p=e->FirstAttribute(); + for(; p; p=p->Next()) m.insert(make_pair(p->Name(),p->Value())); + param = (*fcn)(param,e->Value(),::strlen(e->Value())); + for(StringMap::const_iterator i=m.begin();i!=m.end();++i) { + param = (*fcn)(param,(*i).first.c_str(),(*i).first.length()); + param = (*fcn)(param,(*i).second.c_str(),(*i).second.length()); + } + break; } - break; - } - case TiXmlNode::TEXT: + case TiXmlNode::TEXT: param = (*fcn)(param,n->ToText()->Value(),::strlen(n->ToText()->Value())); break; - case TiXmlNode::UNKNOWN: - case TiXmlNode::COMMENT: - case TiXmlNode::DOCUMENT: - case TiXmlNode::DECLARATION: - default: + case TiXmlNode::UNKNOWN: + case TiXmlNode::COMMENT: + case TiXmlNode::DOCUMENT: + case TiXmlNode::DECLARATION: + default: break; } for(TiXmlNode* c=n->FirstChild(); c; c=c->NextSibling()) - param = Handle_t((XmlElement*)c->ToElement()).checksum(param,fcn); + param = Handle_t((XmlElement*)c->ToElement()).checksum(param,fcn); } #else @@ -796,7 +864,7 @@ unsigned int Handle_t::checksum(unsigned int param,unsigned int (fcn)(unsigned i } /// Create DOM element -Handle_t Document::createElt(const XmlChar* tag) const { +Handle_t Document::createElt(const XmlChar* tag) const { #ifdef DD4HEP_USE_TINYXML return _XE(new TiXmlElement(tag)); #else @@ -805,68 +873,70 @@ Handle_t Document::createElt(const XmlChar* tag) const { } /// Access the ROOT eleemnt of the DOM document -Handle_t Document::root() const { - if ( m_doc ) return _XE(_D(m_doc)->getDocumentElement()); +Handle_t Document::root() const { + if (m_doc) + return _XE(_D(m_doc)->getDocumentElement()); throw runtime_error("Document::root: Invalid handle!"); } /// Standard destructor - releases the document -DocumentHolder::~DocumentHolder() { +DocumentHolder::~DocumentHolder() { #ifdef DD4HEP_USE_TINYXML if (m_doc) delete _D(m_doc); #else - if (m_doc) _D(m_doc)->release(); + if (m_doc) + _D(m_doc)->release(); #endif m_doc = 0; } /// Constructor from DOM document entity -Element::Element(const Document& document, const XmlChar* type) -: m_element(Xml(document.createElt(type)).xe) -{ } +Element::Element(const Document& document, const XmlChar* type) + : m_element(Xml(document.createElt(type)).xe) { +} /// Access the hosting document handle of this DOM element -Document Element::document() const { - return Document((XmlDocument*)(m_element ? _N(m_element)->getOwnerDocument() : 0)); +Document Element::document() const { + return Document((XmlDocument*) (m_element ? _N(m_element)->getOwnerDocument() : 0)); } /// Clone the DOM element tree -Handle_t Element::clone(Handle_t h) const { - if ( m_element && h ) { +Handle_t Element::clone(Handle_t h) const { + if (m_element && h) { return h.clone(Document::DOC(document())); } throw runtime_error("Element::clone: Invalid element pointer -- unable to clone node!"); } -Attribute Element::getAttr(const XmlChar* name) const { - return m_element ? attribute_node(m_element,name) : 0; +Attribute Element::getAttr(const XmlChar* name) const { + return m_element ? attribute_node(m_element, name) : 0; } /// Set the reference attribute to the node (adds attribute ref="ref-name") -Attribute Element::setRef(const XmlChar* tag, const XmlChar* ref_name) const { - return setChild(tag).setAttr(Unicode_ref,ref_name); +Attribute Element::setRef(const XmlChar* tag, const XmlChar* ref_name) const { + return setChild(tag).setAttr(Unicode_ref, ref_name); } /// Set the reference attribute to the node (adds attribute ref="ref-name") -Attribute Element::setRef(const XmlChar* tag, const string& ref_name) const { - return setRef(tag,Strng_t(ref_name).ptr()); +Attribute Element::setRef(const XmlChar* tag, const string& ref_name) const { + return setRef(tag, Strng_t(ref_name).ptr()); } /// Access the value of the reference attribute of the node (attribute ref="ref-name") -const XmlChar* Element::getRef(const XmlChar* tag) const { - return child(tag).attr<cpXmlChar>(Unicode_ref); +const XmlChar* Element::getRef(const XmlChar* tag) const { + return child(tag).attr < cpXmlChar > (Unicode_ref); } /// Add a new child to the DOM node -Handle_t Element::addChild(const XmlChar* tag) const { +Handle_t Element::addChild(const XmlChar* tag) const { Handle_t e = document().createElt(tag); m_element.append(e); return e; } /// Check if a child with the required tag exists - if not create it and add it to the current node -Handle_t Element::setChild(const XmlChar* t) const { - Elt_t e = m_element.child(t,false); +Handle_t Element::setChild(const XmlChar* t) const { + Elt_t e = m_element.child(t, false); return e ? Handle_t(e) : addChild(t); } @@ -880,117 +950,112 @@ void Element::addComment(const char* text) const { } /// Initializing constructor to create a new XMLElement and add it to the document. -RefElement::RefElement(const Document& document, const XmlChar* type, const XmlChar* name) -: Element(document, type) -{ - m_name = name ? setAttr(_U(name),name) : 0; +RefElement::RefElement(const Document& document, const XmlChar* type, const XmlChar* name) + : Element(document, type) { + m_name = name ? setAttr(_U(name), name) : 0; } /// Construction from existing object handle -RefElement::RefElement(const Handle_t& e) -: Element(e) -{ +RefElement::RefElement(const Handle_t& e) + : Element(e) { m_name = m_element ? getAttr(_U(name)) : 0; } /// Copy constructor -RefElement::RefElement(const RefElement& e) -: Element(e), m_name(e.m_name) -{ +RefElement::RefElement(const RefElement& e) + : Element(e), m_name(e.m_name) { } /// Assignment operator RefElement& RefElement::operator=(const RefElement& e) { - m_element = e.m_element; return *this; + m_element = e.m_element; + return *this; } -const XmlChar* RefElement::name() const { - if ( 0 == m_name ) cout << "Error:tag=" << m_element.tag() << endl; +const XmlChar* RefElement::name() const { + if (0 == m_name) + cout << "Error:tag=" << m_element.tag() << endl; return attribute_value(m_name); } -const XmlChar* RefElement::refName() const { - if ( 0 == m_name ) cout << "Error:tag=" << m_element.tag() << endl; +const XmlChar* RefElement::refName() const { + if (0 == m_name) + cout << "Error:tag=" << m_element.tag() << endl; return attribute_value(m_name); } -void RefElement::setName(const XmlChar* new_name) { - setAttr(_U(name),new_name); +void RefElement::setName(const XmlChar* new_name) { + setAttr(_U(name), new_name); } #ifndef DD4HEP_USE_TINYXML -Collection_t::Collection_t(Handle_t element, const XmlChar* tag) - : m_children(element,tag) -{ +Collection_t::Collection_t(Handle_t element, const XmlChar* tag) + : m_children(element, tag) { m_node = m_children.reset(); } #endif Collection_t::Collection_t(Handle_t element, const char* tag) - : m_children(element,Strng_t(tag)) -{ + : m_children(element, Strng_t(tag)) { m_node = m_children.reset(); } /// Constructor over XmlElements in a node list -Collection_t::Collection_t(NodeList node_list) - : m_children(node_list) -{ +Collection_t::Collection_t(NodeList node_list) + : m_children(node_list) { m_node = m_children.reset(); } /// Reset the collection object to restart the iteration -Collection_t& Collection_t::reset() { +Collection_t& Collection_t::reset() { m_node = m_children.reset(); return *this; } /// Access the collection size. Avoid this call -- sloooow! -size_t Collection_t::size() const { - return Handle_t(m_children.m_node).numChildren(m_children.m_tag,false); +size_t Collection_t::size() const { + return Handle_t(m_children.m_node).numChildren(m_children.m_tag, false); } /// Helper function to throw an exception -void Collection_t::throw_loop_exception(const std::exception& e) const { - if ( m_node ) { - throw runtime_error(std::string(e.what())+"\n"+ - "DD4hep: Error interpreting XML nodes of type <"+tag()+"/>"); +void Collection_t::throw_loop_exception(const std::exception& e) const { + if (m_node) { + throw runtime_error(std::string(e.what()) + "\n" + "DD4hep: Error interpreting XML nodes of type <" + tag() + "/>"); } - throw runtime_error(std::string(e.what())+"\n"+ - "DD4hep: Error interpreting collections XML nodes."); + throw runtime_error(std::string(e.what()) + "\n" + "DD4hep: Error interpreting collections XML nodes."); } -void Collection_t::operator++() const { +void Collection_t::operator++() const { Elt_t e = this->parent(); - while(m_node) { + while (m_node) { m_node = m_children.next(); - if ( m_node && _N(m_node)->getNodeType() == ELEMENT_NODE_TYPE ) { - if ( this->parent() == e ) - return; + if (m_node && _N(m_node)->getNodeType() == ELEMENT_NODE_TYPE) { + if (this->parent() == e) + return; } } } -void Collection_t::operator--() const { +void Collection_t::operator--() const { Elt_t e = this->parent(); - while(m_node) { + while (m_node) { m_node = m_children.previous(); - if ( m_node && _N(m_node)->getNodeType() == ELEMENT_NODE_TYPE ) { - if ( this->parent() == e ) - return; + if (m_node && _N(m_node)->getNodeType() == ELEMENT_NODE_TYPE) { + if (this->parent() == e) + return; } } } -void Collection_t::operator++(int) const { +void Collection_t::operator++(int) const { ++(*this); } -void Collection_t::operator--(int) const { +void Collection_t::operator--(int) const { --(*this); } -Handle_t Document::clone(Handle_t source) const { +Handle_t Document::clone(Handle_t source) const { #ifdef DD4HEP_USE_TINYXML return _XE(source.clone(0)); #else diff --git a/DDCore/src/XML/XMLTags.cpp b/DDCore/src/XML/XMLTags.cpp index e7a051072..1f80738f7 100644 --- a/DDCore/src/XML/XMLTags.cpp +++ b/DDCore/src/XML/XMLTags.cpp @@ -5,24 +5,24 @@ #include "xercesc/util/PlatformUtils.hpp" namespace { - struct __Init { + struct __Init { __Init() { - try { xercesc::XMLPlatformUtils::Initialize(); } - catch (const xercesc::XMLException& e) { - std::cout << "Xerces-c error in initialization:" - << xercesc::XMLString::transcode(e.getMessage()) - << std::endl; + try { + xercesc::XMLPlatformUtils::Initialize(); + } + catch (const xercesc::XMLException& e) { + std::cout << "Xerces-c error in initialization:" << xercesc::XMLString::transcode(e.getMessage()) << std::endl; } } ~__Init() { xercesc::XMLPlatformUtils::Terminate(); } }; - __Init __In__; + __Init __In__; } #else namespace { - struct __Init { + struct __Init { __Init() { } }; @@ -33,14 +33,18 @@ namespace { #define UNICODE(x) extern const Tag_t Unicode_##x (#x) #include "XML/UnicodeValues.h" -namespace DD4hep { namespace XML { +namespace DD4hep { + namespace XML { - extern const Tag_t Unicode_NULL ("0"); - extern const Tag_t Unicode_empty (""); - extern const Tag_t Unicode_star ("*"); - extern const Tag_t Unicode_PI ("3.14159265358979323846"); - extern const Tag_t Unicode_TWOPI ("6.28318530717958647692"); + extern const Tag_t Unicode_NULL("0"); + extern const Tag_t Unicode_empty(""); + extern const Tag_t Unicode_star("*"); + extern const Tag_t Unicode_PI("3.14159265358979323846"); + extern const Tag_t Unicode_TWOPI("6.28318530717958647692"); - void tags_init() {static __Init i; } + void tags_init() { + static __Init i; + } -}} + } +} diff --git a/DDCore/src/plugins/Compact2Objects.cpp b/DDCore/src/plugins/Compact2Objects.cpp index 816aeb9b5..870390517 100644 --- a/DDCore/src/plugins/Compact2Objects.cpp +++ b/DDCore/src/plugins/Compact2Objects.cpp @@ -41,114 +41,133 @@ namespace DD4hep { struct Property; struct AlignmentFile; } - template <> void Converter<Constant>::operator()(xml_h e) const; - template <> void Converter<Material>::operator()(xml_h e) const; - template <> void Converter<Atom>::operator()(xml_h e) const; - template <> void Converter<VisAttr>::operator()(xml_h e) const; - template <> void Converter<AlignmentEntry>::operator()(xml_h e) const; - template <> void Converter<Region>::operator()(xml_h e) const; - template <> void Converter<Readout>::operator()(xml_h e) const; - template <> void Converter<LimitSet>::operator()(xml_h e) const; - template <> void Converter<Property>::operator()(xml_h e) const; - template <> void Converter<CartesianField>::operator()(xml_h e) const; - template <> void Converter<SensitiveDetector>::operator()(xml_h element) const; - template <> void Converter<DetElement>::operator()(xml_h element) const; - template <> void Converter<GdmlFile>::operator()(xml_h element) const; - template <> void Converter<AlignmentFile>::operator()(xml_h element) const; - template <> void Converter<Header>::operator()(xml_h element) const; - template <> void Converter<Compact>::operator()(xml_h element) const; + template <> void Converter<Constant>::operator()(xml_h e) const; + template <> void Converter<Material>::operator()(xml_h e) const; + template <> void Converter<Atom>::operator()(xml_h e) const; + template <> void Converter<VisAttr>::operator()(xml_h e) const; + template <> void Converter<AlignmentEntry>::operator()(xml_h e) const; + template <> void Converter<Region>::operator()(xml_h e) const; + template <> void Converter<Readout>::operator()(xml_h e) const; + template <> void Converter<LimitSet>::operator()(xml_h e) const; + template <> void Converter<Property>::operator()(xml_h e) const; + template <> void Converter<CartesianField>::operator()(xml_h e) const; + template <> void Converter<SensitiveDetector>::operator()(xml_h element) const; + template <> void Converter<DetElement>::operator()(xml_h element) const; + template <> void Converter<GdmlFile>::operator()(xml_h element) const; + template <> void Converter<AlignmentFile>::operator()(xml_h element) const; + template <> void Converter<Header>::operator()(xml_h element) const; + template <> void Converter<Compact>::operator()(xml_h element) const; } namespace { static UInt_t unique_mat_id = 0xAFFEFEED; - void throw_print(const std::string& msg) { - printout(ERROR,"Compact",msg.c_str()); + void throw_print(const std::string& msg) { + printout(ERROR, "Compact", msg.c_str()); throw runtime_error(msg); } } -static Ref_t create_GridXYZ(lcdd_t& lcdd, xml_h e) { - GridXYZ obj(lcdd,"grid_xyz"); - if ( e.hasAttr(_U(gridSizeX)) ) obj.setGridSizeX(e.attr<float>(_U(gridSizeX))); - if ( e.hasAttr(_U(gridSizeY)) ) obj.setGridSizeY(e.attr<float>(_U(gridSizeY))); - if ( e.hasAttr(_U(gridSizeZ)) ) obj.setGridSizeZ(e.attr<float>(_U(gridSizeZ))); +static Ref_t create_GridXYZ(lcdd_t& lcdd, xml_h e) { + GridXYZ obj(lcdd, "grid_xyz"); + if (e.hasAttr(_U(gridSizeX))) + obj.setGridSizeX(e.attr<float>(_U(gridSizeX))); + if (e.hasAttr(_U(gridSizeY))) + obj.setGridSizeY(e.attr<float>(_U(gridSizeY))); + if (e.hasAttr(_U(gridSizeZ))) + obj.setGridSizeZ(e.attr<float>(_U(gridSizeZ))); return obj; } DECLARE_XMLELEMENT(GridXYZ,create_GridXYZ); -static Ref_t create_GlobalGridXY(lcdd_t& lcdd, xml_h e) { - GridXY obj(lcdd,"global_grid_xy"); - if ( e.hasAttr(_U(gridSizeX)) ) obj.setGridSizeX(e.attr<float>(_U(gridSizeX))); - if ( e.hasAttr(_U(gridSizeY)) ) obj.setGridSizeY(e.attr<float>(_U(gridSizeY))); +static Ref_t create_GlobalGridXY(lcdd_t& lcdd, xml_h e) { + GridXY obj(lcdd, "global_grid_xy"); + if (e.hasAttr(_U(gridSizeX))) + obj.setGridSizeX(e.attr<float>(_U(gridSizeX))); + if (e.hasAttr(_U(gridSizeY))) + obj.setGridSizeY(e.attr<float>(_U(gridSizeY))); return obj; } DECLARE_XMLELEMENT(GlobalGridXY,create_GlobalGridXY); -static Ref_t create_CartesianGridXY(lcdd_t& lcdd, xml_h e) { - GridXY obj(lcdd,"cartesian_grid_xy"); - if ( e.hasAttr(_U(gridSizeX)) ) obj.setGridSizeX(e.attr<double>(_U(gridSizeX))); - if ( e.hasAttr(_U(gridSizeY)) ) obj.setGridSizeY(e.attr<double>(_U(gridSizeY))); +static Ref_t create_CartesianGridXY(lcdd_t& lcdd, xml_h e) { + GridXY obj(lcdd, "cartesian_grid_xy"); + if (e.hasAttr(_U(gridSizeX))) + obj.setGridSizeX(e.attr<double>(_U(gridSizeX))); + if (e.hasAttr(_U(gridSizeY))) + obj.setGridSizeY(e.attr<double>(_U(gridSizeY))); return obj; } DECLARE_XMLELEMENT(CartesianGridXY,create_CartesianGridXY); -namespace DD4hep { namespace Geometry { typedef GridXY RegularNgonCartesianGridXY; }} +namespace DD4hep { + namespace Geometry { + typedef GridXY RegularNgonCartesianGridXY; + } +} DECLARE_XMLELEMENT(RegularNgonCartesianGridXY,create_CartesianGridXY); -namespace DD4hep { namespace Geometry { +namespace DD4hep { + namespace Geometry { typedef GridXYZ CartesianGridXYZ; typedef GridXY EcalBarrelCartesianGridXY; -}} + } +} DECLARE_XMLELEMENT(CartesianGridXYZ,create_CartesianGridXY); DECLARE_XMLELEMENT(EcalBarrelCartesianGridXY,create_CartesianGridXY); - -static Ref_t create_ProjectiveCylinder(lcdd_t& lcdd, xml_h e) { + +static Ref_t create_ProjectiveCylinder(lcdd_t& lcdd, xml_h e) { ProjectiveCylinder obj(lcdd); - if ( e.hasAttr(_U(phiBins)) ) obj.setPhiBins(e.attr<int>(_U(phiBins))); - if ( e.hasAttr(_U(thetaBins)) ) obj.setThetaBins(e.attr<int>(_U(thetaBins))); + if (e.hasAttr(_U(phiBins))) + obj.setPhiBins(e.attr<int>(_U(phiBins))); + if (e.hasAttr(_U(thetaBins))) + obj.setThetaBins(e.attr<int>(_U(thetaBins))); return obj; } DECLARE_XMLELEMENT(ProjectiveCylinder,create_ProjectiveCylinder); - -static Ref_t create_NonProjectiveCylinder(lcdd_t& lcdd, xml_h e) { + +static Ref_t create_NonProjectiveCylinder(lcdd_t& lcdd, xml_h e) { NonProjectiveCylinder obj(lcdd); - if ( e.hasAttr(_U(gridSizePhi)) ) obj.setThetaBinSize(e.attr<double>(_U(gridSizePhi))); - if ( e.hasAttr(_U(gridSizeZ)) ) obj.setPhiBinSize(e.attr<double>(_U(gridSizeZ))); + if (e.hasAttr(_U(gridSizePhi))) + obj.setThetaBinSize(e.attr<double>(_U(gridSizePhi))); + if (e.hasAttr(_U(gridSizeZ))) + obj.setPhiBinSize(e.attr<double>(_U(gridSizeZ))); return obj; } DECLARE_XMLELEMENT(NonProjectiveCylinder,create_NonProjectiveCylinder); - -static Ref_t create_ProjectiveZPlane(lcdd_t& lcdd, xml_h e) { + +static Ref_t create_ProjectiveZPlane(lcdd_t& lcdd, xml_h e) { ProjectiveZPlane obj(lcdd); - if ( e.hasAttr(_U(phiBins)) ) obj.setThetaBins(e.attr<int>(_U(phiBins))); - if ( e.hasAttr(_U(thetaBins)) ) obj.setPhiBins(e.attr<int>(_U(thetaBins))); + if (e.hasAttr(_U(phiBins))) + obj.setThetaBins(e.attr<int>(_U(phiBins))); + if (e.hasAttr(_U(thetaBins))) + obj.setPhiBins(e.attr<int>(_U(thetaBins))); return obj; } DECLARE_XMLELEMENT(ProjectiveZPlane,create_ProjectiveZPlane); -static Ref_t create_ConstantField(lcdd_t& /* lcdd */, xml_h e) { +static Ref_t create_ConstantField(lcdd_t& /* lcdd */, xml_h e) { CartesianField obj; xml_comp_t field(e), strength(e.child(_U(strength))); - string t = e.attr<string>(_U(field)); + string t = e.attr < string > (_U(field)); ConstantField* ptr = new ConstantField(); - ptr->type = ::toupper(t[0])=='E' ? CartesianField::ELECTRIC : CartesianField::MAGNETIC; + ptr->type = ::toupper(t[0]) == 'E' ? CartesianField::ELECTRIC : CartesianField::MAGNETIC; ptr->direction.SetX(strength.x()); ptr->direction.SetY(strength.y()); ptr->direction.SetZ(strength.z()); - obj.assign(ptr,field.nameStr(),field.typeStr()); + obj.assign(ptr, field.nameStr(), field.typeStr()); return obj; } DECLARE_XMLELEMENT(ConstantField,create_ConstantField); -static Ref_t create_SolenoidField(lcdd_t& lcdd, xml_h e) { +static Ref_t create_SolenoidField(lcdd_t& lcdd, xml_h e) { xml_comp_t c(e); bool has_inner_radius = c.hasAttr(_U(inner_radius)); bool has_outer_radius = c.hasAttr(_U(outer_radius)); - if ( !has_inner_radius && !has_outer_radius ) { + if (!has_inner_radius && !has_outer_radius) { throw_print("Compact2Objects[ERROR]: For a solenoidal field at least one of the " - " xml attributes inner_radius of outer_radius MUST be set."); + " xml attributes inner_radius of outer_radius MUST be set."); } CartesianField obj; SolenoidField* ptr = new SolenoidField(); @@ -157,54 +176,63 @@ static Ref_t create_SolenoidField(lcdd_t& lcdd, xml_h e) { // If no "inner_radius" is given, the "outer_radius" IS the "inner_radius" // and the "outer_radius" is given by one side of the world volume's box // - if ( has_inner_radius && has_outer_radius ) { + if (has_inner_radius && has_outer_radius) { ptr->innerRadius = c.attr<double>(_U(inner_radius)); ptr->outerRadius = c.attr<double>(_U(outer_radius)); } - else if ( has_inner_radius ) { + else if (has_inner_radius) { Box box = lcdd.worldVolume().solid(); ptr->innerRadius = c.attr<double>(_U(inner_radius)); ptr->outerRadius = box.x(); } - else if ( has_outer_radius ) { + else if (has_outer_radius) { Box box = lcdd.worldVolume().solid(); ptr->innerRadius = c.attr<double>(_U(outer_radius)); ptr->outerRadius = box.x(); } - if ( c.hasAttr(_U(inner_field)) ) ptr->innerField = c.attr<double>(_U(inner_field)); - if ( c.hasAttr(_U(outer_field)) ) ptr->outerField = c.attr<double>(_U(outer_field)); - if ( c.hasAttr(_U(zmax)) ) ptr->maxZ = c.attr<double>(_U(zmax)); - else ptr->maxZ = lcdd.constant<double>("world_side"); - if ( c.hasAttr(_U(zmin)) ) ptr->minZ = c.attr<double>(_U(zmin)); - else ptr->minZ = -ptr->maxZ; - obj.assign(ptr,c.nameStr(),c.typeStr()); + if (c.hasAttr(_U(inner_field))) + ptr->innerField = c.attr<double>(_U(inner_field)); + if (c.hasAttr(_U(outer_field))) + ptr->outerField = c.attr<double>(_U(outer_field)); + if (c.hasAttr(_U(zmax))) + ptr->maxZ = c.attr<double>(_U(zmax)); + else + ptr->maxZ = lcdd.constant<double>("world_side"); + if (c.hasAttr(_U(zmin))) + ptr->minZ = c.attr<double>(_U(zmin)); + else + ptr->minZ = -ptr->maxZ; + obj.assign(ptr, c.nameStr(), c.typeStr()); return obj; } DECLARE_XMLELEMENT(SolenoidMagnet,create_SolenoidField); // This is the plugin required for slic: note the different name DECLARE_XMLELEMENT(solenoid,create_SolenoidField); -static Ref_t create_DipoleField(lcdd_t& /* lcdd */, xml_h e) { +static Ref_t create_DipoleField(lcdd_t& /* lcdd */, xml_h e) { xml_comp_t c(e); CartesianField obj; DipoleField* ptr = new DipoleField(); double val, lunit = c.attr<double>(_U(lunit)), funit = c.attr<double>(_U(funit)); - if ( c.hasAttr(_U(zmin)) ) ptr->zmin = _multiply<double>(c.attr<string>(_U(zmin)),lunit); - if ( c.hasAttr(_U(zmax)) ) ptr->zmax = _multiply<double>(c.attr<string>(_U(zmax)),lunit); - if ( c.hasAttr(_U(rmax)) ) ptr->rmax = _multiply<double>(c.attr<string>(_U(rmax)),lunit); - for( xml_coll_t coll(c,_U(dipole_coeff)); coll; ++coll) { - val = funit/pow(lunit,(int)ptr->coefficents.size()); - val = _multiply<double>(coll.value(),val); + if (c.hasAttr(_U(zmin))) + ptr->zmin = _multiply<double>(c.attr < string > (_U(zmin)), lunit); + if (c.hasAttr(_U(zmax))) + ptr->zmax = _multiply<double>(c.attr < string > (_U(zmax)), lunit); + if (c.hasAttr(_U(rmax))) + ptr->rmax = _multiply<double>(c.attr < string > (_U(rmax)), lunit); + for (xml_coll_t coll(c, _U(dipole_coeff)); coll; ++coll) { + val = funit / pow(lunit, (int) ptr->coefficents.size()); + val = _multiply<double>(coll.value(), val); ptr->coefficents.push_back(val); } - obj.assign(ptr,c.nameStr(),c.typeStr()); + obj.assign(ptr, c.nameStr(), c.typeStr()); return obj; -} +} DECLARE_XMLELEMENT(DipoleMagnet,create_DipoleField); static long create_Compact(lcdd_t& lcdd, xml_h element) { - Converter<Compact> converter(lcdd); + Converter < Compact > converter(lcdd); converter(element); return 1; } @@ -214,12 +242,11 @@ DECLARE_XML_DOC_READER(lccdd,create_Compact); * * */ -template <> void Converter<Constant>::operator()(xml_h e) const { - xml_ref_t constant(e); - TNamed* obj = new TNamed(constant.attr<string>(_U(name)).c_str(), - constant.attr<string>(_U(value)).c_str()); - Ref_t cons(obj); - _toDictionary(obj->GetName(),obj->GetTitle()); +template <> void Converter<Constant>::operator()(xml_h e) const { + xml_ref_t constant(e); + TNamed* obj = new TNamed(constant.attr < string > (_U(name)).c_str(), constant.attr < string > (_U(value)).c_str()); + Ref_t cons(obj); + _toDictionary(obj->GetName(), obj->GetTitle()); lcdd.addConstant(cons); } @@ -227,13 +254,13 @@ template <> void Converter<Constant>::operator()(xml_h e) const { * * */ -template <> void Converter<Header>::operator()(xml_h e) const { +template <> void Converter<Header>::operator()(xml_h e) const { xml_comp_t c(e); - Header h(e.attr<string>(_U(name)),e.attr<string>(_U(title))); - h.setUrl(e.attr<string>(_U(url))); - h.setAuthor(e.attr<string>(_U(author))); - h.setStatus(e.attr<string>(_U(status))); - h.setVersion(e.attr<string>(_U(version))); + Header h(e.attr < string > (_U(name)), e.attr < string > (_U(title))); + h.setUrl(e.attr < string > (_U(url))); + h.setAuthor(e.attr < string > (_U(author))); + h.setStatus(e.attr < string > (_U(status))); + h.setVersion(e.attr < string > (_U(version))); h.setComment(e.child(_U(comment)).text()); lcdd.setHeader(h); } @@ -254,90 +281,90 @@ template <> void Converter<Header>::operator()(xml_h e) const { * </element> * */ -template <> void Converter<Material>::operator()(xml_h e) const { - xml_ref_t m(e); - TGeoManager& mgr = lcdd.manager(); - xml_tag_t mname = m.name(); - const char* matname = mname.c_str(); - TGeoElementTable* table = mgr.GetElementTable(); - TGeoMaterial* mat = mgr.GetMaterial(matname); - TGeoMixture* mix = dynamic_cast<TGeoMixture*>(mat); - xml_coll_t fractions(m,_U(fraction)); - xml_coll_t composites(m,_U(composite)); +template <> void Converter<Material>::operator()(xml_h e) const { + xml_ref_t m(e); + TGeoManager& mgr = lcdd.manager(); + xml_tag_t mname = m.name(); + const char* matname = mname.c_str(); + TGeoElementTable* table = mgr.GetElementTable(); + TGeoMaterial* mat = mgr.GetMaterial(matname); + TGeoMixture* mix = dynamic_cast<TGeoMixture*>(mat); + xml_coll_t fractions(m, _U(fraction)); + xml_coll_t composites(m, _U(composite)); bool has_density = true; - if ( 0 == mat ) { + if (0 == mat) { TGeoMaterial* comp_mat; - TGeoElement* comp_elt; - xml_h radlen = m.child(_U(RL),false); - xml_h intlen = m.child(_U(NIL),false); - xml_h density = m.child(_U(D),false); - double radlen_val = radlen.ptr() ? radlen.attr<double>(_U(value)) : 0.0; - double intlen_val = intlen.ptr() ? intlen.attr<double>(_U(value)) : 0.0; - double dens_val = density.ptr() ? density.attr<double>(_U(value)) : 0.0; - if ( 0 == mat && !density.ptr() ) { + TGeoElement* comp_elt; + xml_h radlen = m.child(_U(RL), false); + xml_h intlen = m.child(_U(NIL), false); + xml_h density = m.child(_U(D), false); + double radlen_val = radlen.ptr() ? radlen.attr<double>(_U(value)) : 0.0; + double intlen_val = intlen.ptr() ? intlen.attr<double>(_U(value)) : 0.0; + double dens_val = density.ptr() ? density.attr<double>(_U(value)) : 0.0; + if (0 == mat && !density.ptr()) { has_density = false; } - printout(DEBUG,"Compact","++ Creating material %s",matname); - mat = mix = new TGeoMixture(matname,composites.size(),dens_val); - mat->SetRadLen(radlen_val,intlen_val); - for(composites.reset(); composites; ++composites) { - std::string nam = composites.attr<string>(_U(ref)); + printout(DEBUG, "Compact", "++ Creating material %s", matname); + mat = mix = new TGeoMixture(matname, composites.size(), dens_val); + mat->SetRadLen(radlen_val, intlen_val); + for (composites.reset(); composites; ++composites) { + std::string nam = composites.attr < string > (_U(ref)); double fraction = composites.attr<double>(_U(n)); - if ( 0 != (comp_mat=mgr.GetMaterial(nam.c_str())) ) - mix->AddElement(comp_mat,fraction); - else if ( 0 != (comp_elt=table->FindElement(nam.c_str())) ) - mix->AddElement(comp_elt,fraction); + if (0 != (comp_mat = mgr.GetMaterial(nam.c_str()))) + mix->AddElement(comp_mat, fraction); + else if (0 != (comp_elt = table->FindElement(nam.c_str()))) + mix->AddElement(comp_elt, fraction); else - throw_print("Compact2Objects[ERROR]: Creating material:"+mname+" Element missing: "+nam); + throw_print("Compact2Objects[ERROR]: Creating material:" + mname + " Element missing: " + nam); } - for(fractions.reset(); fractions; ++fractions) { - std::string nam = fractions.attr<string>(_U(ref)); + for (fractions.reset(); fractions; ++fractions) { + std::string nam = fractions.attr < string > (_U(ref)); double fraction = fractions.attr<double>(_U(n)); - if ( 0 != (comp_mat=mgr.GetMaterial(nam.c_str())) ) - mix->AddElement(comp_mat,fraction); - else if ( 0 != (comp_elt=table->FindElement(nam.c_str())) ) - mix->AddElement(comp_elt,fraction); + if (0 != (comp_mat = mgr.GetMaterial(nam.c_str()))) + mix->AddElement(comp_mat, fraction); + else if (0 != (comp_elt = table->FindElement(nam.c_str()))) + mix->AddElement(comp_elt, fraction); else - throw_print("Compact2Objects[ERROR]: Creating material:"+mname+" Element missing: "+nam); + throw_print("Compact2Objects[ERROR]: Creating material:" + mname + " Element missing: " + nam); } // Update estimated density if not provided. - if ( !has_density && mix && 0 == mix->GetDensity() ) { + if (!has_density && mix && 0 == mix->GetDensity()) { double dens = 0.0; - for(composites.reset(); composites; ++composites) { - std::string nam = composites.attr<string>(_U(ref)); - comp_mat = mgr.GetMaterial(nam.c_str()); - dens += composites.attr<double>(_U(n)) * comp_mat->GetDensity(); + for (composites.reset(); composites; ++composites) { + std::string nam = composites.attr < string > (_U(ref)); + comp_mat = mgr.GetMaterial(nam.c_str()); + dens += composites.attr<double>(_U(n)) * comp_mat->GetDensity(); } - for(fractions.reset(); fractions; ++fractions) { - std::string nam = fractions.attr<string>(_U(ref)); - comp_mat = mgr.GetMaterial(nam.c_str()); - dens += composites.attr<double>(_U(n)) * comp_mat->GetDensity(); + for (fractions.reset(); fractions; ++fractions) { + std::string nam = fractions.attr < string > (_U(ref)); + comp_mat = mgr.GetMaterial(nam.c_str()); + dens += composites.attr<double>(_U(n)) * comp_mat->GetDensity(); } - printout(WARNING,"Compact","++ Material: %s with NO density. " - "Set density to %7.3 g/cm**3",matname,dens); + printout(WARNING, "Compact", "++ Material: %s with NO density. " + "Set density to %7.3 g/cm**3", matname, dens); mix->SetDensity(dens); } } TGeoMedium* medium = mgr.GetMedium(matname); - if ( 0 == medium ) { + if (0 == medium) { --unique_mat_id; - medium = new TGeoMedium(matname,unique_mat_id,mat); + medium = new TGeoMedium(matname, unique_mat_id, mat); medium->SetTitle("material"); medium->SetUniqueID(unique_mat_id); } // TGeo has no notion of a material "formula" // Hence, treat the formula the same way as the material itself - if ( m.hasAttr(_U(formula)) ) { - string form = m.attr<string>(_U(formula)); - if ( form != matname ) { + if (m.hasAttr(_U(formula))) { + string form = m.attr < string > (_U(formula)); + if (form != matname) { medium = mgr.GetMedium(form.c_str()); - if ( 0 == medium ) { - --unique_mat_id; - medium = new TGeoMedium(form.c_str(),unique_mat_id,mat); - medium->SetTitle("material"); - medium->SetUniqueID(unique_mat_id); + if (0 == medium) { + --unique_mat_id; + medium = new TGeoMedium(form.c_str(), unique_mat_id, mat); + medium->SetTitle("material"); + medium->SetUniqueID(unique_mat_id); } } } @@ -347,59 +374,62 @@ template <> void Converter<Material>::operator()(xml_h e) const { * * <element Z="29" formula="Cu" name="Cu" > */ -template <> void Converter<Atom>::operator()(xml_h e) const { - xml_ref_t elem(e); - xml_tag_t eltname = elem.name(); - TGeoManager& mgr = lcdd.manager(); +template <> void Converter<Atom>::operator()(xml_h e) const { + xml_ref_t elem(e); + xml_tag_t eltname = elem.name(); + TGeoManager& mgr = lcdd.manager(); TGeoElementTable* tab = mgr.GetElementTable(); - TGeoElement* element = tab->FindElement(eltname.c_str()); - if ( !element ) { + TGeoElement* element = tab->FindElement(eltname.c_str()); + if (!element) { xml_ref_t atom(elem.child(_U(atom))); - tab->AddElement(elem.attr<string>(_U(name)).c_str(), - elem.attr<string>(_U(formula)).c_str(), - elem.attr<int>(_U(Z)), - atom.attr<int>(_U(value)) - ); + tab->AddElement(elem.attr < string > (_U(name)).c_str(), elem.attr < string > (_U(formula)).c_str(), elem.attr<int>(_U(Z)), + atom.attr<int>(_U(value))); element = tab->FindElement(eltname.c_str()); - if ( !element ) { - throw_print("Failed to properly insert the Element:"+eltname+" into the element table!"); + if (!element) { + throw_print("Failed to properly insert the Element:" + eltname + " into the element table!"); } } } /** Convert compact visualization attribute to LCDD visualization attribute * - * <vis name="SiVertexBarrelModuleVis" - * alpha="1.0" r="1.0" g="0.75" b="0.76" - * drawingStyle="wireframe" - * showDaughters="false" + * <vis name="SiVertexBarrelModuleVis" + * alpha="1.0" r="1.0" g="0.75" b="0.76" + * drawingStyle="wireframe" + * showDaughters="false" * visible="true"/> */ -template <> void Converter<VisAttr>::operator()(xml_h e) const { - VisAttr attr(e.attr<string>(_U(name))); +template <> void Converter<VisAttr>::operator()(xml_h e) const { + VisAttr attr(e.attr < string > (_U(name))); float r = e.hasAttr(_U(r)) ? e.attr<float>(_U(r)) : 1.0f; float g = e.hasAttr(_U(g)) ? e.attr<float>(_U(g)) : 1.0f; float b = e.hasAttr(_U(b)) ? e.attr<float>(_U(b)) : 1.0f; - attr.setColor(r,g,b); - if ( e.hasAttr(_U(alpha)) ) attr.setAlpha(e.attr<float>(_U(alpha))); - if ( e.hasAttr(_U(visible)) ) attr.setVisible(e.attr<bool>(_U(visible))); - if ( e.hasAttr(_U(lineStyle)) ) { - string ls = e.attr<string>(_U(lineStyle)); - if ( ls == "unbroken" ) attr.setLineStyle(VisAttr::SOLID); - else if ( ls == "broken" ) attr.setLineStyle(VisAttr::DASHED); - } - else { + attr.setColor(r, g, b); + if (e.hasAttr(_U(alpha))) + attr.setAlpha(e.attr<float>(_U(alpha))); + if (e.hasAttr(_U(visible))) + attr.setVisible(e.attr<bool>(_U(visible))); + if (e.hasAttr(_U(lineStyle))) { + string ls = e.attr < string > (_U(lineStyle)); + if (ls == "unbroken") + attr.setLineStyle(VisAttr::SOLID); + else if (ls == "broken") + attr.setLineStyle(VisAttr::DASHED); + } + else { attr.setLineStyle(VisAttr::SOLID); } - if ( e.hasAttr(_U(drawingStyle)) ) { - string ds = e.attr<string>(_U(drawingStyle)); - if ( ds == "wireframe" ) attr.setDrawingStyle(VisAttr::WIREFRAME); - else if ( ds == "solid" ) attr.setDrawingStyle(VisAttr::SOLID); + if (e.hasAttr(_U(drawingStyle))) { + string ds = e.attr < string > (_U(drawingStyle)); + if (ds == "wireframe") + attr.setDrawingStyle(VisAttr::WIREFRAME); + else if (ds == "solid") + attr.setDrawingStyle(VisAttr::SOLID); } - else { + else { attr.setDrawingStyle(VisAttr::SOLID); } - if ( e.hasAttr(_U(showDaughters)) ) + if (e.hasAttr(_U(showDaughters))) attr.setShowDaughters(e.attr<bool>(_U(showDaughters))); else attr.setShowDaughters(true); @@ -413,26 +443,26 @@ template <> void Converter<VisAttr>::operator()(xml_h e) const { * <rotation theta="theta-value" phi="phi-value" psi="psi-value"/> * </alignment> */ -template <> void Converter<AlignmentEntry>::operator()(xml_h e) const { +template <> void Converter<AlignmentEntry>::operator()(xml_h e) const { xml_comp_t child(e); - string path = e.attr<string>(_U(name)); - bool check = e.hasAttr(_U(check)); + string path = e.attr < string > (_U(name)); + bool check = e.hasAttr(_U(check)); bool overlap = e.hasAttr(_U(overlap)); AlignmentEntry alignment(path); Position pos; RotationZYX rot; - if ( (child=e.child(_U(position),false)) ) { // Position is not mandatory! - pos.SetXYZ(child.x(),child.y(),child.z()); + if ((child = e.child(_U(position), false))) { // Position is not mandatory! + pos.SetXYZ(child.x(), child.y(), child.z()); } - if ( (child=e.child(_U(rotation),false)) ) { // Rotation is not mandatory - rot.SetComponents(child.z(),child.y(),child.x()); + if ((child = e.child(_U(rotation), false))) { // Rotation is not mandatory + rot.SetComponents(child.z(), child.y(), child.x()); } - if ( overlap ) { + if (overlap) { double ovl = e.attr<double>(_U(overlap)); - alignment.align(pos,rot,check,ovl); + alignment.align(pos, rot, check, ovl); } else { - alignment.align(pos,rot,check); + alignment.align(pos, rot, check); } lcdd.addAlignment(alignment); } @@ -440,18 +470,18 @@ template <> void Converter<AlignmentEntry>::operator()(xml_h e) const { /** Specialized converter for compact region objects. * */ -template <> void Converter<Region>::operator()(xml_h e) const { - Region region(e.attr<string>(_U(name))); - vector<string>& limits = region.limits(); - string ene = e.attr<string>(_U(eunit)), len = e.attr<string>(_U(lunit)); +template <> void Converter<Region>::operator()(xml_h e) const { + Region region(e.attr < string > (_U(name))); + vector < string > &limits = region.limits(); + string ene = e.attr < string > (_U(eunit)), len = e.attr < string > (_U(lunit)); region.setEnergyUnit(ene); region.setLengthUnit(len); - region.setCut(_multiply<double>(e.attr<string>(_U(cut)),len)); - region.setThreshold(_multiply<double>(e.attr<string>(_U(threshold)),ene)); + region.setCut(_multiply<double>(e.attr < string > (_U(cut)), len)); + region.setThreshold(_multiply<double>(e.attr < string > (_U(threshold)), ene)); region.setStoreSecondaries(e.attr<bool>(_U(store_secondaries))); - for(xml_coll_t user_limits(e,_U(limitsetref)); user_limits; ++user_limits) - limits.push_back(user_limits.attr<string>(_U(name))); + for (xml_coll_t user_limits(e, _U(limitsetref)); user_limits; ++user_limits) + limits.push_back(user_limits.attr < string > (_U(name))); lcdd.addRegion(region); } @@ -462,24 +492,24 @@ template <> void Converter<Region>::operator()(xml_h e) const { * <id>system:6,barrel:3,module:4,layer:8,slice:5,x:32:-16,y:-16</id> * </readout> */ -template <> void Converter<Readout>::operator()(xml_h e) const { - xml_h id = e.child(_U(id)); - xml_h seg = e.child(_U(segmentation),false); - string name = e.attr<string>(_U(name)); +template <> void Converter<Readout>::operator()(xml_h e) const { + xml_h id = e.child(_U(id)); + xml_h seg = e.child(_U(segmentation), false); + string name = e.attr < string > (_U(name)); Readout ro(name); Ref_t idSpec; - if ( seg ) { // Segmentation is not mandatory! - string type = seg.attr<string>(_U(type)); - Ref_t segment(PluginService::Create<TNamed*>(type,&lcdd,&seg)); - if ( !segment.isValid() ) { + if (seg) { // Segmentation is not mandatory! + string type = seg.attr < string > (_U(type)); + Ref_t segment(PluginService::Create<TNamed*>(type, &lcdd, &seg)); + if (!segment.isValid()) { PluginDebug dbg; - PluginService::Create<TNamed*>(type,&lcdd,&seg); - throw_print("FAILED to create segmentation:"+type+". "+dbg.missingFactory(type)); + PluginService::Create<TNamed*>(type, &lcdd, &seg); + throw_print("FAILED to create segmentation:" + type + ". " + dbg.missingFactory(type)); } ro.setSegmentation(segment); } - if ( id ) { + if (id) { // <id>system:6,barrel:3,module:4,layer:8,slice:5,x:32:-16,y:-16</id> idSpec = IDDescriptor(id.text()); idSpec->SetName(ro.name()); @@ -491,19 +521,19 @@ template <> void Converter<Readout>::operator()(xml_h e) const { /** Specialized converter for compact LimitSet objects. * - * <limitset name="...."> + * <limitset name="...."> * <limit name="step_length_max" particles="*" value="5.0" unit="mm" /> * ... </limitset> */ -template <> void Converter<LimitSet>::operator()(xml_h e) const { - LimitSet ls(e.attr<string>(_U(name))); - for (xml_coll_t c(e,_U(limit)); c; ++c) { +template <> void Converter<LimitSet>::operator()(xml_h e) const { + LimitSet ls(e.attr < string > (_U(name))); + for (xml_coll_t c(e, _U(limit)); c; ++c) { Limit limit; - limit.particles = c.attr<string>(_U(particles)); - limit.name = c.attr<string>(_U(name)); - limit.content = c.attr<string>(_U(value)); - limit.unit = c.attr<string>(_U(unit)); - limit.value = _multiply<double>(limit.content,limit.unit); + limit.particles = c.attr < string > (_U(particles)); + limit.name = c.attr < string > (_U(name)); + limit.content = c.attr < string > (_U(value)); + limit.unit = c.attr < string > (_U(unit)); + limit.value = _multiply<double>(limit.content, limit.unit); ls.addLimit(limit); } lcdd.addLimitSet(ls); @@ -515,18 +545,18 @@ template <> void Converter<LimitSet>::operator()(xml_h e) const { * <attributes name="key" type="" .... /> * ... </properties> */ -template <> void Converter<Property>::operator()(xml_h e) const { - string name = e.attr<string>(_U(name)); +template <> void Converter<Property>::operator()(xml_h e) const { + string name = e.attr < string > (_U(name)); LCDD::Properties& prp = lcdd.properties(); - if ( name.empty() ) { + if (name.empty()) { throw_print("Failed to convert properties. No name given!"); } - vector<xml_attr_t> a = e.attributes(); - if ( prp.find(name) == prp.end() ) { - prp.insert(make_pair(name,LCDD::PropertyValues())); + vector < xml_attr_t > a = e.attributes(); + if (prp.find(name) == prp.end()) { + prp.insert(make_pair(name, LCDD::PropertyValues())); } - for( vector<xml_attr_t>::iterator i=a.begin(); i != a.end(); ++i) { - pair<string,string> val(xml_tag_t(e.attr_name(*i)),e.attr<string>(*i)); + for (vector<xml_attr_t>::iterator i = a.begin(); i != a.end(); ++i) { + pair < string, string > val(xml_tag_t(e.attr_name(*i)), e.attr < string > (*i)); prp[name].insert(val); } } @@ -534,23 +564,23 @@ template <> void Converter<Property>::operator()(xml_h e) const { /** Specialized converter for electric and magnetic fields * * Uses internally a plugin to allow flexible field descriptions. - * + * * <field type="ConstantField" name="Myfield" field="electric"> * <strength x="0" y="0" z="5"/> * </field> */ -template <> void Converter<CartesianField>::operator()(xml_h e) const { +template <> void Converter<CartesianField>::operator()(xml_h e) const { string msg = "updated"; - string name = e.attr<string>(_U(name)); - string type = e.attr<string>(_U(type)); + string name = e.attr < string > (_U(name)); + string type = e.attr < string > (_U(type)); CartesianField field = lcdd.field(name); - if ( !field.isValid() ) { + if (!field.isValid()) { // The field is not present: We create it and add it to LCDD - field = Ref_t(PluginService::Create<TNamed*>(type,&lcdd,&e)); - if ( !field.isValid() ) { + field = Ref_t(PluginService::Create<TNamed*>(type, &lcdd, &e)); + if (!field.isValid()) { PluginDebug dbg; - PluginService::Create<TNamed*>(type,&lcdd,&e); - throw_print("Failed to create field object of type "+type+". "+dbg.missingFactory(type)); + PluginService::Create<TNamed*>(type, &lcdd, &e); + throw_print("Failed to create field object of type " + type + ". " + dbg.missingFactory(type)); } lcdd.addField(field); msg = "created"; @@ -558,202 +588,202 @@ template <> void Converter<CartesianField>::operator()(xml_h e) const { type = field.type(); // Now update the field structure with the generic part ie. set it's properties CartesianField::Properties& prp = field.properties(); - for( xml_coll_t c(e,_U(properties)); c; ++c) { - string props_name = c.attr<string>(_U(name)); - vector<xml_attr_t> a = c.attributes(); - if ( prp.find(props_name) == prp.end() ) { - prp.insert(make_pair(props_name,CartesianField::PropertyValues())); + for (xml_coll_t c(e, _U(properties)); c; ++c) { + string props_name = c.attr < string > (_U(name)); + vector < xml_attr_t > a = c.attributes(); + if (prp.find(props_name) == prp.end()) { + prp.insert(make_pair(props_name, CartesianField::PropertyValues())); } - for( vector<xml_attr_t>::iterator i=a.begin(); i != a.end(); ++i) { - pair<string,string> val(xml_tag_t(c.attr_name(*i)),c.attr<string>(*i)); + for (vector<xml_attr_t>::iterator i = a.begin(); i != a.end(); ++i) { + pair < string, string > val(xml_tag_t(c.attr_name(*i)), c.attr < string > (*i)); prp[props_name].insert(val); } - if ( c.hasAttr(_U(global)) && c.attr<bool>(_U(global)) ) { + if (c.hasAttr(_U(global)) && c.attr<bool>(_U(global))) { lcdd.field().properties() = prp; } } - printout(ALWAYS,"Compact","++ Converted field: Successfully %s field %s [%s]", - msg.c_str(),name.c_str(),type.c_str()); + printout(ALWAYS, "Compact", "++ Converted field: Successfully %s field %s [%s]", msg.c_str(), name.c_str(), type.c_str()); } /** Update sensitive detectors from group tags. * * Handle xml sections of the type: * <sd name="MuonBarrel" - * type="Geant4Calorimeter" - * ecut="100.0*MeV" - * verbose="true" + * type="Geant4Calorimeter" + * ecut="100.0*MeV" + * verbose="true" * hit_aggregation="position" * limits="limit-set-reference" * region="region-name-reference"> * </sd> * */ -template <> void Converter<SensitiveDetector>::operator()(xml_h element) const { - string name = element.attr<string>(_U(name)); +template <> void Converter<SensitiveDetector>::operator()(xml_h element) const { + string name = element.attr < string > (_U(name)); try { - DetElement det = lcdd.detector(name); - SensitiveDetector sd = lcdd.sensitiveDetector(name); + DetElement det = lcdd.detector(name); + SensitiveDetector sd = lcdd.sensitiveDetector(name); - xml_attr_t type = element.attr_nothrow(_U(type)); - if ( type ) { - sd.setType(element.attr<string>(type)); + xml_attr_t type = element.attr_nothrow(_U(type)); + if (type) { + sd.setType(element.attr < string > (type)); } xml_attr_t verbose = element.attr_nothrow(_U(verbose)); - if ( verbose ) { + if (verbose) { sd.setVerbose(element.attr<bool>(verbose)); } xml_attr_t combine = element.attr_nothrow(_U(combine_hits)); - if ( combine ) { + if (combine) { sd.setCombineHits(element.attr<bool>(combine)); } - xml_attr_t limits = element.attr_nothrow(_U(limits)); - if ( limits ) { - string l = element.attr<string>(limits); + xml_attr_t limits = element.attr_nothrow(_U(limits)); + if (limits) { + string l = element.attr < string > (limits); LimitSet ls = lcdd.limitSet(l); - if ( !ls.isValid() ) { - throw_print("Converter<SensitiveDetector>: Request for non-existing limitset:"+l); + if (!ls.isValid()) { + throw_print("Converter<SensitiveDetector>: Request for non-existing limitset:" + l); } sd.setLimitSet(ls); } - xml_attr_t region = element.attr_nothrow(_U(region)); - if ( region ) { - string r = element.attr<string>(region); + xml_attr_t region = element.attr_nothrow(_U(region)); + if (region) { + string r = element.attr < string > (region); Region reg = lcdd.region(r); - if ( !reg.isValid() ) { - throw_print("Converter<SensitiveDetector>: Request for non-existing region:"+r); + if (!reg.isValid()) { + throw_print("Converter<SensitiveDetector>: Request for non-existing region:" + r); } sd.setRegion(reg); } - xml_attr_t hits = element.attr_nothrow(_U(hits_collection)); - if ( hits ) { - sd.setHitsCollection(element.attr<string>(hits)); + xml_attr_t hits = element.attr_nothrow(_U(hits_collection)); + if (hits) { + sd.setHitsCollection(element.attr < string > (hits)); } - xml_attr_t ecut = element.attr_nothrow(_U(ecut)); + xml_attr_t ecut = element.attr_nothrow(_U(ecut)); xml_attr_t eunit = element.attr_nothrow(_U(eunit)); - if ( ecut && eunit ) { - double value = _multiply<double>(_toString(ecut),_toString(eunit)); + if (ecut && eunit) { + double value = _multiply<double>(_toString(ecut), _toString(eunit)); sd.setEnergyCutoff(value); } - else if ( ecut ) { // If no unit is given , we assume the correct Geant4 unit is used! + else if (ecut) { // If no unit is given , we assume the correct Geant4 unit is used! sd.setEnergyCutoff(element.attr<double>(ecut)); } - printout(DEBUG,"Compact","SensitiveDetector-update: %-18s %-24s Hits:%-24s Cutoff:%f7.3f", - sd.name(),(" ["+sd.type()+"]").c_str(),sd.hitsCollection().c_str(),sd.energyCutoff()); + printout(DEBUG, "Compact", "SensitiveDetector-update: %-18s %-24s Hits:%-24s Cutoff:%f7.3f", sd.name(), + (" [" + sd.type() + "]").c_str(), sd.hitsCollection().c_str(), sd.energyCutoff()); xml_attr_t sequence = element.attr_nothrow(_U(sequence)); - if ( sequence ) { + if (sequence) { } } - catch(const exception& e) { - printout(ERROR,"Compact","++ FAILED to convert sensitive detector: %s: %s", - name.c_str(),e.what()); + catch (const exception& e) { + printout(ERROR, "Compact", "++ FAILED to convert sensitive detector: %s: %s", name.c_str(), e.what()); } - catch(...) { - printout(ERROR,"Compact","++ FAILED to convert sensitive detector: %s: %s", - name.c_str(),"UNKNONW Exception"); + catch (...) { + printout(ERROR, "Compact", "++ FAILED to convert sensitive detector: %s: %s", name.c_str(), "UNKNONW Exception"); } } -void setChildTitles(const pair<string,DetElement>& e) { +void setChildTitles(const pair<string, DetElement>& e) { DetElement parent = e.second.parent(); const DetElement::Children& children = e.second.children(); - if ( ::strlen(e.second->GetTitle()) == 0 ) { + if (::strlen(e.second->GetTitle()) == 0) { e.second->SetTitle(parent.isValid() ? parent.type().c_str() : e.first.c_str()); } - for_each(children.begin(),children.end(),setChildTitles); + for_each(children.begin(), children.end(), setChildTitles); } -template <> void Converter<DetElement>::operator()(xml_h element) const { +template <> void Converter<DetElement>::operator()(xml_h element) const { static const char* req_dets = ::getenv("REQUIRED_DETECTORS"); static const char* req_typs = ::getenv("REQUIRED_DETECTOR_TYPES"); static const char* ign_dets = ::getenv("IGNORED_DETECTORS"); static const char* ign_typs = ::getenv("IGNORED_DETECTOR_TYPES"); - string type = element.attr<string>(_U(type)); - string name = element.attr<string>(_U(name)); - string name_match = ":"+name+":"; - string type_match = ":"+type+":"; - if ( req_dets && !strstr(req_dets,name_match.c_str()) ) return; - if ( req_typs && !strstr(req_typs,type_match.c_str()) ) return; - if ( ign_dets && strstr(ign_dets,name_match.c_str()) ) return; - if ( ign_typs && strstr(ign_typs,type_match.c_str()) ) return; + string type = element.attr < string > (_U(type)); + string name = element.attr < string > (_U(name)); + string name_match = ":" + name + ":"; + string type_match = ":" + type + ":"; + if (req_dets && !strstr(req_dets, name_match.c_str())) + return; + if (req_typs && !strstr(req_typs, type_match.c_str())) + return; + if (ign_dets && strstr(ign_dets, name_match.c_str())) + return; + if (ign_typs && strstr(ign_typs, type_match.c_str())) + return; try { xml_attr_t attr_ro = element.attr_nothrow(_U(readout)); SensitiveDetector sd; - if ( attr_ro ) { - Readout ro = lcdd.readout(element.attr<string>(attr_ro)); - if ( !ro.isValid() ) { - throw runtime_error("No Readout structure present for detector:"+name); + if (attr_ro) { + Readout ro = lcdd.readout(element.attr < string > (attr_ro)); + if (!ro.isValid()) { + throw runtime_error("No Readout structure present for detector:" + name); } - sd = SensitiveDetector(name,"sensitive"); + sd = SensitiveDetector(name, "sensitive"); sd.setHitsCollection(ro.name()); sd.setReadout(ro); lcdd.addSensitiveDetector(sd); } Ref_t sens = sd; - DetElement det(Ref_t(PluginService::Create<TNamed*>(type,&lcdd,&element,&sens))); - if ( det.isValid() ) { - setChildTitles(make_pair(name,det)); + DetElement det(Ref_t(PluginService::Create<TNamed*>(type, &lcdd, &element, &sens))); + if (det.isValid()) { + setChildTitles(make_pair(name, det)); } - printout(det.isValid() ? INFO : ERROR,"Compact","%s subdetector:%s of type %s %s", - (det.isValid() ? "++ Converted" : "FAILED "),name.c_str(),type.c_str(), - (sd.isValid() ? ("["+sd.type()+"]").c_str() : "")); + printout(det.isValid() ? INFO : ERROR, "Compact", "%s subdetector:%s of type %s %s", + (det.isValid() ? "++ Converted" : "FAILED "), name.c_str(), type.c_str(), + (sd.isValid() ? ("[" + sd.type() + "]").c_str() : "")); - if ( !det.isValid() ) { + if (!det.isValid()) { PluginDebug dbg; - PluginService::Create<TNamed*>(type,&lcdd,&element,&sens); - throw runtime_error("Failed to execute subdetector creation plugin. "+dbg.missingFactory(type)); + PluginService::Create<TNamed*>(type, &lcdd, &element, &sens); + throw runtime_error("Failed to execute subdetector creation plugin. " + dbg.missingFactory(type)); } lcdd.addDetector(det); return; } - catch(const exception& e) { - printout(ERROR,"Compact","++ FAILED to convert subdetector: %s: %s",name.c_str(),e.what()); + catch (const exception& e) { + printout(ERROR, "Compact", "++ FAILED to convert subdetector: %s: %s", name.c_str(), e.what()); terminate(); } - catch(...) { - printout(ERROR,"Compact","++ FAILED to convert subdetector: %s: %s",name.c_str(),"UNKNONW Exception"); + catch (...) { + printout(ERROR, "Compact", "++ FAILED to convert subdetector: %s: %s", name.c_str(), "UNKNONW Exception"); terminate(); } } - + /// Read material entries from a seperate file in one of the include sections of the geometry -template <> void Converter<GdmlFile>::operator()(xml_h element) const { - xml_h materials = XML::DocumentHandler().load(element,element.attr_value(_U(ref))).root(); - xml_coll_t(materials,_U(element) ).for_each(Converter<Atom>(this->lcdd)); - xml_coll_t(materials,_U(material)).for_each(Converter<Material>(this->lcdd)); +template <> void Converter<GdmlFile>::operator()(xml_h element) const { + xml_h materials = XML::DocumentHandler().load(element, element.attr_value(_U(ref))).root(); + xml_coll_t(materials, _U(element)).for_each(Converter < Atom > (this->lcdd)); + xml_coll_t(materials, _U(material)).for_each(Converter < Material > (this->lcdd)); } /// Read alignment entries from a seperate file in one of the include sections of the geometry -template <> void Converter<AlignmentFile>::operator()(xml_h element) const { - xml_h alignments = XML::DocumentHandler().load(element,element.attr_value(_U(ref))).root(); - xml_coll_t(alignments,_U(alignment)).for_each(Converter<AlignmentEntry>(this->lcdd)); +template <> void Converter<AlignmentFile>::operator()(xml_h element) const { + xml_h alignments = XML::DocumentHandler().load(element, element.attr_value(_U(ref))).root(); + xml_coll_t(alignments, _U(alignment)).for_each(Converter < AlignmentEntry > (this->lcdd)); } -template <> void Converter<Compact>::operator()(xml_h element) const { +template <> void Converter<Compact>::operator()(xml_h element) const { char text[32]; xml_elt_t compact(element); - xml_coll_t(compact,_U(includes) ).for_each(_U(gdmlFile), Converter<GdmlFile>(lcdd)); - if ( element.hasChild(_U(info)) ) - (Converter<Header>(lcdd))(xml_h(compact.child(_U(info)))); - xml_coll_t(compact,_U(define) ).for_each(_U(constant), Converter<Constant>(lcdd)); - xml_coll_t(compact,_U(materials) ).for_each(_U(element), Converter<Atom>(lcdd)); - xml_coll_t(compact,_U(materials) ).for_each(_U(material), Converter<Material>(lcdd)); - xml_coll_t(compact,_U(properties) ).for_each(_U(attributes),Converter<Property>(lcdd)); + xml_coll_t(compact, _U(includes)).for_each(_U(gdmlFile), Converter < GdmlFile > (lcdd)); + if (element.hasChild(_U(info))) + (Converter < Header > (lcdd))(xml_h(compact.child(_U(info)))); + xml_coll_t(compact, _U(define)).for_each(_U(constant), Converter < Constant > (lcdd)); + xml_coll_t(compact, _U(materials)).for_each(_U(element), Converter < Atom > (lcdd)); + xml_coll_t(compact, _U(materials)).for_each(_U(material), Converter < Material > (lcdd)); + xml_coll_t(compact, _U(properties)).for_each(_U(attributes), Converter < Property > (lcdd)); lcdd.init(); - xml_coll_t(compact,_U(limits) ).for_each(_U(limitset), Converter<LimitSet>(lcdd)); - xml_coll_t(compact,_U(display) ).for_each(_U(vis), Converter<VisAttr>(lcdd)); - xml_coll_t(compact,_U(readouts) ).for_each(_U(readout), Converter<Readout>(lcdd)); - xml_coll_t(compact,_U(detectors) ).for_each(_U(detector), Converter<DetElement>(lcdd)); - xml_coll_t(compact,_U(includes) ).for_each(_U(alignment),Converter<AlignmentFile>(lcdd)); - xml_coll_t(compact,_U(alignments) ).for_each(_U(alignment),Converter<AlignmentEntry>(lcdd)); - xml_coll_t(compact,_U(fields) ).for_each(_U(field), Converter<CartesianField>(lcdd)); - xml_coll_t(compact,_U(sensitive_detectors)).for_each(_U(sd),Converter<SensitiveDetector>(lcdd)); - ::snprintf(text,sizeof(text),"%u",xml_h(element).checksum(0)); - lcdd.addConstant(Constant("compact_checksum",text)); + xml_coll_t(compact, _U(limits)).for_each(_U(limitset), Converter < LimitSet > (lcdd)); + xml_coll_t(compact, _U(display)).for_each(_U(vis), Converter < VisAttr > (lcdd)); + xml_coll_t(compact, _U(readouts)).for_each(_U(readout), Converter < Readout > (lcdd)); + xml_coll_t(compact, _U(detectors)).for_each(_U(detector), Converter < DetElement > (lcdd)); + xml_coll_t(compact, _U(includes)).for_each(_U(alignment), Converter < AlignmentFile > (lcdd)); + xml_coll_t(compact, _U(alignments)).for_each(_U(alignment), Converter < AlignmentEntry > (lcdd)); + xml_coll_t(compact, _U(fields)).for_each(_U(field), Converter < CartesianField > (lcdd)); + xml_coll_t(compact, _U(sensitive_detectors)).for_each(_U(sd), Converter < SensitiveDetector > (lcdd)); + ::snprintf(text, sizeof(text), "%u", xml_h(element).checksum(0)); + lcdd.addConstant(Constant("compact_checksum", text)); lcdd.endDocument(); } - #ifdef _WIN32 template Converter<Atom>; template Converter<Compact>; diff --git a/DDCore/src/plugins/Geant4XML.cpp b/DDCore/src/plugins/Geant4XML.cpp index 6ca96a01a..10c3610b1 100644 --- a/DDCore/src/plugins/Geant4XML.cpp +++ b/DDCore/src/plugins/Geant4XML.cpp @@ -21,27 +21,27 @@ using namespace DD4hep; using namespace DD4hep::Geometry; namespace DD4hep { - template <> void Converter<Geant4>::operator()(xml_h e) const; - template <> void Converter<Geometry::GdmlFile>::operator()(xml_h e) const; - template <> void Converter<Geometry::Property>::operator()(xml_h e) const; - template <> void Converter<Geometry::SensitiveDetector>::operator()(xml_h e) const; + template <> void Converter<Geant4>::operator()(xml_h e) const; + template <> void Converter<Geometry::GdmlFile>::operator()(xml_h e) const; + template <> void Converter<Geometry::Property>::operator()(xml_h e) const; + template <> void Converter<Geometry::SensitiveDetector>::operator()(xml_h e) const; } -template <> void Converter<Geant4>::operator()(xml_h element) const { +template <> void Converter<Geant4>::operator()(xml_h element) const { xml_elt_t compact(element); //xml_coll_t(compact,_U(includes) ).for_each(_U(gdmlFile), Converter<Geometry::GdmlFile>(lcdd,param)); - xml_coll_t(compact,_U(properties) ).for_each(_U(attributes),Converter<Geometry::Property>(lcdd,param)); - xml_coll_t(compact,_U(sensitive_detectors)).for_each(_U(sd),Converter<Geometry::SensitiveDetector>(lcdd,param)); + xml_coll_t(compact, _U(properties)).for_each(_U(attributes), Converter < Geometry::Property > (lcdd, param)); + xml_coll_t(compact, _U(sensitive_detectors)).for_each(_U(sd), Converter < Geometry::SensitiveDetector > (lcdd, param)); } static long create_Geant4(lcdd_t& lcdd, const xml_h& element) { - (Converter<Geant4>(lcdd))(element); + (Converter < Geant4 > (lcdd))(element); return 1; } DECLARE_XML_DOC_READER(geant4,create_Geant4); static Ref_t handle_Geant4(lcdd_t& lcdd, const xml_h& element) { - (Converter<Geant4>(lcdd))(element); + (Converter < Geant4 > (lcdd))(element); return Ref_t(0); } DECLARE_XMLELEMENT(geant4_xml_setup,handle_Geant4); diff --git a/DDCore/src/plugins/LCDD2Output.cpp b/DDCore/src/plugins/LCDD2Output.cpp index 9d03dca7c..8923ba19e 100644 --- a/DDCore/src/plugins/LCDD2Output.cpp +++ b/DDCore/src/plugins/LCDD2Output.cpp @@ -21,66 +21,60 @@ #include <iostream> #include <iomanip> - using namespace std; namespace DD4hep { using namespace Geometry; void dumpNode(TGeoNode* n, int level) { - TGeoMatrix* mat = n->GetMatrix(); - TGeoVolume* vol = n->GetVolume(); - TGeoMedium* med = vol->GetMedium(); - TGeoShape* shape = vol->GetShape(); + TGeoMatrix* mat = n->GetMatrix(); + TGeoVolume* vol = n->GetVolume(); + TGeoMedium* med = vol->GetMedium(); + TGeoShape* shape = vol->GetShape(); TObjArray* nodes = vol->GetNodes(); - for(int i=0; i<level;++i) cout << " "; - cout << " ++Node:|" << n->GetName() << "| "; - cout << " Volume: " << vol->GetName() - << " material:" << med->GetName() - << " shape:" << shape->GetName() - << endl; - for(int i=0; i<level;++i) cout << " "; + for (int i = 0; i < level; ++i) + cout << " "; + cout << " ++Node:|" << n->GetName() << "| "; + cout << " Volume: " << vol->GetName() << " material:" << med->GetName() << " shape:" << shape->GetName() << endl; + for (int i = 0; i < level; ++i) + cout << " "; const Double_t* tr = mat->GetTranslation(); - cout << " matrix:|" << mat->GetName() << "|" - << mat->IsTranslation() - << mat->IsRotation() - << mat->IsScale() - << " tr:x=" << tr[0] << " y=" << tr[1] << " z=" << tr[2]; - if ( mat->IsRotation() ) { - Double_t theta,phi,psi; + cout << " matrix:|" << mat->GetName() << "|" << mat->IsTranslation() << mat->IsRotation() << mat->IsScale() + << " tr:x=" << tr[0] << " y=" << tr[1] << " z=" << tr[2]; + if (mat->IsRotation()) { + Double_t theta, phi, psi; TGeoRotation rot(*mat); - rot.GetAngles(phi,theta,psi); + rot.GetAngles(phi, theta, psi); cout << " rot: theta:" << theta << " phi:" << phi << " psi:" << psi; } cout << endl; PlacedVolume plv(n); - for(int i=0; i<level;++i) cout << " "; + for (int i = 0; i < level; ++i) + cout << " "; cout << " volume:" << plv.toString(); cout << endl; TIter next(nodes); TGeoNode *geoNode; while ((geoNode = (TGeoNode *) next())) { - dumpNode(geoNode,level+1); + dumpNode(geoNode, level + 1); } } void dumpVolume(TGeoVolume* vol, int level) { - TObjArray* nodes = vol->GetNodes(); - TGeoMedium* med = vol->GetMedium(); - TGeoShape* shape = vol->GetShape(); + TObjArray* nodes = vol->GetNodes(); + TGeoMedium* med = vol->GetMedium(); + TGeoShape* shape = vol->GetShape(); - for(int i=0; i<level;++i) cout << " "; - cout << "++Volume: " << vol->GetName() - << " material:" << med->GetName() - << " shape:" << shape->GetName() - << endl; + for (int i = 0; i < level; ++i) + cout << " "; + cout << "++Volume: " << vol->GetName() << " material:" << med->GetName() << " shape:" << shape->GetName() << endl; TIter next(nodes); TGeoNode *geoNode; while ((geoNode = (TGeoNode *) next())) { - dumpNode(geoNode,level+1); + dumpNode(geoNode, level + 1); } } void dumpTopVolume(const LCDD& lcdd) { - dumpVolume(lcdd.manager().GetTopVolume(),0); + dumpVolume(lcdd.manager().GetTopVolume(), 0); } } diff --git a/DDCore/src/plugins/LCDDConverter.cpp b/DDCore/src/plugins/LCDDConverter.cpp index 45b387d5c..0fadea41f 100644 --- a/DDCore/src/plugins/LCDDConverter.cpp +++ b/DDCore/src/plugins/LCDDConverter.cpp @@ -51,7 +51,7 @@ using namespace std; namespace { typedef Position XYZRotation; #if 0 - XYZRotation getXYZangles(const Double_t* r) { + XYZRotation getXYZangles(const Double_t* r) { Double_t cosb = sqrt(r[0]*r[0] + r[1]*r[1]); if (cosb > 0.00001) { return XYZRotation(atan2(r[5], r[8]), atan2(-r[2], cosb), atan2(r[1], r[0])); @@ -59,40 +59,42 @@ namespace { return XYZRotation(atan2(-r[7], r[4]),atan2(-r[2], cosb),0); } #endif - XYZRotation getXYZangles(const Double_t* rotationMatrix) { + XYZRotation getXYZangles(const Double_t* rotationMatrix) { Double_t a, b, c; - Double_t rad = 1.0;// RAD by default! 180.0 / TMath::ACos(-1.0); + Double_t rad = 1.0; // RAD by default! 180.0 / TMath::ACos(-1.0); const Double_t *r = rotationMatrix; Double_t cosb = TMath::Sqrt(r[0] * r[0] + r[1] * r[1]); if (cosb > 0.00001) { a = TMath::ATan2(r[5], r[8]) * rad; b = TMath::ATan2(-r[2], cosb) * rad; c = TMath::ATan2(r[1], r[0]) * rad; - } else { + } + else { a = TMath::ATan2(-r[7], r[4]) * rad; b = TMath::ATan2(-r[2], cosb) * rad; c = 0; } - return XYZRotation(a,b,c); + return XYZRotation(a, b, c); } } -void LCDDConverter::GeometryInfo::check(const string& name, const TNamed* n,map<string,const TNamed*>& m) const { - map<string,const TNamed*>::const_iterator i=m.find(name); - if ( i != m.end() ) { +void LCDDConverter::GeometryInfo::check(const string& name, const TNamed* n, map<string, const TNamed*>& m) const { + map<string, const TNamed*>::const_iterator i = m.find(name); + if (i != m.end()) { const char* isa = n ? n->IsA()->GetName() : (*i).second ? (*i).second->IsA()->GetName() : "Unknown"; - cout << isa << "(position): duplicate entry with name:" << name - << " " << (void*)n << " " << (void*)(*i).second << endl; + cout << isa << "(position): duplicate entry with name:" << name << " " << (void*) n << " " << (void*) (*i).second << endl; } - m.insert(make_pair(name,n)); + m.insert(make_pair(name, n)); } /// Initializing Constructor -LCDDConverter::LCDDConverter( LCDD& lcdd ) : m_lcdd(lcdd), m_dataPtr(0) { +LCDDConverter::LCDDConverter(LCDD& lcdd) + : m_lcdd(lcdd), m_dataPtr(0) { } -LCDDConverter::~LCDDConverter() { - if ( m_dataPtr ) delete m_dataPtr; +LCDDConverter::~LCDDConverter() { + if (m_dataPtr) + delete m_dataPtr; m_dataPtr = 0; } @@ -100,16 +102,16 @@ LCDDConverter::~LCDDConverter() { xml_h LCDDConverter::handleElement(const string& name, const TGeoElement* element) const { GeometryInfo& geo = data(); xml_h e = geo.xmlElements[element]; - if ( !e ) { - xml_elt_t atom(geo.doc,_U(atom)); - geo.doc_materials.append(e=xml_elt_t(geo.doc,_U(element))); + if (!e) { + xml_elt_t atom(geo.doc, _U(atom)); + geo.doc_materials.append(e = xml_elt_t(geo.doc, _U(element))); e.append(atom); - e.setAttr(_U(name),element->GetName()); - e.setAttr(_U(formula),element->GetName()); - e.setAttr(_U(Z),element->Z()); - atom.setAttr(_U(type),"A"); - atom.setAttr(_U(unit),"g/mol"); - atom.setAttr(_U(value),element->A() /* *(g/mole) */); + e.setAttr(_U(name), element->GetName()); + e.setAttr(_U(formula), element->GetName()); + e.setAttr(_U(Z), element->Z()); + atom.setAttr(_U(type), "A"); + atom.setAttr(_U(unit), "g/mol"); + atom.setAttr(_U(value), element->A() /* *(g/mole) */); geo.xmlElements[element] = e; } return e; @@ -119,56 +121,57 @@ xml_h LCDDConverter::handleElement(const string& name, const TGeoElement* elemen xml_h LCDDConverter::handleMaterial(const string& name, const TGeoMedium* medium) const { GeometryInfo& geo = data(); xml_h mat = geo.xmlMaterials[medium]; - if ( !mat ) { + if (!mat) { xml_h obj; TGeoMaterial* m = medium->GetMaterial(); - double d = m->GetDensity(); //*(gram/cm3); - if ( d < 1e-25 ) d = 1e-25; - mat = xml_elt_t(geo.doc,_U(material)); - mat.setAttr(_U(name),medium->GetName()); - mat.append(obj=xml_elt_t(geo.doc,_U(D))); - obj.setAttr(_U(value),d /* *(g/cm3) */); - obj.setAttr(_U(unit),"g/cm3"); - obj.setAttr(_U(type),"density"); - - geo.checkMaterial(name,medium); - if ( name == "B" ) { + double d = m->GetDensity(); //*(gram/cm3); + if (d < 1e-25) + d = 1e-25; + mat = xml_elt_t(geo.doc, _U(material)); + mat.setAttr(_U(name), medium->GetName()); + mat.append(obj = xml_elt_t(geo.doc, _U(D))); + obj.setAttr(_U(value), d /* *(g/cm3) */); + obj.setAttr(_U(unit), "g/cm3"); + obj.setAttr(_U(type), "density"); + + geo.checkMaterial(name, medium); + if (name == "B") { cout << "Converting material:" << name << endl; } - if ( m->IsMixture() ) { - TGeoMixture *mix = (TGeoMixture*)m; + if (m->IsMixture()) { + TGeoMixture *mix = (TGeoMixture*) m; const double *wmix = mix->GetWmixt(); - const int *nmix = mix->GetNmixt(); - double sum = 0e0; - for (int i=0, n=mix->GetNelements(); i < n; i++) { - TGeoElement *elt = mix->GetElement(i); - handleElement(elt->GetName(),elt); - sum += wmix[i]; + const int *nmix = mix->GetNmixt(); + double sum = 0e0; + for (int i = 0, n = mix->GetNelements(); i < n; i++) { + TGeoElement *elt = mix->GetElement(i); + handleElement(elt->GetName(), elt); + sum += wmix[i]; } - for (int i=0, n=mix->GetNelements(); i < n; i++) { - TGeoElement *elt = mix->GetElement(i); - string formula = elt->GetTitle()+string("_elm"); - if ( nmix ) { - mat.append(obj=xml_elt_t(geo.doc,_U(composite))); - obj.setAttr(_U(n),nmix[i]); - } - else { - mat.append(obj=xml_elt_t(geo.doc,_U(fraction))); - obj.setAttr(_U(n),wmix[i]/sum); - } - obj.setAttr(_U(ref),elt->GetName()); + for (int i = 0, n = mix->GetNelements(); i < n; i++) { + TGeoElement *elt = mix->GetElement(i); + string formula = elt->GetTitle() + string("_elm"); + if (nmix) { + mat.append(obj = xml_elt_t(geo.doc, _U(composite))); + obj.setAttr(_U(n), nmix[i]); + } + else { + mat.append(obj = xml_elt_t(geo.doc, _U(fraction))); + obj.setAttr(_U(n), wmix[i] / sum); + } + obj.setAttr(_U(ref), elt->GetName()); } } else { TGeoElement *elt = m->GetElement(0); cout << "Converting non mixing material:" << name << endl; - xml_elt_t atom(geo.doc,_U(atom)); - handleElement(elt->GetName(),elt); + xml_elt_t atom(geo.doc, _U(atom)); + handleElement(elt->GetName(), elt); mat.append(atom); - mat.setAttr(_U(Z),m->GetZ()); - atom.setAttr(_U(type),"A"); - atom.setAttr(_U(unit),"g/mol"); - atom.setAttr(_U(value),m->GetA() /* *(g/mole) */); + mat.setAttr(_U(Z), m->GetZ()); + atom.setAttr(_U(type), "A"); + atom.setAttr(_U(unit), "g/mol"); + atom.setAttr(_U(value), m->GetA() /* *(g/mole) */); } geo.doc_materials.append(mat); geo.xmlMaterials[medium] = mat; @@ -177,338 +180,337 @@ xml_h LCDDConverter::handleMaterial(const string& name, const TGeoMedium* medium } /// Dump solid in GDML format to output stream -xml_h LCDDConverter::handleSolid(const string& name, const TGeoShape* shape) const { +xml_h LCDDConverter::handleSolid(const string& name, const TGeoShape* shape) const { GeometryInfo& geo = data(); SolidMap::iterator sit = geo.xmlSolids.find(shape); - if ( !shape ) { + if (!shape) { // This is an invalid volume. Let's pray returning nothing will work, // and the non-existing solid is also nowhere referenced in the GDML. return xml_h(0); } - else if ( sit != geo.xmlSolids.end() ) { + else if (sit != geo.xmlSolids.end()) { // The solidis already registered. Return the reference return (*sit).second; } - else if ( shape->IsA() == TGeoShapeAssembly::Class() ) { + else if (shape->IsA() == TGeoShapeAssembly::Class()) { // Assemblies have no shape in GDML. Hence, return nothing. return xml_h(0); } - else { + else { xml_h solid(0); xml_h zplane(0); - geo.checkShape(name,shape); - if ( shape->IsA() == TGeoBBox::Class() ) { - const TGeoBBox* s = (const TGeoBBox*)shape; - geo.doc_solids.append(solid = xml_elt_t(geo.doc,_U(box))); - solid.setAttr(_U(name),Unicode(name)); - solid.setAttr(_U(x), 2*s->GetDX()*CM_2_MM); - solid.setAttr(_U(y), 2*s->GetDY()*CM_2_MM); - solid.setAttr(_U(z), 2*s->GetDZ()*CM_2_MM); - solid.setAttr(_U(lunit),"mm"); + geo.checkShape(name, shape); + if (shape->IsA() == TGeoBBox::Class()) { + const TGeoBBox* s = (const TGeoBBox*) shape; + geo.doc_solids.append(solid = xml_elt_t(geo.doc, _U(box))); + solid.setAttr(_U(name), Unicode(name)); + solid.setAttr(_U(x), 2 * s->GetDX() * CM_2_MM); + solid.setAttr(_U(y), 2 * s->GetDY() * CM_2_MM); + solid.setAttr(_U(z), 2 * s->GetDZ() * CM_2_MM); + solid.setAttr(_U(lunit), "mm"); } - else if ( shape->IsA() == TGeoTube::Class() ) { - const TGeoTube* s = (const TGeoTube*)shape; - geo.doc_solids.append(solid = xml_elt_t(geo.doc,_U(tube))); - solid.setAttr(_U(name),Unicode(name)); - solid.setAttr(_U(rmin), s->GetRmin()*CM_2_MM); - solid.setAttr(_U(rmax), s->GetRmax()*CM_2_MM); - solid.setAttr(_U(z), 2*s->GetDz()*CM_2_MM); + else if (shape->IsA() == TGeoTube::Class()) { + const TGeoTube* s = (const TGeoTube*) shape; + geo.doc_solids.append(solid = xml_elt_t(geo.doc, _U(tube))); + solid.setAttr(_U(name), Unicode(name)); + solid.setAttr(_U(rmin), s->GetRmin() * CM_2_MM); + solid.setAttr(_U(rmax), s->GetRmax() * CM_2_MM); + solid.setAttr(_U(z), 2 * s->GetDz() * CM_2_MM); solid.setAttr(_U(startphi), 0e0); - solid.setAttr(_U(deltaphi), 2*M_PI); - solid.setAttr(_U(aunit),"rad"); - solid.setAttr(_U(lunit),"mm"); + solid.setAttr(_U(deltaphi), 2 * M_PI); + solid.setAttr(_U(aunit), "rad"); + solid.setAttr(_U(lunit), "mm"); } - else if ( shape->IsA() == TGeoEltu::Class() ) { - const TGeoEltu* s = (const TGeoEltu*)shape; - geo.doc_solids.append(solid = xml_elt_t(geo.doc,_U(eltube))); + else if (shape->IsA() == TGeoEltu::Class()) { + const TGeoEltu* s = (const TGeoEltu*) shape; + geo.doc_solids.append(solid = xml_elt_t(geo.doc, _U(eltube))); solid.setAttr(_U(name), Unicode(name)); - solid.setAttr(_U(dx), s->GetA() *CM_2_MM); - solid.setAttr(_U(dy), s->GetB() *CM_2_MM); - solid.setAttr(_U(dz), s->GetDz()*CM_2_MM); - solid.setAttr(_U(lunit),"mm"); + solid.setAttr(_U(dx), s->GetA() * CM_2_MM); + solid.setAttr(_U(dy), s->GetB() * CM_2_MM); + solid.setAttr(_U(dz), s->GetDz() * CM_2_MM); + solid.setAttr(_U(lunit), "mm"); } - else if ( shape->IsA() == TGeoTubeSeg::Class() ) { - const TGeoTubeSeg* s = (const TGeoTubeSeg*)shape; - geo.doc_solids.append(solid = xml_elt_t(geo.doc,_U(tube))); - solid.setAttr(_U(name),Unicode(name)); - solid.setAttr(_U(rmin), s->GetRmin()*CM_2_MM); - solid.setAttr(_U(rmax), s->GetRmax()*CM_2_MM); - solid.setAttr(_U(z), 2*s->GetDz()*CM_2_MM); // Full zlen in GDML, half zlen in TGeo - solid.setAttr(_U(startphi), s->GetPhi1()*DEGREE_2_RAD); - solid.setAttr(_U(deltaphi), s->GetPhi2()*DEGREE_2_RAD); - solid.setAttr(_U(aunit),"rad"); - solid.setAttr(_U(lunit),"mm"); + else if (shape->IsA() == TGeoTubeSeg::Class()) { + const TGeoTubeSeg* s = (const TGeoTubeSeg*) shape; + geo.doc_solids.append(solid = xml_elt_t(geo.doc, _U(tube))); + solid.setAttr(_U(name), Unicode(name)); + solid.setAttr(_U(rmin), s->GetRmin() * CM_2_MM); + solid.setAttr(_U(rmax), s->GetRmax() * CM_2_MM); + solid.setAttr(_U(z), 2 * s->GetDz() * CM_2_MM); // Full zlen in GDML, half zlen in TGeo + solid.setAttr(_U(startphi), s->GetPhi1() * DEGREE_2_RAD); + solid.setAttr(_U(deltaphi), s->GetPhi2() * DEGREE_2_RAD); + solid.setAttr(_U(aunit), "rad"); + solid.setAttr(_U(lunit), "mm"); } - else if ( shape->IsA() == TGeoTubeSeg::Class() ) { - const TGeoTubeSeg* s = (const TGeoTubeSeg*)shape; - geo.doc_solids.append(solid = xml_elt_t(geo.doc,_U(tube))); - solid.setAttr(_U(name),Unicode(name)); - solid.setAttr(_U(rmin), s->GetRmin()*CM_2_MM); - solid.setAttr(_U(rmax), s->GetRmax()*CM_2_MM); - solid.setAttr(_U(z), 2*s->GetDz()*CM_2_MM); // Full zlen in GDML, half zlen in TGeo - solid.setAttr(_U(startphi), s->GetPhi1()*DEGREE_2_RAD); - solid.setAttr(_U(deltaphi), s->GetPhi2()*DEGREE_2_RAD); - solid.setAttr(_U(aunit),"rad"); - solid.setAttr(_U(lunit),"mm"); + else if (shape->IsA() == TGeoTubeSeg::Class()) { + const TGeoTubeSeg* s = (const TGeoTubeSeg*) shape; + geo.doc_solids.append(solid = xml_elt_t(geo.doc, _U(tube))); + solid.setAttr(_U(name), Unicode(name)); + solid.setAttr(_U(rmin), s->GetRmin() * CM_2_MM); + solid.setAttr(_U(rmax), s->GetRmax() * CM_2_MM); + solid.setAttr(_U(z), 2 * s->GetDz() * CM_2_MM); // Full zlen in GDML, half zlen in TGeo + solid.setAttr(_U(startphi), s->GetPhi1() * DEGREE_2_RAD); + solid.setAttr(_U(deltaphi), s->GetPhi2() * DEGREE_2_RAD); + solid.setAttr(_U(aunit), "rad"); + solid.setAttr(_U(lunit), "mm"); } - else if ( shape->IsA() == TGeoHype::Class() ) { - const TGeoHype* s = (const TGeoHype*)shape; - geo.doc_solids.append(solid = xml_elt_t(geo.doc,_U(hype))); - solid.setAttr(_U(name),Unicode(name)); - solid.setAttr(_U(rmin), 2*s->GetRmin()*CM_2_MM); - solid.setAttr(_U(rmax), 2*s->GetRmax()*CM_2_MM); - solid.setAttr(_U(outst), 2*s->GetStOut()*CM_2_MM); - solid.setAttr(_U(z), 2*s->GetDz()*CM_2_MM); // Full zlen in GDML, half zlen in TGeo - solid.setAttr(_U(aunit),"rad"); - solid.setAttr(_U(lunit),"mm"); + else if (shape->IsA() == TGeoHype::Class()) { + const TGeoHype* s = (const TGeoHype*) shape; + geo.doc_solids.append(solid = xml_elt_t(geo.doc, _U(hype))); + solid.setAttr(_U(name), Unicode(name)); + solid.setAttr(_U(rmin), 2 * s->GetRmin() * CM_2_MM); + solid.setAttr(_U(rmax), 2 * s->GetRmax() * CM_2_MM); + solid.setAttr(_U(outst), 2 * s->GetStOut() * CM_2_MM); + solid.setAttr(_U(z), 2 * s->GetDz() * CM_2_MM); // Full zlen in GDML, half zlen in TGeo + solid.setAttr(_U(aunit), "rad"); + solid.setAttr(_U(lunit), "mm"); } - else if ( shape->IsA() == TGeoTrd2::Class() ) { - const TGeoTrd2* s = (const TGeoTrd2*)shape; - geo.doc_solids.append(solid = xml_elt_t(geo.doc,_U(trd))); - solid.setAttr(_U(name),Unicode(name)); - solid.setAttr(_U(x1), 2*s->GetDx1()*CM_2_MM); - solid.setAttr(_U(x2), 2*s->GetDx2()*CM_2_MM); - solid.setAttr(_U(y1), 2*s->GetDy1()*CM_2_MM); - solid.setAttr(_U(y2), 2*s->GetDy2()*CM_2_MM); - solid.setAttr(_U(z), 2*s->GetDz() *CM_2_MM); // Full zlen in GDML, half zlen in TGeo - solid.setAttr(_U(lunit),"mm"); + else if (shape->IsA() == TGeoTrd2::Class()) { + const TGeoTrd2* s = (const TGeoTrd2*) shape; + geo.doc_solids.append(solid = xml_elt_t(geo.doc, _U(trd))); + solid.setAttr(_U(name), Unicode(name)); + solid.setAttr(_U(x1), 2 * s->GetDx1() * CM_2_MM); + solid.setAttr(_U(x2), 2 * s->GetDx2() * CM_2_MM); + solid.setAttr(_U(y1), 2 * s->GetDy1() * CM_2_MM); + solid.setAttr(_U(y2), 2 * s->GetDy2() * CM_2_MM); + solid.setAttr(_U(z), 2 * s->GetDz() * CM_2_MM); // Full zlen in GDML, half zlen in TGeo + solid.setAttr(_U(lunit), "mm"); } - else if ( shape->IsA() == TGeoTrap::Class() ) { - const TGeoTrap* s = (const TGeoTrap*)shape; - geo.doc_solids.append(solid = xml_elt_t(geo.doc,_U(trap))); - solid.setAttr(_U(name),Unicode(name)); - solid.setAttr(_U(z), 2*s->GetDz()*CM_2_MM); // Full zlen in GDML, half zlen in TGeo - solid.setAttr(_U(x1), 2*s->GetBl1()*CM_2_MM); - solid.setAttr(_U(x2), 2*s->GetTl1()*CM_2_MM); - solid.setAttr(_U(x3), 2*s->GetBl2()*CM_2_MM); - solid.setAttr(_U(x4), 2*s->GetTl2()*CM_2_MM); - solid.setAttr(_U(y1), 2*s->GetH1()*CM_2_MM); - solid.setAttr(_U(y2), 2*s->GetH2()*CM_2_MM); - solid.setAttr(_U(alpha1),s->GetAlpha1()*DEGREE_2_RAD); - solid.setAttr(_U(alpha2),s->GetAlpha2()*DEGREE_2_RAD); - solid.setAttr(_U(theta), s->GetTheta()*DEGREE_2_RAD); - solid.setAttr(_U(phi), s->GetPhi()*DEGREE_2_RAD); - solid.setAttr(_U(aunit),"rad"); - solid.setAttr(_U(lunit),"mm"); + else if (shape->IsA() == TGeoTrap::Class()) { + const TGeoTrap* s = (const TGeoTrap*) shape; + geo.doc_solids.append(solid = xml_elt_t(geo.doc, _U(trap))); + solid.setAttr(_U(name), Unicode(name)); + solid.setAttr(_U(z), 2 * s->GetDz() * CM_2_MM); // Full zlen in GDML, half zlen in TGeo + solid.setAttr(_U(x1), 2 * s->GetBl1() * CM_2_MM); + solid.setAttr(_U(x2), 2 * s->GetTl1() * CM_2_MM); + solid.setAttr(_U(x3), 2 * s->GetBl2() * CM_2_MM); + solid.setAttr(_U(x4), 2 * s->GetTl2() * CM_2_MM); + solid.setAttr(_U(y1), 2 * s->GetH1() * CM_2_MM); + solid.setAttr(_U(y2), 2 * s->GetH2() * CM_2_MM); + solid.setAttr(_U(alpha1), s->GetAlpha1() * DEGREE_2_RAD); + solid.setAttr(_U(alpha2), s->GetAlpha2() * DEGREE_2_RAD); + solid.setAttr(_U(theta), s->GetTheta() * DEGREE_2_RAD); + solid.setAttr(_U(phi), s->GetPhi() * DEGREE_2_RAD); + solid.setAttr(_U(aunit), "rad"); + solid.setAttr(_U(lunit), "mm"); } - else if ( shape->IsA() == TGeoPara::Class() ) { - const TGeoPara* s = (const TGeoPara*)shape; - geo.doc_solids.append(solid = xml_elt_t(geo.doc,_U(para))); - solid.setAttr(_U(name),Unicode(name)); - solid.setAttr(_U(x), s->GetX()*CM_2_MM); - solid.setAttr(_U(y), s->GetY()*CM_2_MM); - solid.setAttr(_U(z), s->GetZ()*CM_2_MM); - solid.setAttr(_U(alpha),s->GetAlpha()*DEGREE_2_RAD); - solid.setAttr(_U(theta),s->GetTheta()*DEGREE_2_RAD); - solid.setAttr(_U(phi), s->GetPhi()*DEGREE_2_RAD); - solid.setAttr(_U(aunit),"rad"); - solid.setAttr(_U(lunit),"mm"); + else if (shape->IsA() == TGeoPara::Class()) { + const TGeoPara* s = (const TGeoPara*) shape; + geo.doc_solids.append(solid = xml_elt_t(geo.doc, _U(para))); + solid.setAttr(_U(name), Unicode(name)); + solid.setAttr(_U(x), s->GetX() * CM_2_MM); + solid.setAttr(_U(y), s->GetY() * CM_2_MM); + solid.setAttr(_U(z), s->GetZ() * CM_2_MM); + solid.setAttr(_U(alpha), s->GetAlpha() * DEGREE_2_RAD); + solid.setAttr(_U(theta), s->GetTheta() * DEGREE_2_RAD); + solid.setAttr(_U(phi), s->GetPhi() * DEGREE_2_RAD); + solid.setAttr(_U(aunit), "rad"); + solid.setAttr(_U(lunit), "mm"); } - else if ( shape->IsA() == TGeoPgon::Class() ) { - const TGeoPgon* s = (const TGeoPgon*)shape; - geo.doc_solids.append(solid = xml_elt_t(geo.doc,_U(polyhedra))); - solid.setAttr(_U(name), Unicode(name)); - solid.setAttr(_U(startphi),s->GetPhi1()*DEGREE_2_RAD); - solid.setAttr(_U(deltaphi),s->GetDphi()*DEGREE_2_RAD); - solid.setAttr(_U(numsides),s->GetNedges()); - solid.setAttr(_U(aunit), "rad"); - solid.setAttr(_U(lunit), "mm"); - for( size_t i=0; i<s->GetNz(); ++i ) { - zplane = xml_elt_t(geo.doc,_U(zplane)); - zplane.setAttr(_U(rmin),s->GetRmin(i)*CM_2_MM); - zplane.setAttr(_U(rmax),s->GetRmax(i)*CM_2_MM); - zplane.setAttr(_U(z),s->GetZ(i)*CM_2_MM); - solid.append(zplane); + else if (shape->IsA() == TGeoPgon::Class()) { + const TGeoPgon* s = (const TGeoPgon*) shape; + geo.doc_solids.append(solid = xml_elt_t(geo.doc, _U(polyhedra))); + solid.setAttr(_U(name), Unicode(name)); + solid.setAttr(_U(startphi), s->GetPhi1() * DEGREE_2_RAD); + solid.setAttr(_U(deltaphi), s->GetDphi() * DEGREE_2_RAD); + solid.setAttr(_U(numsides), s->GetNedges()); + solid.setAttr(_U(aunit), "rad"); + solid.setAttr(_U(lunit), "mm"); + for (size_t i = 0; i < s->GetNz(); ++i) { + zplane = xml_elt_t(geo.doc, _U(zplane)); + zplane.setAttr(_U(rmin), s->GetRmin(i) * CM_2_MM); + zplane.setAttr(_U(rmax), s->GetRmax(i) * CM_2_MM); + zplane.setAttr(_U(z), s->GetZ(i) * CM_2_MM); + solid.append(zplane); } } - else if ( shape->IsA() == TGeoPcon::Class() ) { - const TGeoPcon* s = (const TGeoPcon*)shape; - geo.doc_solids.append(solid = xml_elt_t(geo.doc,_U(polycone))); - solid.setAttr(_U(name),Unicode(name)); - solid.setAttr(_U(startphi),s->GetPhi1()*DEGREE_2_RAD); - solid.setAttr(_U(deltaphi),s->GetDphi()*DEGREE_2_RAD); - solid.setAttr(_U(aunit),"rad"); - solid.setAttr(_U(lunit),"mm"); - for( size_t i=0; i<s->GetNz(); ++i ) { - zplane = xml_elt_t(geo.doc,_U(zplane)); - zplane.setAttr(_U(rmin),s->GetRmin(i)*CM_2_MM); - zplane.setAttr(_U(rmax),s->GetRmax(i)*CM_2_MM); - zplane.setAttr(_U(z),s->GetZ(i)*CM_2_MM); - solid.append(zplane); + else if (shape->IsA() == TGeoPcon::Class()) { + const TGeoPcon* s = (const TGeoPcon*) shape; + geo.doc_solids.append(solid = xml_elt_t(geo.doc, _U(polycone))); + solid.setAttr(_U(name), Unicode(name)); + solid.setAttr(_U(startphi), s->GetPhi1() * DEGREE_2_RAD); + solid.setAttr(_U(deltaphi), s->GetDphi() * DEGREE_2_RAD); + solid.setAttr(_U(aunit), "rad"); + solid.setAttr(_U(lunit), "mm"); + for (size_t i = 0; i < s->GetNz(); ++i) { + zplane = xml_elt_t(geo.doc, _U(zplane)); + zplane.setAttr(_U(rmin), s->GetRmin(i) * CM_2_MM); + zplane.setAttr(_U(rmax), s->GetRmax(i) * CM_2_MM); + zplane.setAttr(_U(z), s->GetZ(i) * CM_2_MM); + solid.append(zplane); } } - else if ( shape->IsA() == TGeoConeSeg::Class() ) { - const TGeoConeSeg* s = (const TGeoConeSeg*)shape; - geo.doc_solids.append(solid = xml_elt_t(geo.doc,_U(polycone))); - solid.setAttr(_U(name),Unicode(name)); - solid.setAttr(_U(startphi), s->GetPhi1()*DEGREE_2_RAD); - solid.setAttr(_U(deltaphi),(s->GetPhi2()-s->GetPhi1())*DEGREE_2_RAD); - solid.setAttr(_U(aunit),"rad"); - solid.setAttr(_U(lunit),"mm"); - xml_elt_t zplane = xml_elt_t(geo.doc,_U(zplane)); - zplane.setAttr(_U(rmin), s->GetRmin1()*CM_2_MM); - zplane.setAttr(_U(rmax), s->GetRmax1()*CM_2_MM); - zplane.setAttr(_U(z), -s->GetDz()*CM_2_MM); + else if (shape->IsA() == TGeoConeSeg::Class()) { + const TGeoConeSeg* s = (const TGeoConeSeg*) shape; + geo.doc_solids.append(solid = xml_elt_t(geo.doc, _U(polycone))); + solid.setAttr(_U(name), Unicode(name)); + solid.setAttr(_U(startphi), s->GetPhi1() * DEGREE_2_RAD); + solid.setAttr(_U(deltaphi), (s->GetPhi2() - s->GetPhi1()) * DEGREE_2_RAD); + solid.setAttr(_U(aunit), "rad"); + solid.setAttr(_U(lunit), "mm"); + xml_elt_t zplane = xml_elt_t(geo.doc, _U(zplane)); + zplane.setAttr(_U(rmin), s->GetRmin1() * CM_2_MM); + zplane.setAttr(_U(rmax), s->GetRmax1() * CM_2_MM); + zplane.setAttr(_U(z), -s->GetDz() * CM_2_MM); solid.append(zplane); - zplane = xml_elt_t(geo.doc,_U(zplane)); - zplane.setAttr(_U(rmin), s->GetRmin2()*CM_2_MM); - zplane.setAttr(_U(rmax), s->GetRmax2()*CM_2_MM); - zplane.setAttr(_U(z), s->GetDz()*CM_2_MM); + zplane = xml_elt_t(geo.doc, _U(zplane)); + zplane.setAttr(_U(rmin), s->GetRmin2() * CM_2_MM); + zplane.setAttr(_U(rmax), s->GetRmax2() * CM_2_MM); + zplane.setAttr(_U(z), s->GetDz() * CM_2_MM); solid.append(zplane); #if 0 - solid.setAttr(_U(z), 2*s->GetDz()*CM_2_MM); - solid.setAttr(_U(rmin1), s->GetRmin1()*CM_2_MM); - solid.setAttr(_U(rmin2), s->GetRmin2()*CM_2_MM); - solid.setAttr(_U(rmax1), s->GetRmax1()*CM_2_MM); - solid.setAttr(_U(rmax2), s->GetRmax2()*CM_2_MM); + solid.setAttr(_U(z), 2*s->GetDz()*CM_2_MM); + solid.setAttr(_U(rmin1), s->GetRmin1()*CM_2_MM); + solid.setAttr(_U(rmin2), s->GetRmin2()*CM_2_MM); + solid.setAttr(_U(rmax1), s->GetRmax1()*CM_2_MM); + solid.setAttr(_U(rmax2), s->GetRmax2()*CM_2_MM); #endif } - else if ( shape->IsA() == TGeoCone::Class() ) { - const TGeoCone* s = (const TGeoCone*)shape; - geo.doc_solids.append(solid = xml_elt_t(geo.doc,_U(cone))); - solid.setAttr(_U(name),Unicode(name)); - solid.setAttr(_U(z), 2*s->GetDz()*CM_2_MM); - solid.setAttr(_U(rmin1), s->GetRmin1()*CM_2_MM); - solid.setAttr(_U(rmax1), s->GetRmax1()*CM_2_MM); - solid.setAttr(_U(rmin2), s->GetRmin2()*CM_2_MM); - solid.setAttr(_U(rmax2), s->GetRmax2()*CM_2_MM); - solid.setAttr(_U(startphi),0e0); - solid.setAttr(_U(deltaphi),2*M_PI); - solid.setAttr(_U(aunit),"rad"); - solid.setAttr(_U(lunit),"mm"); + else if (shape->IsA() == TGeoCone::Class()) { + const TGeoCone* s = (const TGeoCone*) shape; + geo.doc_solids.append(solid = xml_elt_t(geo.doc, _U(cone))); + solid.setAttr(_U(name), Unicode(name)); + solid.setAttr(_U(z), 2 * s->GetDz() * CM_2_MM); + solid.setAttr(_U(rmin1), s->GetRmin1() * CM_2_MM); + solid.setAttr(_U(rmax1), s->GetRmax1() * CM_2_MM); + solid.setAttr(_U(rmin2), s->GetRmin2() * CM_2_MM); + solid.setAttr(_U(rmax2), s->GetRmax2() * CM_2_MM); + solid.setAttr(_U(startphi), 0e0); + solid.setAttr(_U(deltaphi), 2 * M_PI); + solid.setAttr(_U(aunit), "rad"); + solid.setAttr(_U(lunit), "mm"); } - else if ( shape->IsA() == TGeoParaboloid::Class() ) { - const TGeoParaboloid* s = (const TGeoParaboloid*)shape; - geo.doc_solids.append(solid = xml_elt_t(geo.doc,_U(paraboloid))); - solid.setAttr(_U(name),Unicode(name)); - solid.setAttr(_U(rlo),s->GetRlo()*CM_2_MM); - solid.setAttr(_U(rhi),s->GetRhi()*CM_2_MM); - solid.setAttr(_U(dz),s->GetDz()*CM_2_MM); - solid.setAttr(_U(lunit),"mm"); + else if (shape->IsA() == TGeoParaboloid::Class()) { + const TGeoParaboloid* s = (const TGeoParaboloid*) shape; + geo.doc_solids.append(solid = xml_elt_t(geo.doc, _U(paraboloid))); + solid.setAttr(_U(name), Unicode(name)); + solid.setAttr(_U(rlo), s->GetRlo() * CM_2_MM); + solid.setAttr(_U(rhi), s->GetRhi() * CM_2_MM); + solid.setAttr(_U(dz), s->GetDz() * CM_2_MM); + solid.setAttr(_U(lunit), "mm"); } - else if ( shape->IsA() == TGeoSphere::Class() ) { - const TGeoSphere* s = (const TGeoSphere*)shape; - geo.doc_solids.append(solid = xml_elt_t(geo.doc,_U(sphere))); - solid.setAttr(_U(name), Unicode(name)); - solid.setAttr(_U(rmin), s->GetRmin()*CM_2_MM); - solid.setAttr(_U(rmax), s->GetRmax()*CM_2_MM); - solid.setAttr(_U(startphi), s->GetPhi1()*DEGREE_2_RAD); - solid.setAttr(_U(deltaphi), (s->GetPhi2()-s->GetPhi1())*DEGREE_2_RAD); - solid.setAttr(_U(starttheta), s->GetTheta1()*DEGREE_2_RAD); - solid.setAttr(_U(deltatheta), (s->GetTheta2()-s->GetTheta1())*DEGREE_2_RAD); - solid.setAttr(_U(aunit),"rad"); - solid.setAttr(_U(lunit),"mm"); + else if (shape->IsA() == TGeoSphere::Class()) { + const TGeoSphere* s = (const TGeoSphere*) shape; + geo.doc_solids.append(solid = xml_elt_t(geo.doc, _U(sphere))); + solid.setAttr(_U(name), Unicode(name)); + solid.setAttr(_U(rmin), s->GetRmin() * CM_2_MM); + solid.setAttr(_U(rmax), s->GetRmax() * CM_2_MM); + solid.setAttr(_U(startphi), s->GetPhi1() * DEGREE_2_RAD); + solid.setAttr(_U(deltaphi), (s->GetPhi2() - s->GetPhi1()) * DEGREE_2_RAD); + solid.setAttr(_U(starttheta), s->GetTheta1() * DEGREE_2_RAD); + solid.setAttr(_U(deltatheta), (s->GetTheta2() - s->GetTheta1()) * DEGREE_2_RAD); + solid.setAttr(_U(aunit), "rad"); + solid.setAttr(_U(lunit), "mm"); } - else if ( shape->IsA() == TGeoTorus::Class() ) { - const TGeoTorus* s = (const TGeoTorus*)shape; - geo.doc_solids.append(solid = xml_elt_t(geo.doc,_U(torus))); - solid.setAttr(_U(name),Unicode(name)); - solid.setAttr(_U(rtor), s->GetR()*CM_2_MM); - solid.setAttr(_U(rmin), s->GetRmin()*CM_2_MM); - solid.setAttr(_U(rmax), s->GetRmax()*CM_2_MM); - solid.setAttr(_U(startphi), s->GetPhi1()*DEGREE_2_RAD); - solid.setAttr(_U(deltaphi), s->GetDphi()*DEGREE_2_RAD); - solid.setAttr(_U(aunit),"rad"); - solid.setAttr(_U(lunit),"mm"); + else if (shape->IsA() == TGeoTorus::Class()) { + const TGeoTorus* s = (const TGeoTorus*) shape; + geo.doc_solids.append(solid = xml_elt_t(geo.doc, _U(torus))); + solid.setAttr(_U(name), Unicode(name)); + solid.setAttr(_U(rtor), s->GetR() * CM_2_MM); + solid.setAttr(_U(rmin), s->GetRmin() * CM_2_MM); + solid.setAttr(_U(rmax), s->GetRmax() * CM_2_MM); + solid.setAttr(_U(startphi), s->GetPhi1() * DEGREE_2_RAD); + solid.setAttr(_U(deltaphi), s->GetDphi() * DEGREE_2_RAD); + solid.setAttr(_U(aunit), "rad"); + solid.setAttr(_U(lunit), "mm"); } - else if ( shape->IsA() == TGeoArb8::Class() ) { - TGeoArb8* s = (TGeoArb8*)shape; + else if (shape->IsA() == TGeoArb8::Class()) { + TGeoArb8* s = (TGeoArb8*) shape; const double* vtx = s->GetVertices(); - geo.doc_solids.append(solid = xml_elt_t(geo.doc,_U(arb8))); - solid.setAttr(_U(name),Unicode(name)); - solid.setAttr(_U(v1x),vtx[0]*CM_2_MM); - solid.setAttr(_U(v1y),vtx[1]*CM_2_MM); - solid.setAttr(_U(v2x),vtx[2]*CM_2_MM); - solid.setAttr(_U(v2y),vtx[3]*CM_2_MM); - solid.setAttr(_U(v3x),vtx[4]*CM_2_MM); - solid.setAttr(_U(v3y),vtx[5]*CM_2_MM); - solid.setAttr(_U(v4x),vtx[6]*CM_2_MM); - solid.setAttr(_U(v4y),vtx[7]*CM_2_MM); - solid.setAttr(_U(v5x),vtx[8]*CM_2_MM); - solid.setAttr(_U(v5y),vtx[9]*CM_2_MM); - solid.setAttr(_U(v6x),vtx[10]*CM_2_MM); - solid.setAttr(_U(v6y),vtx[11]*CM_2_MM); - solid.setAttr(_U(v7x),vtx[12]*CM_2_MM); - solid.setAttr(_U(v7y),vtx[13]*CM_2_MM); - solid.setAttr(_U(v8x),vtx[14]*CM_2_MM); - solid.setAttr(_U(v8y),vtx[15]*CM_2_MM); - solid.setAttr(_U(dz), s->GetDz()*CM_2_MM); - solid.setAttr(_U(lunit),"mm"); + geo.doc_solids.append(solid = xml_elt_t(geo.doc, _U(arb8))); + solid.setAttr(_U(name), Unicode(name)); + solid.setAttr(_U(v1x), vtx[0] * CM_2_MM); + solid.setAttr(_U(v1y), vtx[1] * CM_2_MM); + solid.setAttr(_U(v2x), vtx[2] * CM_2_MM); + solid.setAttr(_U(v2y), vtx[3] * CM_2_MM); + solid.setAttr(_U(v3x), vtx[4] * CM_2_MM); + solid.setAttr(_U(v3y), vtx[5] * CM_2_MM); + solid.setAttr(_U(v4x), vtx[6] * CM_2_MM); + solid.setAttr(_U(v4y), vtx[7] * CM_2_MM); + solid.setAttr(_U(v5x), vtx[8] * CM_2_MM); + solid.setAttr(_U(v5y), vtx[9] * CM_2_MM); + solid.setAttr(_U(v6x), vtx[10] * CM_2_MM); + solid.setAttr(_U(v6y), vtx[11] * CM_2_MM); + solid.setAttr(_U(v7x), vtx[12] * CM_2_MM); + solid.setAttr(_U(v7y), vtx[13] * CM_2_MM); + solid.setAttr(_U(v8x), vtx[14] * CM_2_MM); + solid.setAttr(_U(v8y), vtx[15] * CM_2_MM); + solid.setAttr(_U(dz), s->GetDz() * CM_2_MM); + solid.setAttr(_U(lunit), "mm"); } - else if ( shape->IsA() == TGeoCompositeShape::Class() ) { + else if (shape->IsA() == TGeoCompositeShape::Class()) { char text[32]; - const TGeoCompositeShape* s = (const TGeoCompositeShape*)shape; + const TGeoCompositeShape* s = (const TGeoCompositeShape*) shape; const TGeoBoolNode* boolean = s->GetBoolNode(); TGeoBoolNode::EGeoBoolType oper = boolean->GetBooleanOperator(); TGeoMatrix* rm = boolean->GetRightMatrix(); TGeoMatrix* lm = boolean->GetLeftMatrix(); - TGeoShape* ls = boolean->GetLeftShape(); - TGeoShape* rs = boolean->GetRightShape(); - xml_h left = handleSolid(ls->GetName(),ls); - xml_h right = handleSolid(rs->GetName(),rs); + TGeoShape* ls = boolean->GetLeftShape(); + TGeoShape* rs = boolean->GetRightShape(); + xml_h left = handleSolid(ls->GetName(), ls); + xml_h right = handleSolid(rs->GetName(), rs); xml_h first(0), second(0); - if ( !left ) { - throw runtime_error("G4Converter: No left LCDD Solid present for composite shape:"+name); + if (!left) { + throw runtime_error("G4Converter: No left LCDD Solid present for composite shape:" + name); } - if ( !right ) { - throw runtime_error("G4Converter: No right LCDD Solid present for composite shape:"+name); + if (!right) { + throw runtime_error("G4Converter: No right LCDD Solid present for composite shape:" + name); } - if ( oper == TGeoBoolNode::kGeoSubtraction ) - solid = xml_elt_t(geo.doc,_U(subtraction)); + if ( oper == TGeoBoolNode::kGeoSubtraction ) + solid = xml_elt_t(geo.doc,_U(subtraction)); else if ( oper == TGeoBoolNode::kGeoUnion ) - solid = xml_elt_t(geo.doc,_U(union)); + solid = xml_elt_t(geo.doc,_U(union)); else if ( oper == TGeoBoolNode::kGeoIntersection ) - solid = xml_elt_t(geo.doc,_U(intersection)); + solid = xml_elt_t(geo.doc,_U(intersection)); xml_h obj; geo.doc_solids.append(solid); - solid.append(first=xml_elt_t(geo.doc,_U(first))); - solid.setAttr(_U(name),Unicode(name)); - first.setAttr(_U(ref),ls->GetName()); - const double *tr = lm->GetTranslation(); - double phi=0., theta=0., psi=0.; - + solid.append(first = xml_elt_t(geo.doc, _U(first))); + solid.setAttr(_U(name), Unicode(name)); + first.setAttr(_U(ref), ls->GetName()); + const double *tr = lm->GetTranslation(); + double phi = 0., theta = 0., psi = 0.; + if ((tr[0] != 0.0) || (tr[1] != 0.0) || (tr[2] != 0.0)) { - first.append(obj=xml_elt_t(geo.doc,_U(firstposition))); - obj.setAttr(_U(x),tr[0]*CM_2_MM); - obj.setAttr(_U(y),tr[1]*CM_2_MM); - obj.setAttr(_U(z),tr[2]*CM_2_MM); + first.append(obj = xml_elt_t(geo.doc, _U(firstposition))); + obj.setAttr(_U(x), tr[0] * CM_2_MM); + obj.setAttr(_U(y), tr[1] * CM_2_MM); + obj.setAttr(_U(z), tr[2] * CM_2_MM); } - if ( lm->IsRotation() ) { - TGeoMatrix& linv = lm->Inverse(); - XYZRotation rot = getXYZangles(linv.GetRotationMatrix()); - if ((rot.X() != 0.0) || (rot.Y() != 0.0) || (rot.Z() != 0.0)) { - first.append(obj=xml_elt_t(geo.doc,_U(firstrotation))); - obj.setAttr(_U(name),name); - obj.setAttr(_U(x),rot.X()); - obj.setAttr(_U(y),rot.Y()); - obj.setAttr(_U(z),rot.Z()); - obj.setAttr(_U(unit),"rad"); - } + if (lm->IsRotation()) { + TGeoMatrix& linv = lm->Inverse(); + XYZRotation rot = getXYZangles(linv.GetRotationMatrix()); + if ((rot.X() != 0.0) || (rot.Y() != 0.0) || (rot.Z() != 0.0)) { + first.append(obj = xml_elt_t(geo.doc, _U(firstrotation))); + obj.setAttr(_U(name), name); + obj.setAttr(_U(x), rot.X()); + obj.setAttr(_U(y), rot.Y()); + obj.setAttr(_U(z), rot.Z()); + obj.setAttr(_U(unit), "rad"); + } } - tr = rm->GetTranslation(); - solid.append(second=xml_elt_t(geo.doc,_U(second))); - second.setAttr(_U(ref),rs->GetName()); - ::snprintf(text,sizeof(text),"_%p_",rm); + tr = rm->GetTranslation(); + solid.append(second = xml_elt_t(geo.doc, _U(second))); + second.setAttr(_U(ref), rs->GetName()); + ::snprintf(text, sizeof(text), "_%p_", rm); string rnam = rs->GetName(); rnam += text; if ((tr[0] != 0.0) || (tr[1] != 0.0) || (tr[2] != 0.0)) { - xml_ref_t pos = handlePosition(rnam+"pos",rm); - solid.setRef(_U(positionref),pos.name()); + xml_ref_t pos = handlePosition(rnam + "pos", rm); + solid.setRef(_U(positionref), pos.name()); } - if ( rm->IsRotation() ) { - TGeoMatrix& rinv = rm->Inverse(); - XYZRotation rot = getXYZangles(rinv.GetRotationMatrix()); - if ((rot.X() != 0.0) || (rot.Y() != 0.0) || (rot.Z() != 0.0)) { - xml_ref_t rot = handleRotation(rnam+"rot",&rinv); - solid.setRef(_U(rotationref),rot.name()); - } + if (rm->IsRotation()) { + TGeoMatrix& rinv = rm->Inverse(); + XYZRotation rot = getXYZangles(rinv.GetRotationMatrix()); + if ((rot.X() != 0.0) || (rot.Y() != 0.0) || (rot.Z() != 0.0)) { + xml_ref_t rot = handleRotation(rnam + "rot", &rinv); + solid.setRef(_U(rotationref), rot.name()); + } } } - if ( !solid ) { - string err = "Failed to handle unknown solid shape:" + - name + " of type " + string(shape->IsA()->GetName()); + if (!solid) { + string err = "Failed to handle unknown solid shape:" + name + " of type " + string(shape->IsA()->GetName()); throw runtime_error(err); } return data().xmlSolids[shape] = solid; @@ -516,32 +518,32 @@ xml_h LCDDConverter::handleSolid(const string& name, const TGeoShape* shape) c } /// Convert the Position into the corresponding Xml object(s). -xml_h LCDDConverter::handlePosition(const std::string& name, const TGeoMatrix* trafo) const { +xml_h LCDDConverter::handlePosition(const std::string& name, const TGeoMatrix* trafo) const { GeometryInfo& geo = data(); xml_h pos = geo.xmlPositions[trafo]; - if ( !pos ) { + if (!pos) { const double* tr = trafo->GetTranslation(); - if ( tr[0] != 0.0 || tr[1] != 0.0 || tr[2] != 0.0 ) { - geo.checkPosition(name,trafo); - geo.doc_define.append(pos=xml_elt_t(geo.doc,_U(position))); - pos.setAttr(_U(name),name); - pos.setAttr(_U(x),tr[0]*CM_2_MM); - pos.setAttr(_U(y),tr[1]*CM_2_MM); - pos.setAttr(_U(z),tr[2]*CM_2_MM); - pos.setAttr(_U(unit),"mm"); + if (tr[0] != 0.0 || tr[1] != 0.0 || tr[2] != 0.0) { + geo.checkPosition(name, trafo); + geo.doc_define.append(pos = xml_elt_t(geo.doc, _U(position))); + pos.setAttr(_U(name), name); + pos.setAttr(_U(x), tr[0] * CM_2_MM); + pos.setAttr(_U(y), tr[1] * CM_2_MM); + pos.setAttr(_U(z), tr[2] * CM_2_MM); + pos.setAttr(_U(unit), "mm"); } - else if ( geo.identity_pos ) { + else if (geo.identity_pos) { pos = geo.identity_pos; } else { - geo.doc_define.append(geo.identity_pos=xml_elt_t(geo.doc,_U(position))); - geo.identity_pos.setAttr(_U(name),"identity_pos"); - geo.identity_pos.setAttr(_U(x),0); - geo.identity_pos.setAttr(_U(y),0); - geo.identity_pos.setAttr(_U(z),0); - geo.identity_pos.setAttr(_U(unit),"mm"); + geo.doc_define.append(geo.identity_pos = xml_elt_t(geo.doc, _U(position))); + geo.identity_pos.setAttr(_U(name), "identity_pos"); + geo.identity_pos.setAttr(_U(x), 0); + geo.identity_pos.setAttr(_U(y), 0); + geo.identity_pos.setAttr(_U(z), 0); + geo.identity_pos.setAttr(_U(unit), "mm"); pos = geo.identity_pos; - geo.checkPosition("identity_pos",0); + geo.checkPosition("identity_pos", 0); } geo.xmlPositions[trafo] = pos; } @@ -549,32 +551,32 @@ xml_h LCDDConverter::handlePosition(const std::string& name, const TGeoMatrix* t } /// Convert the Rotation into the corresponding Xml object(s). -xml_h LCDDConverter::handleRotation(const std::string& name, const TGeoMatrix* trafo) const { +xml_h LCDDConverter::handleRotation(const std::string& name, const TGeoMatrix* trafo) const { GeometryInfo& geo = data(); xml_h rot = geo.xmlRotations[trafo]; - if ( !rot ) { + if (!rot) { XYZRotation r = getXYZangles(trafo->GetRotationMatrix()); - if ( !(r.X() == 0.0 && r.Y() == 0.0 && r.Z() == 0.0) ) { - geo.checkRotation(name,trafo); - geo.doc_define.append(rot=xml_elt_t(geo.doc,_U(rotation))); - rot.setAttr(_U(name),name); - rot.setAttr(_U(x),r.X()); - rot.setAttr(_U(y),r.Y()); - rot.setAttr(_U(z),r.Z()); - rot.setAttr(_U(unit),"rad"); + if (!(r.X() == 0.0 && r.Y() == 0.0 && r.Z() == 0.0)) { + geo.checkRotation(name, trafo); + geo.doc_define.append(rot = xml_elt_t(geo.doc, _U(rotation))); + rot.setAttr(_U(name), name); + rot.setAttr(_U(x), r.X()); + rot.setAttr(_U(y), r.Y()); + rot.setAttr(_U(z), r.Z()); + rot.setAttr(_U(unit), "rad"); } - else if ( geo.identity_rot ) { + else if (geo.identity_rot) { rot = geo.identity_rot; } else { - geo.doc_define.append(geo.identity_rot=xml_elt_t(geo.doc,_U(rotation))); - geo.identity_rot.setAttr(_U(name),"identity_rot"); - geo.identity_rot.setAttr(_U(x),0); - geo.identity_rot.setAttr(_U(y),0); - geo.identity_rot.setAttr(_U(z),0); - geo.identity_rot.setAttr(_U(unit),"rad"); + geo.doc_define.append(geo.identity_rot = xml_elt_t(geo.doc, _U(rotation))); + geo.identity_rot.setAttr(_U(name), "identity_rot"); + geo.identity_rot.setAttr(_U(x), 0); + geo.identity_rot.setAttr(_U(y), 0); + geo.identity_rot.setAttr(_U(z), 0); + geo.identity_rot.setAttr(_U(unit), "rad"); rot = geo.identity_rot; - geo.checkRotation("identity_rot",0); + geo.checkRotation("identity_rot", 0); } geo.xmlRotations[trafo] = rot; } @@ -582,66 +584,66 @@ xml_h LCDDConverter::handleRotation(const std::string& name, const TGeoMatrix* t } /// Dump logical volume in GDML format to output stream -xml_h LCDDConverter::handleVolume(const string& name, const TGeoVolume* volume) const { +xml_h LCDDConverter::handleVolume(const string& name, const TGeoVolume* volume) const { GeometryInfo& geo = data(); xml_h vol = geo.xmlVolumes[volume]; - if ( !vol ) { - const TGeoVolume* v = volume; - Volume _v = Ref_t(v); - string n = v->GetName(); - TGeoMedium* m = v->GetMedium(); - TGeoShape* s = v->GetShape(); - xml_ref_t sol = handleSolid(s->GetName(),s); - - geo.checkVolume(name,volume); - if ( v->IsAssembly() ) { - vol=xml_elt_t(geo.doc,_U(assembly)); - vol.setAttr(_U(name),n); + if (!vol) { + const TGeoVolume* v = volume; + Volume _v = Ref_t(v); + string n = v->GetName(); + TGeoMedium* m = v->GetMedium(); + TGeoShape* s = v->GetShape(); + xml_ref_t sol = handleSolid(s->GetName(), s); + + geo.checkVolume(name, volume); + if (v->IsAssembly()) { + vol = xml_elt_t(geo.doc, _U(assembly)); + vol.setAttr(_U(name), n); } - else { - if ( !sol ) - throw runtime_error("G4Converter: No LCDD Solid present for volume:"+n); - else if ( !m ) - throw runtime_error("G4Converter: No LCDD material present for volume:"+n); - - vol=xml_elt_t(geo.doc,_U(volume)); - vol.setAttr(_U(name),n); - if ( m ) { - string mat_name = m->GetName(); - xml_ref_t med = handleMaterial(mat_name,m); - vol.setRef(_U(materialref),med.name()); + else { + if (!sol) + throw runtime_error("G4Converter: No LCDD Solid present for volume:" + n); + else if (!m) + throw runtime_error("G4Converter: No LCDD material present for volume:" + n); + + vol = xml_elt_t(geo.doc, _U(volume)); + vol.setAttr(_U(name), n); + if (m) { + string mat_name = m->GetName(); + xml_ref_t med = handleMaterial(mat_name, m); + vol.setRef(_U(materialref), med.name()); } - vol.setRef(_U(solidref),sol.name()); + vol.setRef(_U(solidref), sol.name()); } geo.doc_structure.append(vol); geo.xmlVolumes[v] = vol; - const TObjArray* dau = ((TGeoVolume*)v)->GetNodes(); - if ( dau && dau->GetEntries() > 0 ) { - for(Int_t i=0, n=dau->GetEntries(); i<n; ++i) { - TGeoNode* node = (TGeoNode*)dau->At(i); - handlePlacement(node->GetName(),node); + const TObjArray* dau = ((TGeoVolume*) v)->GetNodes(); + if (dau && dau->GetEntries() > 0) { + for (Int_t i = 0, n = dau->GetEntries(); i < n; ++i) { + TGeoNode* node = (TGeoNode*) dau->At(i); + handlePlacement(node->GetName(), node); } } - if ( geo.doc_header && dynamic_cast<const Volume::Object*>(volume) ) { - Region reg = _v.region(); - LimitSet lim = _v.limitSet(); - VisAttr vis = _v.visAttributes(); + if (geo.doc_header && dynamic_cast<const Volume::Object*>(volume)) { + Region reg = _v.region(); + LimitSet lim = _v.limitSet(); + VisAttr vis = _v.visAttributes(); SensitiveDetector det = _v.sensitiveDetector(); - if ( det.isValid() ) { - xml_ref_t data = handleSensitive(det.name(),det.ptr()); - vol.setRef(_U(sdref),data.name()); + if (det.isValid()) { + xml_ref_t data = handleSensitive(det.name(), det.ptr()); + vol.setRef(_U(sdref), data.name()); } - if ( reg.isValid() ) { - xml_ref_t data = handleRegion(reg.name(),reg.ptr()); - vol.setRef(_U(regionref),data.name()); + if (reg.isValid()) { + xml_ref_t data = handleRegion(reg.name(), reg.ptr()); + vol.setRef(_U(regionref), data.name()); } - if ( lim.isValid() ) { - xml_ref_t data = handleLimitSet(lim.name(),lim.ptr()); - vol.setRef(_U(limitsetref),data.name()); + if (lim.isValid()) { + xml_ref_t data = handleLimitSet(lim.name(), lim.ptr()); + vol.setRef(_U(limitsetref), data.name()); } - if ( vis.isValid() ) { - xml_ref_t data = handleVis(vis.name(),vis.ptr()); - vol.setRef(_U(visref),data.name()); + if (vis.isValid()) { + xml_ref_t data = handleVis(vis.name(), vis.ptr()); + vol.setRef(_U(visref), data.name()); } } } @@ -649,20 +651,20 @@ xml_h LCDDConverter::handleVolume(const string& name, const TGeoVolume* volume) } /// Dump logical volume in GDML format to output stream -xml_h LCDDConverter::handleVolumeVis(const string& name, const TGeoVolume* volume) const { +xml_h LCDDConverter::handleVolumeVis(const string& name, const TGeoVolume* volume) const { GeometryInfo& geo = data(); xml_h vol = geo.xmlVolumes[volume]; - if ( !vol ) { - const TGeoVolume* v = volume; - Volume _v = Ref_t(v); - if ( dynamic_cast<const Volume::Object*>(volume) ) { + if (!vol) { + const TGeoVolume* v = volume; + Volume _v = Ref_t(v); + if (dynamic_cast<const Volume::Object*>(volume)) { VisAttr vis = _v.visAttributes(); - if ( vis.isValid() ) { - geo.doc_structure.append(vol=xml_elt_t(geo.doc,_U(volume))); - vol.setAttr(_U(name),v->GetName()); - xml_ref_t data = handleVis(vis.name(),vis.ptr()); - vol.setRef(_U(visref),data.name()); - geo.xmlVolumes[v] = vol; + if (vis.isValid()) { + geo.doc_structure.append(vol = xml_elt_t(geo.doc, _U(volume))); + vol.setAttr(_U(name), v->GetName()); + xml_ref_t data = handleVis(vis.name(), vis.ptr()); + vol.setRef(_U(visref), data.name()); + geo.xmlVolumes[v] = vol; } } } @@ -670,16 +672,19 @@ xml_h LCDDConverter::handleVolumeVis(const string& name, const TGeoVolume* volum } /// Dump logical volume in GDML format to output stream -void LCDDConverter::collectVolume(const string& name, const TGeoVolume* volume) const { +void LCDDConverter::collectVolume(const string& name, const TGeoVolume* volume) const { Volume v = Ref_t(volume); - if ( dynamic_cast<const Volume::Object*>(volume) ) { - GeometryInfo& geo = data(); - Region reg = v.region(); - LimitSet lim = v.limitSet(); + if (dynamic_cast<const Volume::Object*>(volume)) { + GeometryInfo& geo = data(); + Region reg = v.region(); + LimitSet lim = v.limitSet(); SensitiveDetector det = v.sensitiveDetector(); - if ( lim.isValid() ) geo.limits.insert(lim.ptr()); - if ( reg.isValid() ) geo.regions.insert(reg.ptr()); - if ( det.isValid() ) geo.sensitives.insert(det.ptr()); + if (lim.isValid()) + geo.limits.insert(lim.ptr()); + if (reg.isValid()) + geo.regions.insert(reg.ptr()); + if (det.isValid()) + geo.sensitives.insert(det.ptr()); } else { cout << "LCDDConverter::collectVolume: Skip volume:" << volume->GetName() << endl; @@ -687,18 +692,18 @@ void LCDDConverter::collectVolume(const string& name, const TGeoVolume* volume) } void LCDDConverter::checkVolumes(const string& name, const TGeoVolume* volume) const { - NameSet::const_iterator i=m_checkNames.find(name); - if ( i != m_checkNames.end() ) { + NameSet::const_iterator i = m_checkNames.find(name); + if (i != m_checkNames.end()) { Volume v = Ref_t(volume); cout << "checkVolumes: Volume " << name << " "; - if ( dynamic_cast<const Volume::Object*>(volume) ) { + if (dynamic_cast<const Volume::Object*>(volume)) { SensitiveDetector s = v.sensitiveDetector(); VisAttr vis = v.visAttributes(); - if ( s.isValid() ) { - cout << "of " << s.name() << " "; + if (s.isValid()) { + cout << "of " << s.name() << " "; } - else if ( vis.isValid() ) { - cout << "with VisAttrs " << vis.name() << " "; + else if (vis.isValid()) { + cout << "with VisAttrs " << vis.name() << " "; } } cout << "has duplicate entries." << endl; @@ -710,81 +715,81 @@ void LCDDConverter::checkVolumes(const string& name, const TGeoVolume* volume) c /// Dump volume placement in GDML format to output stream xml_h LCDDConverter::handlePlacement(const string& name, const TGeoNode* node) const { GeometryInfo& geo = data(); - xml_h place = geo.xmlPlacements[node]; - if ( !place ) { - TGeoMatrix* m = node->GetMatrix(); - TGeoVolume* v = node->GetVolume(); - xml_ref_t vol = xml_h(geo.xmlVolumes[v]); - xml_h mot = geo.xmlVolumes[node->GetMotherVolume()]; - - place = xml_elt_t(geo.doc,_U(physvol)); - if ( mot ) { // Beware of top level volume! + xml_h place = geo.xmlPlacements[node]; + if (!place) { + TGeoMatrix* m = node->GetMatrix(); + TGeoVolume* v = node->GetVolume(); + xml_ref_t vol = xml_h(geo.xmlVolumes[v]); + xml_h mot = geo.xmlVolumes[node->GetMotherVolume()]; + + place = xml_elt_t(geo.doc, _U(physvol)); + if (mot) { // Beware of top level volume! mot.append(place); } - place.setRef(_U(volumeref),vol.name()); - if ( m ) { + place.setRef(_U(volumeref), vol.name()); + if (m) { char text[32]; - ::snprintf(text,sizeof(text),"_%p_pos",node); - xml_ref_t pos = handlePosition(name+text,m); - ::snprintf(text,sizeof(text),"_%p_rot",node); - xml_ref_t rot = handleRotation(name+text,m); - place.setRef(_U(positionref),pos.name()); - place.setRef(_U(rotationref),rot.name()); + ::snprintf(text, sizeof(text), "_%p_pos", node); + xml_ref_t pos = handlePosition(name + text, m); + ::snprintf(text, sizeof(text), "_%p_rot", node); + xml_ref_t rot = handleRotation(name + text, m); + place.setRef(_U(positionref), pos.name()); + place.setRef(_U(rotationref), rot.name()); } - if ( geo.doc_root.tag() != "gdml" ) { - if ( dynamic_cast<const PlacedVolume::Object*>(node) ) { - PlacedVolume p = Ref_t(node); - const PlacedVolume::VolIDs& ids = p.volIDs(); - for(PlacedVolume::VolIDs::const_iterator i=ids.begin(); i!=ids.end(); ++i) { - xml_h pvid = xml_elt_t(geo.doc,_U(physvolid)); - pvid.setAttr(_U(field_name),(*i).first); - pvid.setAttr(_U(value),(*i).second); - place.append(pvid); - } + if (geo.doc_root.tag() != "gdml") { + if (dynamic_cast<const PlacedVolume::Object*>(node)) { + PlacedVolume p = Ref_t(node); + const PlacedVolume::VolIDs& ids = p.volIDs(); + for (PlacedVolume::VolIDs::const_iterator i = ids.begin(); i != ids.end(); ++i) { + xml_h pvid = xml_elt_t(geo.doc, _U(physvolid)); + pvid.setAttr(_U(field_name), (*i).first); + pvid.setAttr(_U(value), (*i).second); + place.append(pvid); + } } } geo.xmlPlacements[node] = place; } else { - cout << "Attempt to DOUBLE-place physical volume:" << name << " No:" << node->GetNumber() << endl; + cout << "Attempt to DOUBLE-place physical volume:" << name << " No:" << node->GetNumber() << endl; } return place; } /// Convert the geometry type region into the corresponding LCDD object(s). -xml_h LCDDConverter::handleRegion(const std::string& name, const TNamed* region) const { - GeometryInfo& geo = data(); +xml_h LCDDConverter::handleRegion(const std::string& name, const TNamed* region) const { + GeometryInfo& geo = data(); xml_h reg = geo.xmlRegions[region]; - if ( !reg ) { + if (!reg) { Region r = Ref_t(region); - geo.doc_regions.append(reg=xml_elt_t(geo.doc,_U(region))); - reg.setAttr(_U(name), r.name()); - reg.setAttr(_U(cut), r.cut()); + geo.doc_regions.append(reg = xml_elt_t(geo.doc, _U(region))); + reg.setAttr(_U(name), r.name()); + reg.setAttr(_U(cut), r.cut()); reg.setAttr(_U(eunit), r.energyUnit()); reg.setAttr(_U(lunit), r.lengthUnit()); - reg.setAttr(_U(store_secondaries),r.storeSecondaries()); + reg.setAttr(_U(store_secondaries), r.storeSecondaries()); geo.xmlRegions[region] = reg; } return reg; } /// Convert the geometry type LimitSet into the corresponding LCDD object(s) -xml_h LCDDConverter::handleLimitSet(const std::string& name, const TNamed* limitset) const { - GeometryInfo& geo = data(); +xml_h LCDDConverter::handleLimitSet(const std::string& name, const TNamed* limitset) const { + GeometryInfo& geo = data(); xml_h xml = geo.xmlLimits[limitset]; - if ( !xml ) { + if (!xml) { LimitSet lim = Ref_t(limitset); - geo.doc_limits.append(xml=xml_elt_t(geo.doc,_U(limitset))); - xml.setAttr(_U(name),lim.name()); + geo.doc_limits.append(xml = xml_elt_t(geo.doc, _U(limitset))); + xml.setAttr(_U(name), lim.name()); const set<Limit>& obj = lim.limits(); - for(set<Limit>::const_iterator i=obj.begin(); i!=obj.end(); ++i) { - xml_h x = xml_elt_t(geo.doc,_U(limit)); + for (set<Limit>::const_iterator i = obj.begin(); i != obj.end(); ++i) { + xml_h x = xml_elt_t(geo.doc, _U(limit)); const Limit& l = *i; xml.append(x); - x.setAttr(_U(name),l.name); - x.setAttr(_U(unit),l.unit); - x.setAttr(_U(value),l.value); - x.setAttr(_U(particles),l.particles); + x.setAttr(_U(name), l.name); + x.setAttr(_U(unit), l.unit); + x.setAttr(_U(value), l.value); + x.setAttr(_U(particles), l.particles); } geo.xmlLimits[limitset] = xml; } @@ -792,50 +797,50 @@ xml_h LCDDConverter::handleLimitSet(const std::string& name, const TNamed* limit } /// Convert the segmentation of a SensitiveDetector into the corresponding LCDD object -xml_h LCDDConverter::handleSegmentation(Segmentation seg) const { +xml_h LCDDConverter::handleSegmentation(Segmentation seg) const { xml_h xml; - if ( seg.isValid() ) { + if (seg.isValid()) { typedef SegmentationParams::Parameters _P; string typ = seg.type(); SegmentationParams par(seg); _P p = par.parameters(); - xml = xml_elt_t(data().doc,Unicode(typ)); - for(_P::const_iterator i=p.begin(); i != p.end(); ++i) { - const _P::value_type& v=*i; - if ( v.first == "lunit" ) { - string val = v.second == _toDouble("mm") ? "mm" : - v.second == _toDouble("cm") ? "cm" : - v.second == _toDouble("m") ? "m" : - v.second == _toDouble("micron") ? "micron" : - v.second == _toDouble("nanometer") ? "namometer" : "??"; - xml.setAttr(Unicode(v.first),Unicode(val)); - continue; + xml = xml_elt_t(data().doc, Unicode(typ)); + for (_P::const_iterator i = p.begin(); i != p.end(); ++i) { + const _P::value_type& v = *i; + if (v.first == "lunit") { + string val = v.second == _toDouble("mm") ? "mm" : v.second == _toDouble("cm") ? "cm" : + v.second == _toDouble("m") ? "m" : v.second == _toDouble("micron") ? "micron" : + v.second == _toDouble("nanometer") ? "namometer" : "??"; + xml.setAttr(Unicode(v.first), Unicode(val)); + continue; } - xml.setAttr(Unicode(v.first),v.second); + xml.setAttr(Unicode(v.first), v.second); } } return xml; } /// Convert the geometry type SensitiveDetector into the corresponding LCDD object(s). -xml_h LCDDConverter::handleSensitive(const string& name, const TNamed* sens_det) const { +xml_h LCDDConverter::handleSensitive(const string& name, const TNamed* sens_det) const { GeometryInfo& geo = data(); xml_h sensdet = geo.xmlSensDets[sens_det]; - if ( !sensdet ) { + if (!sensdet) { SensitiveDetector sd = Ref_t(sens_det); - geo.doc_detectors.append(sensdet = xml_elt_t(geo.doc,Unicode(sd.type()))); - sensdet.setAttr(_U(name),sd.name()); - sensdet.setAttr(_U(ecut),sd.energyCutoff()); - sensdet.setAttr(_U(eunit),"MeV"); - sensdet.setAttr(_U(verbose),int(sd.verbose() ? 1 : 0)); - sensdet.setAttr(_U(hits_collection),sd.hitsCollection()); - if ( sd.combineHits() ) sensdet.setAttr(_U(combine_hits),sd.combineHits()); + geo.doc_detectors.append(sensdet = xml_elt_t(geo.doc, Unicode(sd.type()))); + sensdet.setAttr(_U(name), sd.name()); + sensdet.setAttr(_U(ecut), sd.energyCutoff()); + sensdet.setAttr(_U(eunit), "MeV"); + sensdet.setAttr(_U(verbose), int(sd.verbose() ? 1 : 0)); + sensdet.setAttr(_U(hits_collection), sd.hitsCollection()); + if (sd.combineHits()) + sensdet.setAttr(_U(combine_hits), sd.combineHits()); Readout ro = sd.readout(); - if ( ro.isValid() ) { - xml_ref_t ref = handleIdSpec(ro.idSpec().name(),ro.idSpec().ptr()); - sensdet.setRef(_U(idspecref),ref.name()); + if (ro.isValid()) { + xml_ref_t ref = handleIdSpec(ro.idSpec().name(), ro.idSpec().ptr()); + sensdet.setRef(_U(idspecref), ref.name()); xml_h seg = handleSegmentation(ro.segmentation()); - if ( seg ) sensdet.append(seg); + if (seg) + sensdet.append(seg); } geo.xmlSensDets[sens_det] = sensdet; } @@ -846,14 +851,14 @@ xml_h LCDDConverter::handleSensitive(const string& name, const TNamed* sens_det) xml_h LCDDConverter::handleIdSpec(const std::string& name, const TNamed* id_spec) const { GeometryInfo& geo = data(); xml_h id = geo.xmlIdSpecs[id_spec]; - if ( !id ) { - int length=0, start=0; + if (!id) { + int length = 0, start = 0; IDDescriptor desc = Ref_t(id_spec); - geo.doc_idDict.append(id=xml_elt_t(geo.doc,_U(idspec))); - id.setAttr(_U(name),name); + geo.doc_idDict.append(id = xml_elt_t(geo.doc, _U(idspec))); + id.setAttr(_U(name), name); const IDDescriptor::FieldMap& m = desc.fields(); - for(IDDescriptor::FieldMap::const_iterator i=m.begin(); i!=m.end(); ++i) { - xml_h idfield = xml_elt_t(geo.doc,_U(idfield)); + for (IDDescriptor::FieldMap::const_iterator i = m.begin(); i != m.end(); ++i) { + xml_h idfield = xml_elt_t(geo.doc, _U(idfield)); #if 0 const IDDescriptor::Field& f = (*i).second; start = f.first; @@ -865,47 +870,47 @@ xml_h LCDDConverter::handleIdSpec(const std::string& name, const TNamed* id_spec #else IDDescriptor::Field f = (*i).second; idfield.setAttr(_U(signed),f->isSigned() ? true : false); - idfield.setAttr(_U(label),f->name()); - idfield.setAttr(_U(length),(int)f->width()); - idfield.setAttr(_U(start),(int)f->offset()); + idfield.setAttr(_U(label), f->name()); + idfield.setAttr(_U(length), (int) f->width()); + idfield.setAttr(_U(start), (int) f->offset()); #endif id.append(idfield); } - id.setAttr(_U(length),length+start); + id.setAttr(_U(length), length + start); geo.xmlIdSpecs[id_spec] = id; } return id; } /// Convert the geometry visualisation attributes to the corresponding LCDD object(s). -xml_h LCDDConverter::handleVis(const string& name, const TNamed* v) const { +xml_h LCDDConverter::handleVis(const string& name, const TNamed* v) const { GeometryInfo& geo = data(); xml_h vis = geo.xmlVis[v]; - if ( !vis ) { - float r=0, g=0, b=0; - VisAttr attr = Ref_t(v); - int style = attr.lineStyle(); - int draw = attr.drawingStyle(); - - geo.doc_display.append(vis=xml_elt_t(geo.doc,_U(vis))); - vis.setAttr(_U(name),attr.name()); - vis.setAttr(_U(visible),attr.visible()); - vis.setAttr(_U(show_daughters),attr.showDaughters()); - if ( style == VisAttr::SOLID ) - vis.setAttr(_U(line_style),"unbroken"); - else if ( style == VisAttr::DASHED ) - vis.setAttr(_U(line_style),"broken"); - if ( draw == VisAttr::SOLID ) - vis.setAttr(_U(drawing_style),"solid"); - else if ( draw == VisAttr::WIREFRAME ) - vis.setAttr(_U(drawing_style),"wireframe"); - - xml_h col = xml_elt_t(geo.doc,_U(color)); - attr.rgb(r,g,b); - col.setAttr(_U(alpha),attr.alpha()); - col.setAttr(_U(R),r); - col.setAttr(_U(G),g); - col.setAttr(_U(B),b); + if (!vis) { + float r = 0, g = 0, b = 0; + VisAttr attr = Ref_t(v); + int style = attr.lineStyle(); + int draw = attr.drawingStyle(); + + geo.doc_display.append(vis = xml_elt_t(geo.doc, _U(vis))); + vis.setAttr(_U(name), attr.name()); + vis.setAttr(_U(visible), attr.visible()); + vis.setAttr(_U(show_daughters), attr.showDaughters()); + if (style == VisAttr::SOLID) + vis.setAttr(_U(line_style), "unbroken"); + else if (style == VisAttr::DASHED) + vis.setAttr(_U(line_style), "broken"); + if (draw == VisAttr::SOLID) + vis.setAttr(_U(drawing_style), "solid"); + else if (draw == VisAttr::WIREFRAME) + vis.setAttr(_U(drawing_style), "wireframe"); + + xml_h col = xml_elt_t(geo.doc, _U(color)); + attr.rgb(r, g, b); + col.setAttr(_U(alpha), attr.alpha()); + col.setAttr(_U(R), r); + col.setAttr(_U(G), g); + col.setAttr(_U(B), b); vis.append(col); geo.xmlVis[v] = vis; } @@ -913,22 +918,23 @@ xml_h LCDDConverter::handleVis(const string& name, const TNamed* v) const { } /// Convert the electric or magnetic fields into the corresponding Xml object(s). -xml_h LCDDConverter::handleField(const std::string& name, const TNamed* f) const { +xml_h LCDDConverter::handleField(const std::string& name, const TNamed* f) const { GeometryInfo& geo = data(); xml_h field = geo.xmlFields[f]; - if ( !field ) { - Ref_t fld(f); + if (!field) { + Ref_t fld(f); string type = f->GetTitle(); - field=xml_elt_t(geo.doc,Unicode(type)); - field.setAttr(_U(name),f->GetName()); - fld = PluginService::Create<TNamed*>(type+"_Convert2LCDD",&m_lcdd,&field,&fld); - cout << "++ " << (fld.isValid() ? "Converted" : "FAILED to convert ") - << " electromagnetic field:" << f->GetName() << " of type " << type << endl; - if ( !fld.isValid() ) { + field = xml_elt_t(geo.doc, Unicode(type)); + field.setAttr(_U(name), f->GetName()); + fld = PluginService::Create<TNamed*>(type + "_Convert2LCDD", &m_lcdd, &field, &fld); + cout << "++ " << (fld.isValid() ? "Converted" : "FAILED to convert ") << " electromagnetic field:" << f->GetName() + << " of type " << type << endl; + if (!fld.isValid()) { PluginDebug dbg; - PluginService::Create<TNamed*>(type+"_Convert2LCDD",&m_lcdd,&field,&fld); - throw runtime_error("Failed to locate plugin to convert electromagnetic field:"+ - string(f->GetName())+" of type "+type+". "+dbg.missingFactory(type)); + PluginService::Create<TNamed*>(type + "_Convert2LCDD", &m_lcdd, &field, &fld); + throw runtime_error( + "Failed to locate plugin to convert electromagnetic field:" + string(f->GetName()) + " of type " + type + ". " + + dbg.missingFactory(type)); } geo.doc_fields.append(field); } @@ -936,176 +942,179 @@ xml_h LCDDConverter::handleField(const std::string& name, const TNamed* f) con } /// Handle the geant 4 specific properties -void LCDDConverter::handleProperties(LCDD::Properties& prp) const { - map<string,string> processors; +void LCDDConverter::handleProperties(LCDD::Properties& prp) const { + map<string, string> processors; static int s_idd = 9999999; string id; - for(LCDD::Properties::const_iterator i=prp.begin(); i!=prp.end(); ++i) { + for (LCDD::Properties::const_iterator i = prp.begin(); i != prp.end(); ++i) { const string& nam = (*i).first; const LCDD::PropertyValues& vals = (*i).second; - if ( nam.substr(0,6) == "geant4" ) { + if (nam.substr(0, 6) == "geant4") { LCDD::PropertyValues::const_iterator id_it = vals.find("id"); - if ( id_it != vals.end() ) { - id= (*id_it).second; + if (id_it != vals.end()) { + id = (*id_it).second; } else { - char text[32]; - ::snprintf(text,sizeof(text),"%d",++s_idd); - id = text; + char text[32]; + ::snprintf(text, sizeof(text), "%d", ++s_idd); + id = text; } - processors.insert(make_pair(id,nam)); + processors.insert(make_pair(id, nam)); } } - for(map<string,string>::const_iterator i=processors.begin(); i!=processors.end(); ++i) { + for (map<string, string>::const_iterator i = processors.begin(); i != processors.end(); ++i) { const LCDDConverter* ptr = this; string nam = (*i).second; const LCDD::PropertyValues& vals = prp[nam]; string type = vals.find("type")->second; - string tag = type + "_Geant4_action"; - long result = PluginService::Create<long>(tag,&m_lcdd,ptr,&vals); - if ( 0 == result ) { + string tag = type + "_Geant4_action"; + long result = PluginService::Create<long>(tag, &m_lcdd, ptr, &vals); + if (0 == result) { PluginDebug dbg; - PluginService::Create<long>(tag,&m_lcdd,ptr,&vals); + PluginService::Create<long>(tag, &m_lcdd, ptr, &vals); throw runtime_error("Failed to locate plugin to interprete files of type" - " \""+tag+"\" - no factory:"+type+". "+dbg.missingFactory(tag)); + " \"" + tag + "\" - no factory:" + type + ". " + dbg.missingFactory(tag)); } - result = *(long*)result; - if ( result != 1 ) { - throw runtime_error("Failed to invoke the plugin "+tag+" of type "+type); + result = *(long*) result; + if (result != 1) { + throw runtime_error("Failed to invoke the plugin " + tag + " of type " + type); } cout << "+++++ Executed Successfully LCDD setup module *" << type << "* ." << endl; } } /// Add header information in LCDD format -void LCDDConverter::handleHeader() const { +void LCDDConverter::handleHeader() const { GeometryInfo& geo = data(); Header hdr = m_lcdd.header(); xml_h obj; - geo.doc_header.append(obj=xml_elt_t(geo.doc,_U(detector))); - obj.setAttr(_U(name),hdr.name()); - geo.doc_header.append(obj=xml_elt_t(geo.doc,_U(generator))); - obj.setAttr(_U(name),"LCDDConverter"); - obj.setAttr(_U(version),hdr.version()); - obj.setAttr(_U(file),hdr.url()); - obj.setAttr(_U(checksum),Unicode(m_lcdd.constantAsString("compact_checksum"))); - geo.doc_header.append(obj=xml_elt_t(geo.doc,_U(author))); - obj.setAttr(_U(name),hdr.author()); - geo.doc_header.append(obj=xml_elt_t(geo.doc,_U(comment))); + geo.doc_header.append(obj = xml_elt_t(geo.doc, _U(detector))); + obj.setAttr(_U(name), hdr.name()); + geo.doc_header.append(obj = xml_elt_t(geo.doc, _U(generator))); + obj.setAttr(_U(name), "LCDDConverter"); + obj.setAttr(_U(version), hdr.version()); + obj.setAttr(_U(file), hdr.url()); + obj.setAttr(_U(checksum), Unicode(m_lcdd.constantAsString("compact_checksum"))); + geo.doc_header.append(obj = xml_elt_t(geo.doc, _U(author))); + obj.setAttr(_U(name), hdr.author()); + geo.doc_header.append(obj = xml_elt_t(geo.doc, _U(comment))); obj.setText(hdr.comment()); } -template <typename O, typename C, typename F> void handle(const O* o, const C& c, F pmf) { - for(typename C::const_iterator i=c.begin(); i != c.end(); ++i) { +template <typename O, typename C, typename F> void handle(const O* o, const C& c, F pmf) { + for (typename C::const_iterator i = c.begin(); i != c.end(); ++i) { string n = (*i)->GetName(); - (o->*pmf)(n,*i); + (o->*pmf)(n, *i); } } -template <typename O, typename C, typename F> void handleMap(const O* o, const C& c, F pmf) { - for(typename C::const_iterator i=c.begin(); i != c.end(); ++i) +template <typename O, typename C, typename F> void handleMap(const O* o, const C& c, F pmf) { + for (typename C::const_iterator i = c.begin(); i != c.end(); ++i) (o->*pmf)((*i).first, (*i).second); } -template <typename O, typename C, typename F> void handleRMap(const O* o, const C& c, F pmf) { - for(typename C::const_reverse_iterator i=c.rbegin(); i != c.rend(); ++i) +template <typename O, typename C, typename F> void handleRMap(const O* o, const C& c, F pmf) { + for (typename C::const_reverse_iterator i = c.rbegin(); i != c.rend(); ++i) handle(o, (*i).second, pmf); } /// Create geometry conversion xml_doc_t LCDDConverter::createGDML(DetElement top) { LCDD& lcdd = m_lcdd; - if ( !top.isValid() ) { + if (!top.isValid()) { throw runtime_error("Attempt to call createGDML with an invalid geometry!"); } - GeometryInfo& geo = *(m_dataPtr=new GeometryInfo); + GeometryInfo& geo = *(m_dataPtr = new GeometryInfo); m_data->clear(); - collect(top,geo); + collect(top, geo); cout << "++ ==> Converting in memory detector description to GDML format..." << endl; const char* comment = "\n" - " +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n" - " ++++ Linear collider detector description GDML in C++ ++++\n" - " ++++ DD4hep Detector description generator. ++++\n" - " ++++ ++++\n" - " ++++ Parser:" XML_IMPLEMENTATION_TYPE " ++++\n" - " ++++ ++++\n" - " ++++ M.Frank CERN/LHCb ++++\n" - " +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n "; + " +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n" + " ++++ Linear collider detector description GDML in C++ ++++\n" + " ++++ DD4hep Detector description generator. ++++\n" + " ++++ ++++\n" + " ++++ Parser:" + XML_IMPLEMENTATION_TYPE + " ++++\n" + " ++++ ++++\n" + " ++++ M.Frank CERN/LHCb ++++\n" + " +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n "; XML::DocumentHandler docH; - geo.doc = docH.create("gdml",comment); + geo.doc = docH.create("gdml", comment); geo.doc_root = geo.doc.root(); - geo.doc_root.setAttr(Unicode("xmlns:xs"),"http://www.w3.org/2001/XMLSchema-instance"); + geo.doc_root.setAttr(Unicode("xmlns:xs"), "http://www.w3.org/2001/XMLSchema-instance"); geo.doc_root.setAttr(Unicode("xs:noNamespaceSchemaLocation"), - "http://service-spi.web.cern.ch/service-spi/app/releases/GDML/schema/gdml.xsd"); + "http://service-spi.web.cern.ch/service-spi/app/releases/GDML/schema/gdml.xsd"); // geo.doc = docH.create("gdml_simple_extension",comment); // geo.doc_root.setAttr(Unicode("xmlns:gdml_simple_extension"),"http://www.example.org"); // geo.doc_root.setAttr(Unicode("xs:noNamespaceSchemaLocation"), // "http://service-spi.web.cern.ch/service-spi/app/releases/GDML/schema/gdml.xsd"); - geo.doc_root.append(geo.doc_define = xml_elt_t(geo.doc,_U(define))); - geo.doc_root.append(geo.doc_materials = xml_elt_t(geo.doc,_U(materials))); - geo.doc_root.append(geo.doc_solids = xml_elt_t(geo.doc,_U(solids))); - geo.doc_root.append(geo.doc_structure = xml_elt_t(geo.doc,_U(structure))); - geo.doc_root.append(geo.doc_setup = xml_elt_t(geo.doc,_U(setup))); - geo.doc_setup.setRef(_U(world),lcdd.worldVolume().name()); - geo.doc_setup.setAttr(_U(name),Unicode("Default")); - geo.doc_setup.setAttr(_U(version),Unicode("1.0")); + geo.doc_root.append(geo.doc_define = xml_elt_t(geo.doc, _U(define))); + geo.doc_root.append(geo.doc_materials = xml_elt_t(geo.doc, _U(materials))); + geo.doc_root.append(geo.doc_solids = xml_elt_t(geo.doc, _U(solids))); + geo.doc_root.append(geo.doc_structure = xml_elt_t(geo.doc, _U(structure))); + geo.doc_root.append(geo.doc_setup = xml_elt_t(geo.doc, _U(setup))); + geo.doc_setup.setRef(_U(world), lcdd.worldVolume().name()); + geo.doc_setup.setAttr(_U(name), Unicode("Default")); + geo.doc_setup.setAttr(_U(version), Unicode("1.0")); // Ensure that all required materials are present in the LCDD material table #if 0 const LCDD::HandleMap& mat = lcdd.materials(); for(LCDD::HandleMap::const_iterator i=mat.begin(); i!=mat.end(); ++i) - geo.materials.insert(dynamic_cast<TGeoMedium*>((*i).second.ptr())); + geo.materials.insert(dynamic_cast<TGeoMedium*>((*i).second.ptr())); #endif // Start creating the objects for materials, solids and log volumes. handle(this, geo.materials, &LCDDConverter::handleMaterial); cout << "++ Handled " << geo.materials.size() << " materials." << endl; - handle(this, geo.volumes, &LCDDConverter::collectVolume); + handle(this, geo.volumes, &LCDDConverter::collectVolume); cout << "++ Handled " << geo.volumes.size() << " volumes." << endl; - handle(this, geo.solids, &LCDDConverter::handleSolid); + handle(this, geo.solids, &LCDDConverter::handleSolid); cout << "++ Handled " << geo.solids.size() << " solids." << endl; - handle(this, geo.volumes, &LCDDConverter::handleVolume); + handle(this, geo.volumes, &LCDDConverter::handleVolume); cout << "++ Handled " << geo.volumes.size() << " volumes." << endl; m_checkNames.clear(); - handle(this, geo.volumes, &LCDDConverter::checkVolumes); + handle(this, geo.volumes, &LCDDConverter::checkVolumes); return geo.doc; } - /// Create geometry conversion xml_doc_t LCDDConverter::createVis(DetElement top) { LCDD& lcdd = m_lcdd; - if ( !top.isValid() ) { + if (!top.isValid()) { throw runtime_error("Attempt to call createLCDD with an invalid geometry!"); } - GeometryInfo& geo = *(m_dataPtr=new GeometryInfo); + GeometryInfo& geo = *(m_dataPtr = new GeometryInfo); m_data->clear(); - collect(top,geo); + collect(top, geo); cout << "++ ==> Dump visualisation attributes from in memory detector description..." << endl; const char comment[] = "\n" - " +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n" - " ++++ Linear collider detector description LCDD in C++ ++++\n" - " ++++ DD4hep Detector description generator. ++++\n" - " ++++ ++++\n" - " ++++ Parser:" XML_IMPLEMENTATION_TYPE " ++++\n" - " ++++ ++++\n" - " ++++ M.Frank CERN/LHCb ++++\n" - " +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n "; + " +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n" + " ++++ Linear collider detector description LCDD in C++ ++++\n" + " ++++ DD4hep Detector description generator. ++++\n" + " ++++ ++++\n" + " ++++ Parser:" + XML_IMPLEMENTATION_TYPE + " ++++\n" + " ++++ ++++\n" + " ++++ M.Frank CERN/LHCb ++++\n" + " +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n "; XML::DocumentHandler docH; xml_elt_t elt(0); - geo.doc = docH.create("visualization",comment); + geo.doc = docH.create("visualization", comment); geo.doc_root = geo.doc.root(); - geo.doc_root.append(geo.doc_display = xml_elt_t(geo.doc,_U(display))); - geo.doc_root.append(geo.doc_structure = xml_elt_t(geo.doc,_U(structure))); + geo.doc_root.append(geo.doc_display = xml_elt_t(geo.doc, _U(display))); + geo.doc_root.append(geo.doc_structure = xml_elt_t(geo.doc, _U(structure))); - handle(this, geo.volumes, &LCDDConverter::collectVolume); - handle(this, geo.volumes, &LCDDConverter::handleVolumeVis); + handle(this, geo.volumes, &LCDDConverter::collectVolume); + handle(this, geo.volumes, &LCDDConverter::handleVolumeVis); cout << "++ Handled " << geo.volumes.size() << " volumes." << endl; return geo.doc; } @@ -1113,53 +1122,53 @@ xml_doc_t LCDDConverter::createVis(DetElement top) { /// Create geometry conversion xml_doc_t LCDDConverter::createLCDD(DetElement top) { LCDD& lcdd = m_lcdd; - if ( !top.isValid() ) { + if (!top.isValid()) { throw runtime_error("Attempt to call createLCDD with an invalid geometry!"); } - GeometryInfo& geo = *(m_dataPtr=new GeometryInfo); + GeometryInfo& geo = *(m_dataPtr = new GeometryInfo); m_data->clear(); - collect(top,geo); + collect(top, geo); const char comment[] = "\n" - " +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n" - " ++++ Linear collider detector description LCDD in C++ ++++\n" - " ++++ DD4hep Detector description generator. ++++\n" - " ++++ ++++\n" - " ++++ Parser:" XML_IMPLEMENTATION_TYPE " ++++\n" - " ++++ ++++\n" - " ++++ M.Frank CERN/LHCb ++++\n" - " +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n "; + " +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n" + " ++++ Linear collider detector description LCDD in C++ ++++\n" + " ++++ DD4hep Detector description generator. ++++\n" + " ++++ ++++\n" + " ++++ Parser:" + XML_IMPLEMENTATION_TYPE + " ++++\n" + " ++++ ++++\n" + " ++++ M.Frank CERN/LHCb ++++\n" + " +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n "; XML::DocumentHandler docH; xml_elt_t elt(0); - geo.doc = docH.create("lcdd",comment); + geo.doc = docH.create("lcdd", comment); geo.doc_root = geo.doc.root(); - geo.doc_root.setAttr(Unicode("xmlns:lcdd"), - "http://www.lcsim.org/schemas/lcdd/1.0"); - geo.doc_root.setAttr(Unicode("xmlns:xs"),"http://www.w3.org/2001/XMLSchema-instance"); - geo.doc_root.setAttr(Unicode("xs:noNamespaceSchemaLocation"), - "http://www.lcsim.org/schemas/lcdd/1.0/lcdd.xsd"); - - geo.doc_root.append(geo.doc_header = xml_elt_t(geo.doc,_U(header))); - geo.doc_root.append(geo.doc_idDict = xml_elt_t(geo.doc,_U(iddict))); - geo.doc_root.append(geo.doc_detectors = xml_elt_t(geo.doc,_U(sensitive_detectors))); - geo.doc_root.append(geo.doc_limits = xml_elt_t(geo.doc,_U(limits))); - geo.doc_root.append(geo.doc_regions = xml_elt_t(geo.doc,_U(regions))); - geo.doc_root.append(geo.doc_display = xml_elt_t(geo.doc,_U(display))); - geo.doc_root.append(geo.doc_gdml = xml_elt_t(geo.doc,_U(gdml))); - geo.doc_root.append(geo.doc_fields = xml_elt_t(geo.doc,_U(fields))); - - geo.doc_gdml.append(geo.doc_define = xml_elt_t(geo.doc,_U(define))); - geo.doc_gdml.append(geo.doc_materials = xml_elt_t(geo.doc,_U(materials))); - geo.doc_gdml.append(geo.doc_solids = xml_elt_t(geo.doc,_U(solids))); - geo.doc_gdml.append(geo.doc_structure = xml_elt_t(geo.doc,_U(structure))); - geo.doc_gdml.append(geo.doc_setup = xml_elt_t(geo.doc,_U(setup))); - geo.doc_setup.setRef(_U(world),lcdd.worldVolume().name()); - geo.doc_setup.setAttr(_U(name),Unicode("Default")); - geo.doc_setup.setAttr(_U(version),Unicode("1.0")); + geo.doc_root.setAttr(Unicode("xmlns:lcdd"), "http://www.lcsim.org/schemas/lcdd/1.0"); + geo.doc_root.setAttr(Unicode("xmlns:xs"), "http://www.w3.org/2001/XMLSchema-instance"); + geo.doc_root.setAttr(Unicode("xs:noNamespaceSchemaLocation"), "http://www.lcsim.org/schemas/lcdd/1.0/lcdd.xsd"); + + geo.doc_root.append(geo.doc_header = xml_elt_t(geo.doc, _U(header))); + geo.doc_root.append(geo.doc_idDict = xml_elt_t(geo.doc, _U(iddict))); + geo.doc_root.append(geo.doc_detectors = xml_elt_t(geo.doc, _U(sensitive_detectors))); + geo.doc_root.append(geo.doc_limits = xml_elt_t(geo.doc, _U(limits))); + geo.doc_root.append(geo.doc_regions = xml_elt_t(geo.doc, _U(regions))); + geo.doc_root.append(geo.doc_display = xml_elt_t(geo.doc, _U(display))); + geo.doc_root.append(geo.doc_gdml = xml_elt_t(geo.doc, _U(gdml))); + geo.doc_root.append(geo.doc_fields = xml_elt_t(geo.doc, _U(fields))); + + geo.doc_gdml.append(geo.doc_define = xml_elt_t(geo.doc, _U(define))); + geo.doc_gdml.append(geo.doc_materials = xml_elt_t(geo.doc, _U(materials))); + geo.doc_gdml.append(geo.doc_solids = xml_elt_t(geo.doc, _U(solids))); + geo.doc_gdml.append(geo.doc_structure = xml_elt_t(geo.doc, _U(structure))); + geo.doc_gdml.append(geo.doc_setup = xml_elt_t(geo.doc, _U(setup))); + geo.doc_setup.setRef(_U(world), lcdd.worldVolume().name()); + geo.doc_setup.setAttr(_U(name), Unicode("Default")); + geo.doc_setup.setAttr(_U(version), Unicode("1.0")); // Ensure that all required materials are present in the LCDD material table const LCDD::HandleMap& fld = lcdd.fields(); - for(LCDD::HandleMap::const_iterator i=fld.begin(); i!=fld.end(); ++i) + for (LCDD::HandleMap::const_iterator i = fld.begin(); i != fld.end(); ++i) geo.fields.insert((*i).second.ptr()); cout << "++ ==> Converting in memory detector description to LCDD format..." << endl; @@ -1168,32 +1177,32 @@ xml_doc_t LCDDConverter::createLCDD(DetElement top) { handle(this, geo.materials, &LCDDConverter::handleMaterial); cout << "++ Handled " << geo.materials.size() << " materials." << endl; - handle(this, geo.volumes, &LCDDConverter::collectVolume); + handle(this, geo.volumes, &LCDDConverter::collectVolume); cout << "++ Handled " << geo.volumes.size() << " volumes." << endl; - handle(this, geo.solids, &LCDDConverter::handleSolid); + handle(this, geo.solids, &LCDDConverter::handleSolid); cout << "++ Handled " << geo.solids.size() << " solids." << endl; - handle(this, geo.vis, &LCDDConverter::handleVis); + handle(this, geo.vis, &LCDDConverter::handleVis); cout << "++ Handled " << geo.solids.size() << " visualization attributes." << endl; handle(this, geo.sensitives, &LCDDConverter::handleSensitive); cout << "++ Handled " << geo.sensitives.size() << " sensitive detectors." << endl; - handle(this, geo.limits, &LCDDConverter::handleLimitSet); + handle(this, geo.limits, &LCDDConverter::handleLimitSet); cout << "++ Handled " << geo.limits.size() << " limit sets." << endl; - handle(this, geo.regions, &LCDDConverter::handleRegion); + handle(this, geo.regions, &LCDDConverter::handleRegion); cout << "++ Handled " << geo.regions.size() << " regions." << endl; - handle(this, geo.volumes, &LCDDConverter::handleVolume); + handle(this, geo.volumes, &LCDDConverter::handleVolume); cout << "++ Handled " << geo.volumes.size() << " volumes." << endl; - handle(this, geo.fields, &LCDDConverter::handleField); + handle(this, geo.fields, &LCDDConverter::handleField); cout << "++ Handled " << geo.fields.size() << " fields." << endl; m_checkNames.clear(); - handle(this, geo.volumes, &LCDDConverter::checkVolumes); + handle(this, geo.volumes, &LCDDConverter::checkVolumes); #if 0 //==================== Fields handleProperties(m_lcdd.properties()); @@ -1203,65 +1212,55 @@ xml_doc_t LCDDConverter::createLCDD(DetElement top) { /// Helper constructor LCDDConverter::GeometryInfo::GeometryInfo() - : doc(0), doc_root(0), doc_header(0), doc_idDict(0), doc_detectors(0), - doc_limits(0), doc_regions(0), doc_display(0), doc_gdml(0), - doc_fields(0), doc_define(0), doc_materials(0), - doc_solids(0), doc_structure(0),doc_setup(0) -{ + : doc(0), doc_root(0), doc_header(0), doc_idDict(0), doc_detectors(0), doc_limits(0), doc_regions(0), doc_display(0), doc_gdml( + 0), doc_fields(0), doc_define(0), doc_materials(0), doc_solids(0), doc_structure(0), doc_setup(0) { } -static long dump_output(xml_doc_t doc, int argc, char** argv) { +static long dump_output(xml_doc_t doc, int argc, char** argv) { XML::DocumentHandler docH; - return docH.output(doc, argc>0 ? argv[0] : ""); + return docH.output(doc, argc > 0 ? argv[0] : ""); } -static long create_gdml(LCDD& lcdd, int argc, char** argv) { +static long create_gdml(LCDD& lcdd, int argc, char** argv) { LCDDConverter wr(lcdd); - return dump_output(wr.createGDML(lcdd.world()),argc,argv); + return dump_output(wr.createGDML(lcdd.world()), argc, argv); } -static long create_lcdd(LCDD& lcdd, int argc, char** argv) { +static long create_lcdd(LCDD& lcdd, int argc, char** argv) { LCDDConverter wr(lcdd); - return dump_output(wr.createLCDD(lcdd.world()),argc,argv); + return dump_output(wr.createLCDD(lcdd.world()), argc, argv); } -static long create_vis(LCDD& lcdd, int argc, char** argv) { +static long create_vis(LCDD& lcdd, int argc, char** argv) { LCDDConverter wr(lcdd); - return dump_output(wr.createVis(lcdd.world()),argc,argv); + return dump_output(wr.createVis(lcdd.world()), argc, argv); } -static long create_visASCII(LCDD& lcdd, int argc, char** argv) { +static long create_visASCII(LCDD& lcdd, int argc, char** argv) { LCDDConverter wr(lcdd); xml_doc_t doc = wr.createVis(lcdd.world()); LCDDConverter::GeometryInfo& geo = wr.data(); - map<string,xml_comp_t> vis_map; - for(xml_coll_t c(geo.doc_display,_U(vis)); c; ++c) - vis_map.insert(make_pair(xml_comp_t(c).nameStr(),xml_comp_t(c))); + map<string, xml_comp_t> vis_map; + for (xml_coll_t c(geo.doc_display, _U(vis)); c; ++c) + vis_map.insert(make_pair(xml_comp_t(c).nameStr(), xml_comp_t(c))); const char* sep = ";"; ofstream os(argv[0]); - for(xml_coll_t c(geo.doc_structure,_U(volume)); c; ++c) { + for (xml_coll_t c(geo.doc_structure, _U(volume)); c; ++c) { xml_comp_t vol = c; xml_comp_t ref = c.child(_U(visref)); xml_comp_t vis = (*vis_map.find(ref.refStr())).second; xml_comp_t col = vis.child(_U(color)); - os << "vol:" << vol.nameStr() << sep - << "vis:" << vis.nameStr() << sep - << "visible:" << vis.visible() << sep - << "r:" << col.R() << sep - << "g:" << col.G() << sep - << "b:" << col.B() << sep - << "alpha:" << col.alpha() << sep - << "line_style:" << vis.attr<string>(_U(line_style)) << sep - << "drawing_style:" << vis.attr<string>(_U(drawing_style)) << sep - << "show_daughters:" << vis.show_daughters() << sep - << endl; + os << "vol:" << vol.nameStr() << sep << "vis:" << vis.nameStr() << sep << "visible:" << vis.visible() << sep << "r:" + << col.R() << sep << "g:" << col.G() << sep << "b:" << col.B() << sep << "alpha:" << col.alpha() << sep << "line_style:" + << vis.attr < string > (_U(line_style)) << sep << "drawing_style:" << vis.attr < string + > (_U(drawing_style)) << sep << "show_daughters:" << vis.show_daughters() << sep << endl; } os.close(); return 1; } -DECLARE_APPLY(DD4hepGeometry2VIS, create_vis); +DECLARE_APPLY(DD4hepGeometry2VIS, create_vis); DECLARE_APPLY(DD4hepGeometry2VISASCII, create_visASCII); -DECLARE_APPLY(DD4hepGeometry2GDML, create_gdml); -DECLARE_APPLY(DD4hepGeometry2LCDD, create_lcdd); +DECLARE_APPLY(DD4hepGeometry2GDML, create_gdml); +DECLARE_APPLY(DD4hepGeometry2LCDD, create_lcdd); diff --git a/DDCore/src/plugins/LCDDConverter.h b/DDCore/src/plugins/LCDDConverter.h index ac1065b8a..98e88f1cb 100644 --- a/DDCore/src/plugins/LCDDConverter.h +++ b/DDCore/src/plugins/LCDDConverter.h @@ -35,79 +35,91 @@ namespace DD4hep { /* * Geomentry namespace declaration */ - namespace Geometry { + namespace Geometry { /** @class LCDDConverter LCDDConverter.h XML/LCDDConverter.h - * + * * Geometry converter from DD4hep to Geant 4. * * @author M.Frank * @version 1.0 */ - struct LCDDConverter : public GeoHandler { + struct LCDDConverter: public GeoHandler { typedef XML::XmlElement XmlElement; - typedef std::map<const TGeoElement*,XmlElement*> ElementMap; + typedef std::map<const TGeoElement*, XmlElement*> ElementMap; typedef std::map<const TGeoMedium*, XmlElement*> MaterialMap; - typedef std::map<const TNamed*, XmlElement*> LimitMap; - typedef std::map<const TGeoNode*, XmlElement*> PlacementMap; - typedef std::map<const TNamed*, XmlElement*> RegionMap; - typedef std::map<const TNamed*, XmlElement*> SensDetMap; + typedef std::map<const TNamed*, XmlElement*> LimitMap; + typedef std::map<const TGeoNode*, XmlElement*> PlacementMap; + typedef std::map<const TNamed*, XmlElement*> RegionMap; + typedef std::map<const TNamed*, XmlElement*> SensDetMap; typedef std::map<const TGeoVolume*, XmlElement*> VolumeMap; - typedef std::map<const TGeoShape*, XmlElement*> SolidMap; - typedef std::map<const TNamed*, XmlElement*> VisMap; - typedef std::map<const TNamed*, XmlElement*> FieldMap; - typedef std::map<const TNamed*, XmlElement*> IdSpecMap; + typedef std::map<const TGeoShape*, XmlElement*> SolidMap; + typedef std::map<const TNamed*, XmlElement*> VisMap; + typedef std::map<const TNamed*, XmlElement*> FieldMap; + typedef std::map<const TNamed*, XmlElement*> IdSpecMap; typedef std::map<const TGeoMatrix*, XmlElement*> TrafoMap; - struct GeometryInfo : public GeoHandler::GeometryInfo { - ElementMap xmlElements; - MaterialMap xmlMaterials; - SolidMap xmlSolids; - VolumeMap xmlVolumes; - PlacementMap xmlPlacements; - RegionMap xmlRegions; - VisMap xmlVis; - LimitMap xmlLimits; - IdSpecMap xmlIdSpecs; - SensDetMap xmlSensDets; - TrafoMap xmlPositions; - TrafoMap xmlRotations; - FieldMap xmlFields; - ObjectSet sensitives; - ObjectSet regions; - ObjectSet limits; - // These we need for redundancy and checking the data integrity - typedef std::map<std::string,const TNamed*> CheckIter; - struct _checks { - std::map<std::string,const TNamed*> positions, rotations, volumes, solids, materials; - }; - mutable _checks checks; - void check(const std::string& name,const TNamed* n,std::map<std::string,const TNamed*>& array) const; - void checkPosition(const std::string& name,const TNamed* n) const { check(name,n,checks.positions); } - void checkRotation(const std::string& name,const TNamed* n) const { check(name,n,checks.rotations); } - void checkVolume (const std::string& name,const TNamed* n) const { check(name,n,checks.volumes); } - void checkShape (const std::string& name,const TNamed* n) const { check(name,n,checks.solids); } - void checkMaterial(const std::string& name,const TNamed* n) const { check(name,n,checks.materials); } - - xml_doc_t doc; - xml_h identity_rot, identity_pos; - xml_elt_t doc_root, doc_header, doc_idDict, doc_detectors, doc_limits, doc_regions, - doc_display, doc_gdml, doc_fields, doc_define, doc_materials, doc_solids, doc_structure, doc_setup; - GeometryInfo(); + struct GeometryInfo: public GeoHandler::GeometryInfo { + ElementMap xmlElements; + MaterialMap xmlMaterials; + SolidMap xmlSolids; + VolumeMap xmlVolumes; + PlacementMap xmlPlacements; + RegionMap xmlRegions; + VisMap xmlVis; + LimitMap xmlLimits; + IdSpecMap xmlIdSpecs; + SensDetMap xmlSensDets; + TrafoMap xmlPositions; + TrafoMap xmlRotations; + FieldMap xmlFields; + ObjectSet sensitives; + ObjectSet regions; + ObjectSet limits; + // These we need for redundancy and checking the data integrity + typedef std::map<std::string, const TNamed*> CheckIter; + struct _checks { + std::map<std::string, const TNamed*> positions, rotations, volumes, solids, materials; + }; + mutable _checks checks; + void check(const std::string& name, const TNamed* n, std::map<std::string, const TNamed*>& array) const; + void checkPosition(const std::string& name, const TNamed* n) const { + check(name, n, checks.positions); + } + void checkRotation(const std::string& name, const TNamed* n) const { + check(name, n, checks.rotations); + } + void checkVolume(const std::string& name, const TNamed* n) const { + check(name, n, checks.volumes); + } + void checkShape(const std::string& name, const TNamed* n) const { + check(name, n, checks.solids); + } + void checkMaterial(const std::string& name, const TNamed* n) const { + check(name, n, checks.materials); + } + + xml_doc_t doc; + xml_h identity_rot, identity_pos; + xml_elt_t doc_root, doc_header, doc_idDict, doc_detectors, doc_limits, doc_regions, doc_display, doc_gdml, doc_fields, + doc_define, doc_materials, doc_solids, doc_structure, doc_setup; + GeometryInfo(); }; typedef std::set<std::string> NameSet; /// Reference to detector description - LCDD& m_lcdd; + LCDD& m_lcdd; mutable NameSet m_checkNames; - GeometryInfo* m_dataPtr; + GeometryInfo* m_dataPtr; - GeometryInfo& data() const { return *m_dataPtr; } + GeometryInfo& data() const { + return *m_dataPtr; + } /// Data integrity checker void checkVolumes(const std::string& name, const TGeoVolume* volume) const; - + /// Initializing Constructor - LCDDConverter( LCDD& lcdd ); + LCDDConverter(LCDD& lcdd); /// Standard destructor virtual ~LCDDConverter(); @@ -136,7 +148,7 @@ namespace DD4hep { /// Convert the geometry type logical volume into the corresponding Xml object(s). virtual xml_h handleVolume(const std::string& name, const TGeoVolume* volume) const; virtual xml_h handleVolumeVis(const std::string& name, const TGeoVolume* volume) const; - virtual void collectVolume(const std::string& name, const TGeoVolume* volume) const; + virtual void collectVolume(const std::string& name, const TGeoVolume* volume) const; /// Convert the geometry type volume placement into the corresponding Xml object(s). virtual xml_h handlePlacement(const std::string& name, const TGeoNode* node) const; @@ -145,7 +157,7 @@ namespace DD4hep { ///virtual xml_h handleField(const std::string& name, Ref_t field) const; /// Convert the geometry type region into the corresponding Xml object(s). - virtual xml_h handleRegion(const std::string& name, const TNamed* region) const; + virtual xml_h handleRegion(const std::string& name, const TNamed* region) const; /// Convert the geometry visualisation attributes to the corresponding Xml object(s). virtual xml_h handleVis(const std::string& name, const TNamed* vis) const; @@ -154,22 +166,22 @@ namespace DD4hep { virtual xml_h handleIdSpec(const std::string& name, const TNamed* vis) const; /// Convert the geometry type LimitSet into the corresponding Xml object(s). - virtual xml_h handleLimitSet(const std::string& name, const TNamed* limitset) const; + virtual xml_h handleLimitSet(const std::string& name, const TNamed* limitset) const; /// Convert the geometry type SensitiveDetector into the corresponding Xml object(s). - virtual xml_h handleSensitive(const std::string& name, const TNamed* sens_det) const; + virtual xml_h handleSensitive(const std::string& name, const TNamed* sens_det) const; /// Convert the segmentation of a SensitiveDetector into the corresponding LCDD object - virtual xml_h handleSegmentation(Segmentation seg) const; + virtual xml_h handleSegmentation(Segmentation seg) const; /// Convert the Position into the corresponding Xml object(s). - virtual xml_h handlePosition(const std::string& name, const TGeoMatrix* trafo) const; + virtual xml_h handlePosition(const std::string& name, const TGeoMatrix* trafo) const; /// Convert the Rotation into the corresponding Xml object(s). - virtual xml_h handleRotation(const std::string& name, const TGeoMatrix* trafo) const; + virtual xml_h handleRotation(const std::string& name, const TGeoMatrix* trafo) const; /// Convert the electric or magnetic fields into the corresponding Xml object(s). - virtual xml_h handleField(const std::string& name, const TNamed* field) const; + virtual xml_h handleField(const std::string& name, const TNamed* field) const; /// Handle the geant 4 specific properties void handleProperties(LCDD::Properties& prp) const; diff --git a/DDCore/src/plugins/LCDDFields.cpp b/DDCore/src/plugins/LCDDFields.cpp index 22784b0c0..8f44c0202 100644 --- a/DDCore/src/plugins/LCDDFields.cpp +++ b/DDCore/src/plugins/LCDDFields.cpp @@ -16,17 +16,17 @@ using namespace DD4hep::Geometry; static Ref_t convert_constant_field(LCDD& lcdd, xml_h field, Ref_t object) { xml_doc_t doc = xml_elt_t(field).document(); ConstantField* s = object.data<ConstantField>(); - field.setAttr(_U(lunit),"mm"); + field.setAttr(_U(lunit), "mm"); //field.setAttr(_U(funit),"tesla"); - if ( s->type == CartesianField::ELECTRIC ) - field.setAttr(_U(field),"electric"); - else if ( s->type == CartesianField::MAGNETIC ) - field.setAttr(_U(field),"magnetic"); + if (s->type == CartesianField::ELECTRIC) + field.setAttr(_U(field), "electric"); + else if (s->type == CartesianField::MAGNETIC) + field.setAttr(_U(field), "magnetic"); - xml_elt_t strength = xml_elt_t(doc,_U(strength)); - strength.setAttr(_U(x),s->direction.X()); - strength.setAttr(_U(y),s->direction.Y()); - strength.setAttr(_U(z),s->direction.Z()); + xml_elt_t strength = xml_elt_t(doc, _U(strength)); + strength.setAttr(_U(x), s->direction.X()); + strength.setAttr(_U(y), s->direction.Y()); + strength.setAttr(_U(z), s->direction.Z()); field.append(strength); return object; } @@ -35,18 +35,18 @@ DECLARE_XML_PROCESSOR(ConstantField_Convert2LCDD,convert_constant_field); static Ref_t convert_solenoid(LCDD& lcdd, xml_h field, Ref_t object) { char text[128]; SolenoidField* s = object.data<SolenoidField>(); - field.setAttr(_U(lunit),"mm"); - field.setAttr(_U(funit),"tesla"); - ::snprintf(text,sizeof(text),"%g/mm",s->outerRadius); - field.setAttr(_U(outer_radius),_toDouble(text)); - ::snprintf(text,sizeof(text),"%g/mm",s->innerRadius); - field.setAttr(_U(inner_radius),_toDouble(text)); - ::snprintf(text,sizeof(text),"%g/tesla",s->innerField); - field.setAttr(_U(inner_field),_toDouble(text)); - ::snprintf(text,sizeof(text),"%g/tesla",s->outerField); - field.setAttr(_U(outer_field),_toDouble(text)); - field.setAttr(_U(zmin),s->minZ); - field.setAttr(_U(zmax),s->maxZ); + field.setAttr(_U(lunit), "mm"); + field.setAttr(_U(funit), "tesla"); + ::snprintf(text, sizeof(text), "%g/mm", s->outerRadius); + field.setAttr(_U(outer_radius), _toDouble(text)); + ::snprintf(text, sizeof(text), "%g/mm", s->innerRadius); + field.setAttr(_U(inner_radius), _toDouble(text)); + ::snprintf(text, sizeof(text), "%g/tesla", s->innerField); + field.setAttr(_U(inner_field), _toDouble(text)); + ::snprintf(text, sizeof(text), "%g/tesla", s->outerField); + field.setAttr(_U(outer_field), _toDouble(text)); + field.setAttr(_U(zmin), s->minZ); + field.setAttr(_U(zmax), s->maxZ); return object; } DECLARE_XML_PROCESSOR(solenoid_Convert2LCDD,convert_solenoid); @@ -55,17 +55,17 @@ static Ref_t convert_dipole(LCDD& lcdd, xml_h field, Ref_t object) { char text[128]; xml_doc_t doc = xml_elt_t(field).document(); DipoleField* s = object.data<DipoleField>(); - field.setAttr(_U(lunit),"mm"); - field.setAttr(_U(funit),"tesla"); - ::snprintf(text,sizeof(text),"%g/mm",s->rmax); - field.setAttr(_U(rmax),_toDouble(text)); - ::snprintf(text,sizeof(text),"%g/mm",s->zmax); - field.setAttr(_U(zmax),_toDouble(text)); - ::snprintf(text,sizeof(text),"%g/mm",s->zmin); - field.setAttr(_U(zmin),_toDouble(text)); - DipoleField::Coefficents::const_iterator i=s->coefficents.begin(); - for(; i != s->coefficents.end(); ++i) { - xml_elt_t coeff = xml_elt_t(doc,_U(dipole_coeff)); + field.setAttr(_U(lunit), "mm"); + field.setAttr(_U(funit), "tesla"); + ::snprintf(text, sizeof(text), "%g/mm", s->rmax); + field.setAttr(_U(rmax), _toDouble(text)); + ::snprintf(text, sizeof(text), "%g/mm", s->zmax); + field.setAttr(_U(zmax), _toDouble(text)); + ::snprintf(text, sizeof(text), "%g/mm", s->zmin); + field.setAttr(_U(zmin), _toDouble(text)); + DipoleField::Coefficents::const_iterator i = s->coefficents.begin(); + for (; i != s->coefficents.end(); ++i) { + xml_elt_t coeff = xml_elt_t(doc, _U(dipole_coeff)); coeff.setValue(_toString(*i)); field.append(coeff); } diff --git a/DDCore/src/plugins/PandoraConverter.cpp b/DDCore/src/plugins/PandoraConverter.cpp index 5a4a76572..8c32a920f 100644 --- a/DDCore/src/plugins/PandoraConverter.cpp +++ b/DDCore/src/plugins/PandoraConverter.cpp @@ -22,33 +22,33 @@ namespace DD4hep { /* * XML namespace declaration */ - namespace Geometry { + namespace Geometry { /** @class PandoraConverter PandoraConverter.h XML/PandoraConverter.h - * + * * Geometry converter from DD4hep to Geant 4. * * @author M.Frank * @version 1.0 */ - struct PandoraConverter : public GeoHandler { + struct PandoraConverter: public GeoHandler { protected: - struct GeometryInfo : public GeoHandler::GeometryInfo { - xml_doc_t doc; - xml_elt_t doc_root, doc_calorimeters, doc_detector, doc_coil, doc_tracking; - /// Helper constructor - GeometryInfo(); + struct GeometryInfo: public GeoHandler::GeometryInfo { + xml_doc_t doc; + xml_elt_t doc_root, doc_calorimeters, doc_detector, doc_coil, doc_tracking; + /// Helper constructor + GeometryInfo(); }; /// Reference to detector description - LCDD& m_lcdd; + LCDD& m_lcdd; /// Data pointer - GeometryInfo* m_dataPtr; + GeometryInfo* m_dataPtr; public: - + /// Initializing Constructor - PandoraConverter( LCDD& lcdd ); + PandoraConverter(LCDD& lcdd); /// Standard destructor virtual ~PandoraConverter(); @@ -61,7 +61,6 @@ namespace DD4hep { } // End namespace DD4hep #endif // DD4HEP_GEOMETRY_PANDORACONVERTER_H - //==================================================================== // AIDA Detector description implementation for LCD //-------------------------------------------------------------------- @@ -86,123 +85,121 @@ using namespace std; /// Helper constructor PandoraConverter::GeometryInfo::GeometryInfo() - : doc(0), doc_root(0), doc_calorimeters(0), doc_detector(0), doc_coil(0), doc_tracking(0) -{ + : doc(0), doc_root(0), doc_calorimeters(0), doc_detector(0), doc_coil(0), doc_tracking(0) { } /// Initializing Constructor -PandoraConverter::PandoraConverter( LCDD& lcdd ) - : m_lcdd(lcdd), m_dataPtr(0) -{ +PandoraConverter::PandoraConverter(LCDD& lcdd) + : m_lcdd(lcdd), m_dataPtr(0) { } /// Standard destructor PandoraConverter::~PandoraConverter() { - if ( m_dataPtr ) delete m_dataPtr; + if (m_dataPtr) + delete m_dataPtr; m_dataPtr = 0; } /// Create geometry conversion in Pandora XML format xml_doc_t PandoraConverter::create(DetElement top) { - const char empty_xml[] = - "<?xml version=\"1.0\" encoding=\"UTF-8\">\n" - "<!-- \n" - " +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n" - " ++++ Linear collider detector description in C++ ++++\n" - " ++++ DD4hep Detector description generator. ++++\n" - " ++++ ++++\n" - " ++++ M.Frank CERN/LHCb ++++\n" - " +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n" - "-->\n" - "<pandoraSetup>\n\0\0"; + const char empty_xml[] = "<?xml version=\"1.0\" encoding=\"UTF-8\">\n" + "<!-- \n" + " +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n" + " ++++ Linear collider detector description in C++ ++++\n" + " ++++ DD4hep Detector description generator. ++++\n" + " ++++ ++++\n" + " ++++ M.Frank CERN/LHCb ++++\n" + " +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n" + "-->\n" + "<pandoraSetup>\n\0\0"; XML::DocumentHandler docH; - GeometryInfo& geo = *(m_dataPtr=new GeometryInfo); + GeometryInfo& geo = *(m_dataPtr = new GeometryInfo); xml_elt_t elt(0); Header hdr = m_lcdd.header(); - geo.doc = docH.parse(empty_xml,sizeof(empty_xml)); + geo.doc = docH.parse(empty_xml, sizeof(empty_xml)); geo.doc_root = geo.doc.root(); - geo.doc_root.append(geo.doc_calorimeters = xml_elt_t(geo.doc,_Unicode(calorimeters))); - geo.doc_root.append(geo.doc_detector = xml_elt_t(geo.doc,_Unicode(detector))); - geo.doc_root.append(geo.doc_coil = xml_elt_t(geo.doc,_Unicode(coil))); - geo.doc_root.append(geo.doc_tracking = xml_elt_t(geo.doc,_Unicode(tracking))); - geo.doc_detector.setAttr(_Unicode(name),hdr.name()); - geo.doc_tracking.setAttr(_Unicode(innerR),""); - geo.doc_tracking.setAttr(_Unicode(outerR),""); - geo.doc_tracking.setAttr(_Unicode(z),""); - + geo.doc_root.append(geo.doc_calorimeters = xml_elt_t(geo.doc, _Unicode(calorimeters))); + geo.doc_root.append(geo.doc_detector = xml_elt_t(geo.doc, _Unicode(detector))); + geo.doc_root.append(geo.doc_coil = xml_elt_t(geo.doc, _Unicode(coil))); + geo.doc_root.append(geo.doc_tracking = xml_elt_t(geo.doc, _Unicode(tracking))); + geo.doc_detector.setAttr(_Unicode(name), hdr.name()); + geo.doc_tracking.setAttr(_Unicode(innerR), ""); + geo.doc_tracking.setAttr(_Unicode(outerR), ""); + geo.doc_tracking.setAttr(_Unicode(z), ""); + return geo.doc; } -static long create_lcdd(LCDD& lcdd, int argc, char** argv) { +static long create_lcdd(LCDD& lcdd, int argc, char** argv) { throw runtime_error("The pandora xml conversion plugin is not yet implemented"); return 0; #if 0 -package org.lcsim.geometry.compact.converter.pandora; - -import static org.lcsim.geometry.Calorimeter.CalorimeterType.EM_BARREL; -import static org.lcsim.geometry.Calorimeter.CalorimeterType.EM_ENDCAP; -import static org.lcsim.geometry.Calorimeter.CalorimeterType.HAD_BARREL; -import static org.lcsim.geometry.Calorimeter.CalorimeterType.HAD_ENDCAP; -import static org.lcsim.geometry.Calorimeter.CalorimeterType.MUON_BARREL; -import static org.lcsim.geometry.Calorimeter.CalorimeterType.MUON_ENDCAP; -import hep.physics.particle.properties.ParticlePropertyManager; -import hep.physics.particle.properties.ParticleType; -import hep.physics.vec.BasicHep3Vector; -import hep.physics.vec.Hep3Vector; - -import java.io.InputStream; -import java.io.OutputStream; -import java.text.DecimalFormat; -import java.util.ArrayList; -import java.util.List; -import java.util.StringTokenizer; - -import javax.swing.filechooser.FileFilter; - -import org.jdom.Document; -import org.jdom.Element; -import org.jdom.output.Format; -import org.jdom.output.XMLOutputter; -import org.lcsim.conditions.ConditionsManager; -import org.lcsim.conditions.ConditionsManager.ConditionsNotFoundException; -import org.lcsim.conditions.ConditionsSet; -import org.lcsim.detector.material.BetheBlochCalculator; -import org.lcsim.detector.material.IMaterial; -import org.lcsim.detector.material.MaterialStore; -import org.lcsim.detector.solids.Tube; -import org.lcsim.geometry.Calorimeter; -import org.lcsim.geometry.Calorimeter.CalorimeterType; -import org.lcsim.geometry.Detector; -import org.lcsim.geometry.GeometryReader; -import org.lcsim.geometry.compact.Subdetector; -import org.lcsim.geometry.compact.converter.Converter; -import org.lcsim.geometry.field.Solenoid; -import org.lcsim.geometry.layer.Layer; -import org.lcsim.geometry.layer.LayerSlice; -import org.lcsim.geometry.layer.LayerStack; -import org.lcsim.geometry.segmentation.AbstractCartesianGrid; -import org.lcsim.geometry.subdetector.AbstractPolyhedraCalorimeter; -import org.lcsim.geometry.subdetector.MultiLayerTracker; -import org.lcsim.geometry.util.BaseIDDecoder; -import org.lcsim.geometry.util.IDDescriptor; -import org.lcsim.geometry.util.SamplingFractionManager; - -/** - * This class converts from a compact detector description into slicPandora's - * geometry input format. - * - * @author Jeremy McCormick <jeremym@slac.stanford.edu> - * @version $Id$ - */ + package org.lcsim.geometry.compact.converter.pandora; + + import static org.lcsim.geometry.Calorimeter.CalorimeterType.EM_BARREL; + import static org.lcsim.geometry.Calorimeter.CalorimeterType.EM_ENDCAP; + import static org.lcsim.geometry.Calorimeter.CalorimeterType.HAD_BARREL; + import static org.lcsim.geometry.Calorimeter.CalorimeterType.HAD_ENDCAP; + import static org.lcsim.geometry.Calorimeter.CalorimeterType.MUON_BARREL; + import static org.lcsim.geometry.Calorimeter.CalorimeterType.MUON_ENDCAP; + import hep.physics.particle.properties.ParticlePropertyManager; + import hep.physics.particle.properties.ParticleType; + import hep.physics.vec.BasicHep3Vector; + import hep.physics.vec.Hep3Vector; + + import java.io.InputStream; + import java.io.OutputStream; + import java.text.DecimalFormat; + import java.util.ArrayList; + import java.util.List; + import java.util.StringTokenizer; + + import javax.swing.filechooser.FileFilter; + + import org.jdom.Document; + import org.jdom.Element; + import org.jdom.output.Format; + import org.jdom.output.XMLOutputter; + import org.lcsim.conditions.ConditionsManager; + import org.lcsim.conditions.ConditionsManager.ConditionsNotFoundException; + import org.lcsim.conditions.ConditionsSet; + import org.lcsim.detector.material.BetheBlochCalculator; + import org.lcsim.detector.material.IMaterial; + import org.lcsim.detector.material.MaterialStore; + import org.lcsim.detector.solids.Tube; + import org.lcsim.geometry.Calorimeter; + import org.lcsim.geometry.Calorimeter.CalorimeterType; + import org.lcsim.geometry.Detector; + import org.lcsim.geometry.GeometryReader; + import org.lcsim.geometry.compact.Subdetector; + import org.lcsim.geometry.compact.converter.Converter; + import org.lcsim.geometry.field.Solenoid; + import org.lcsim.geometry.layer.Layer; + import org.lcsim.geometry.layer.LayerSlice; + import org.lcsim.geometry.layer.LayerStack; + import org.lcsim.geometry.segmentation.AbstractCartesianGrid; + import org.lcsim.geometry.subdetector.AbstractPolyhedraCalorimeter; + import org.lcsim.geometry.subdetector.MultiLayerTracker; + import org.lcsim.geometry.util.BaseIDDecoder; + import org.lcsim.geometry.util.IDDescriptor; + import org.lcsim.geometry.util.SamplingFractionManager; + + /** + * This class converts from a compact detector description into slicPandora's + * geometry input format. + * + * @author Jeremy McCormick <jeremym@slac.stanford.edu> + * @version $Id$ + */ public class Main implements Converter -{ - private final static boolean DEBUG = false; - + { + private final static boolean DEBUG = false; + // ConditionsManager instance. - private ConditionsManager conditionsManager = ConditionsManager.defaultInstance(); - + private ConditionsManager conditionsManager = ConditionsManager.defaultInstance(); + // Numerical formatting. static final DecimalFormat xlen = new DecimalFormat("#.########"); static final DecimalFormat xfrac = new DecimalFormat("#.########"); @@ -210,687 +207,686 @@ public class Main implements Converter /** * A range of layers with associated EM and HAD sampling fractions. - * + * * @author Jeremy McCormick <jeremym@slac.stanford.edu> */ static class SamplingLayerRange { - int lowerLayer; - int upperLayer; - double em; - double had; + int lowerLayer; + int upperLayer; + double em; + double had; + + SamplingLayerRange(int lowerLayer, int upperLayer, double em, double had) + { + this.lowerLayer = lowerLayer; + this.upperLayer = upperLayer; + this.em = em; + this.had = had; + } + + public boolean inRange(int layerNumber) + { + return layerNumber >= lowerLayer && layerNumber <= upperLayer; + } + + public int getLowerLayer() + { + return lowerLayer; + } + + public int getUpperLayer() + { + return upperLayer; + } + + public double getEMSampling() + { + return em; + } + + public double getHADSampling() + { + return had; + } + } - SamplingLayerRange(int lowerLayer, int upperLayer, double em, double had) + /** + * A list of SamplingLayerRange objects to represent the sampling for a + * subdetector. + * + * @author Jeremy McCormick <jeremym@slac.stanford.edu> + * + */ + static class SamplingLayers extends ArrayList<SamplingLayerRange> + { + public SamplingLayers() + { + } + + public SamplingLayers(SamplingLayerRange range) + { + this.add(range); + } + + public SamplingLayers(List<SamplingLayerRange> ranges) + { + this.addAll(ranges); + } + + public SamplingLayerRange getSamplingLayerRange(int layern) + { + for (SamplingLayerRange range : this) { - this.lowerLayer = lowerLayer; - this.upperLayer = upperLayer; - this.em = em; - this.had = had; + if (range.inRange(layern)) + return range; } + return null; + } + } - public boolean inRange(int layerNumber) + /** + * Represents CalorimeterConditions for a single subdetector. + * + * @author Jeremy McCormick <jeremym@slac.stanford.edu> + */ + private static class CalorimeterConditions + { + SamplingLayers samplingLayers; + String name; + double mipEnergy; + double mipSigma; + double mipCut; + double timeCut; + + public String toString() + { + StringBuffer buff = new StringBuffer(); + buff.append(name + '\n'); + for (SamplingLayerRange range : samplingLayers) { - return layerNumber >= lowerLayer && layerNumber <= upperLayer; + buff.append("[" + range.getLowerLayer() + " - " + range.getUpperLayer() + "]" + '\n'); + buff.append(" em = " + range.getEMSampling() + '\n'); + buff.append(" had = " + range.getHADSampling() + '\n'); } - public int getLowerLayer() + return buff.toString(); + } + + public SamplingLayers getSamplingLayers() + { + return samplingLayers; + } + + /** + * Constructor that parses raw CalorimeterCalibration conditions for a + * single subdetector. + * + * @param calorimeter + * @param conditions + */ + protected CalorimeterConditions(Calorimeter calorimeter, ConditionsSet conditions) + { + //System.out.println("conditions: " + calorimeter.getName()); + this.name = calorimeter.getName(); + + // Figure out which layering conditions to use based on the + // CalorimeterType. + String layeringName = null; + if (calorimeter.getCalorimeterType() == CalorimeterType.EM_BARREL || calorimeter.getCalorimeterType() == CalorimeterType.EM_ENDCAP) { - return lowerLayer; + layeringName = "ECalLayering"; } - - public int getUpperLayer() + else if (calorimeter.getCalorimeterType() == CalorimeterType.HAD_BARREL || calorimeter.getCalorimeterType() == CalorimeterType.HAD_ENDCAP) { - return upperLayer; + layeringName = "HCalLayering"; } - - public double getEMSampling() + else if (calorimeter.getCalorimeterType() == CalorimeterType.MUON_BARREL || calorimeter.getCalorimeterType() == CalorimeterType.MUON_ENDCAP) { - return em; + layeringName = "MuonLayering"; } - - public double getHADSampling() + else { - return had; + throw new RuntimeException("Don't know how to handle CalorimeterConditions for " + calorimeter.getName() + "."); } - } - /** - * A list of SamplingLayerRange objects to represent the sampling for a - * subdetector. - * - * @author Jeremy McCormick <jeremym@slac.stanford.edu> - * - */ - static class SamplingLayers extends ArrayList<SamplingLayerRange> - { - public SamplingLayers() + String emName = null; + String hadName = null; + if (calorimeter.getCalorimeterType() == CalorimeterType.EM_BARREL || calorimeter.getCalorimeterType() == CalorimeterType.HAD_BARREL || calorimeter.getCalorimeterType() == CalorimeterType.MUON_BARREL) { + emName = "EMBarrel_SF"; + hadName = "HadBarrel_SF"; } - - public SamplingLayers(SamplingLayerRange range) + else if (calorimeter.getCalorimeterType() == CalorimeterType.EM_ENDCAP || calorimeter.getCalorimeterType() == CalorimeterType.HAD_ENDCAP || calorimeter.getCalorimeterType() == CalorimeterType.MUON_ENDCAP) { - this.add(range); + emName = "EMEndcap_SF"; + hadName = "HadEndcap_SF"; } - public SamplingLayers(List<SamplingLayerRange> ranges) + if (emName == null || hadName == null) { - this.addAll(ranges); + throw new RuntimeException("Sampling fractions not found for " + calorimeter.getName() + "."); } - public SamplingLayerRange getSamplingLayerRange(int layern) + String emSampling = conditions.getString(emName); + String hadSampling = conditions.getString(hadName); + List<Double> emSamplingFractions = new ArrayList<Double>(); + List<Double> hadSamplingFractions = new ArrayList<Double>(); + StringTokenizer tok = new StringTokenizer(emSampling, ","); + while (tok.hasMoreTokens()) { - for (SamplingLayerRange range : this) - { - if (range.inRange(layern)) - return range; - } - return null; + Double emSamplingFraction = Double.valueOf(tok.nextToken().trim()); + emSamplingFractions.add(emSamplingFraction); } - } - - /** - * Represents CalorimeterConditions for a single subdetector. - * - * @author Jeremy McCormick <jeremym@slac.stanford.edu> - */ - private static class CalorimeterConditions - { - SamplingLayers samplingLayers; - String name; - double mipEnergy; - double mipSigma; - double mipCut; - double timeCut; - - public String toString() + tok = new StringTokenizer(hadSampling, ","); + while (tok.hasMoreTokens()) { - StringBuffer buff = new StringBuffer(); - buff.append(name + '\n'); - for (SamplingLayerRange range : samplingLayers) - { - buff.append("[" + range.getLowerLayer() + " - " + range.getUpperLayer() + "]" + '\n'); - buff.append(" em = " + range.getEMSampling() + '\n'); - buff.append(" had = " + range.getHADSampling() + '\n'); - } - - return buff.toString(); + Double hadSamplingFraction = Double.valueOf(tok.nextToken().trim()); + hadSamplingFractions.add(hadSamplingFraction); } - public SamplingLayers getSamplingLayers() + String layering = conditions.getString(layeringName); + tok = new StringTokenizer(layering, ","); + List<Integer> layers = new ArrayList<Integer>(); + int maxLayer = calorimeter.getLayering().getLayerCount() - 1; + while (tok.hasMoreTokens()) { - return samplingLayers; + String nextToken = tok.nextToken().trim(); + int nextLayer = Integer.valueOf(nextToken); + layers.add(nextLayer); } - /** - * Constructor that parses raw CalorimeterCalibration conditions for a - * single subdetector. - * - * @param calorimeter - * @param conditions - */ - protected CalorimeterConditions(Calorimeter calorimeter, ConditionsSet conditions) + // FIXME Hack to get the correct starting index for the sampling + // fractions. Ideally, the sampling fractions should be separated by subdetector name. + int samplingIndex = 0; + if (calorimeter.getCalorimeterType() == HAD_BARREL || calorimeter.getCalorimeterType() == HAD_ENDCAP) { - //System.out.println("conditions: " + calorimeter.getName()); - this.name = calorimeter.getName(); - - // Figure out which layering conditions to use based on the - // CalorimeterType. - String layeringName = null; - if (calorimeter.getCalorimeterType() == CalorimeterType.EM_BARREL || calorimeter.getCalorimeterType() == CalorimeterType.EM_ENDCAP) - { - layeringName = "ECalLayering"; - } - else if (calorimeter.getCalorimeterType() == CalorimeterType.HAD_BARREL || calorimeter.getCalorimeterType() == CalorimeterType.HAD_ENDCAP) - { - layeringName = "HCalLayering"; - } - else if (calorimeter.getCalorimeterType() == CalorimeterType.MUON_BARREL || calorimeter.getCalorimeterType() == CalorimeterType.MUON_ENDCAP) - { - layeringName = "MuonLayering"; - } - else - { - throw new RuntimeException("Don't know how to handle CalorimeterConditions for " + calorimeter.getName() + "."); - } - - String emName = null; - String hadName = null; - if (calorimeter.getCalorimeterType() == CalorimeterType.EM_BARREL || calorimeter.getCalorimeterType() == CalorimeterType.HAD_BARREL || calorimeter.getCalorimeterType() == CalorimeterType.MUON_BARREL) - { - emName = "EMBarrel_SF"; - hadName = "HadBarrel_SF"; - } - else if (calorimeter.getCalorimeterType() == CalorimeterType.EM_ENDCAP || calorimeter.getCalorimeterType() == CalorimeterType.HAD_ENDCAP || calorimeter.getCalorimeterType() == CalorimeterType.MUON_ENDCAP) - { - emName = "EMEndcap_SF"; - hadName = "HadEndcap_SF"; - } - - if (emName == null || hadName == null) - { - throw new RuntimeException("Sampling fractions not found for " + calorimeter.getName() + "."); - } - - String emSampling = conditions.getString(emName); - String hadSampling = conditions.getString(hadName); - List<Double> emSamplingFractions = new ArrayList<Double>(); - List<Double> hadSamplingFractions = new ArrayList<Double>(); - StringTokenizer tok = new StringTokenizer(emSampling, ","); - while (tok.hasMoreTokens()) - { - Double emSamplingFraction = Double.valueOf(tok.nextToken().trim()); - emSamplingFractions.add(emSamplingFraction); - } - tok = new StringTokenizer(hadSampling, ","); - while (tok.hasMoreTokens()) - { - Double hadSamplingFraction = Double.valueOf(tok.nextToken().trim()); - hadSamplingFractions.add(hadSamplingFraction); - } - - String layering = conditions.getString(layeringName); - tok = new StringTokenizer(layering, ","); - List<Integer> layers = new ArrayList<Integer>(); - int maxLayer = calorimeter.getLayering().getLayerCount() - 1; - while (tok.hasMoreTokens()) - { - String nextToken = tok.nextToken().trim(); - int nextLayer = Integer.valueOf(nextToken); - layers.add(nextLayer); - } - - // FIXME Hack to get the correct starting index for the sampling - // fractions. Ideally, the sampling fractions should be separated by subdetector name. - int samplingIndex = 0; - if (calorimeter.getCalorimeterType() == HAD_BARREL || calorimeter.getCalorimeterType() == HAD_ENDCAP) - { - samplingIndex = (new StringTokenizer(conditions.getString("ECalLayering"), ",").countTokens()); - } - if (calorimeter.getCalorimeterType() == MUON_BARREL || calorimeter.getCalorimeterType() == MUON_ENDCAP) - { - samplingIndex = (new StringTokenizer(conditions.getString("ECalLayering"), ",").countTokens()); - samplingIndex += (new StringTokenizer(conditions.getString("HCalLayering"), ",").countTokens()); - } - - // System.out.println(" samplingIndex: " + samplingIndex); - - // Create the SamplingLayerRange list. - samplingLayers = new SamplingLayers(); - for (int i = 0; i < layers.size(); i++) - { - // Figure out the layer range. - int lowerLayer = layers.get(i); - int upperLayer = 0; - if (i + 1 > layers.size() - 1) - upperLayer = maxLayer; - else - upperLayer = layers.get(i + 1) - 1; - - // Create the sampling layer range. - double emSamplingFraction = emSamplingFractions.get(samplingIndex); - double hadSamplingFraction = hadSamplingFractions.get(samplingIndex); - SamplingLayerRange samplingLayerRange = new SamplingLayerRange(lowerLayer, upperLayer, emSamplingFraction, hadSamplingFraction); - // System.out.println(" " + lowerLayer + " - " + upperLayer + - // " : " + emSamplingFraction + ", " + hadSamplingFraction); - - samplingLayers.add(samplingLayerRange); - - ++samplingIndex; - } - - // MIP energy. - String mipCondition = null; - String mipSigmaCondition = null; - String mipCutCondition = null; - - // FIXME: Cleanup this ugliness. - if (calorimeter.getCalorimeterType() == CalorimeterType.EM_BARREL || calorimeter.getCalorimeterType() == CalorimeterType.EM_ENDCAP) - { - mipCondition = "ECalMip_MPV"; - mipSigmaCondition = "ECalMip_sig"; - mipCutCondition = "ECalMip_Cut"; - } - else if (calorimeter.getCalorimeterType() == CalorimeterType.HAD_BARREL || calorimeter.getCalorimeterType() == CalorimeterType.HAD_ENDCAP) - { - mipCondition = "HCalMip_MPV"; - mipSigmaCondition = "HCalMip_sig"; - mipCutCondition = "HCalMip_Cut"; - } - else if (calorimeter.getCalorimeterType() == CalorimeterType.MUON_BARREL || calorimeter.getCalorimeterType() == CalorimeterType.MUON_ENDCAP) - { - mipCondition = "MuonMip_MPV"; - mipSigmaCondition = "MuonMip_sig"; - mipCutCondition = "MuonMip_Cut"; - } - mipEnergy = conditions.getDouble(mipCondition); - mipSigma = conditions.getDouble(mipSigmaCondition); - mipCut = conditions.getDouble(mipCutCondition); - timeCut = conditions.getDouble("timeCut"); - - /* - * System.out.println(" mipEnergy: " + mipEnergy); - * System.out.println(" mipSigma: " + mipSigma); - * System.out.println(" mipCut: " + mipCut); - * System.out.println(" timeCut: " + timeCut); - */ + samplingIndex = (new StringTokenizer(conditions.getString("ECalLayering"), ",").countTokens()); } - - public SamplingLayerRange getSamplingLayerRange(int layer) + if (calorimeter.getCalorimeterType() == MUON_BARREL || calorimeter.getCalorimeterType() == MUON_ENDCAP) { - for (SamplingLayerRange layers : this.samplingLayers) - { - if (layers.inRange(layer)) - return layers; - } - return null; + samplingIndex = (new StringTokenizer(conditions.getString("ECalLayering"), ",").countTokens()); + samplingIndex += (new StringTokenizer(conditions.getString("HCalLayering"), ",").countTokens()); } - public double getMipEnergy() + // System.out.println(" samplingIndex: " + samplingIndex); + + // Create the SamplingLayerRange list. + samplingLayers = new SamplingLayers(); + for (int i = 0; i < layers.size(); i++) { - return mipEnergy; + // Figure out the layer range. + int lowerLayer = layers.get(i); + int upperLayer = 0; + if (i + 1 > layers.size() - 1) + upperLayer = maxLayer; + else + upperLayer = layers.get(i + 1) - 1; + + // Create the sampling layer range. + double emSamplingFraction = emSamplingFractions.get(samplingIndex); + double hadSamplingFraction = hadSamplingFractions.get(samplingIndex); + SamplingLayerRange samplingLayerRange = new SamplingLayerRange(lowerLayer, upperLayer, emSamplingFraction, hadSamplingFraction); + // System.out.println(" " + lowerLayer + " - " + upperLayer + + // " : " + emSamplingFraction + ", " + hadSamplingFraction); + + samplingLayers.add(samplingLayerRange); + + ++samplingIndex; } - public double getMipSigma() + // MIP energy. + String mipCondition = null; + String mipSigmaCondition = null; + String mipCutCondition = null; + + // FIXME: Cleanup this ugliness. + if (calorimeter.getCalorimeterType() == CalorimeterType.EM_BARREL || calorimeter.getCalorimeterType() == CalorimeterType.EM_ENDCAP) { - return mipSigma; + mipCondition = "ECalMip_MPV"; + mipSigmaCondition = "ECalMip_sig"; + mipCutCondition = "ECalMip_Cut"; } - - public double getMipCut() + else if (calorimeter.getCalorimeterType() == CalorimeterType.HAD_BARREL || calorimeter.getCalorimeterType() == CalorimeterType.HAD_ENDCAP) + { + mipCondition = "HCalMip_MPV"; + mipSigmaCondition = "HCalMip_sig"; + mipCutCondition = "HCalMip_Cut"; + } + else if (calorimeter.getCalorimeterType() == CalorimeterType.MUON_BARREL || calorimeter.getCalorimeterType() == CalorimeterType.MUON_ENDCAP) { - return mipCut; + mipCondition = "MuonMip_MPV"; + mipSigmaCondition = "MuonMip_sig"; + mipCutCondition = "MuonMip_Cut"; } + mipEnergy = conditions.getDouble(mipCondition); + mipSigma = conditions.getDouble(mipSigmaCondition); + mipCut = conditions.getDouble(mipCutCondition); + timeCut = conditions.getDouble("timeCut"); + + /* + * System.out.println(" mipEnergy: " + mipEnergy); + * System.out.println(" mipSigma: " + mipSigma); + * System.out.println(" mipCut: " + mipCut); + * System.out.println(" timeCut: " + timeCut); + */ + } - public double getTimeCut() + public SamplingLayerRange getSamplingLayerRange(int layer) + { + for (SamplingLayerRange layers : this.samplingLayers) { - return timeCut; + if (layers.inRange(layer)) + return layers; } + return null; + } + + public double getMipEnergy() + { + return mipEnergy; + } + + public double getMipSigma() + { + return mipSigma; + } + + public double getMipCut() + { + return mipCut; + } + + public double getTimeCut() + { + return timeCut; + } } - public void convert(String inputFileName, InputStream in, OutputStream out) throws Exception + public void convert(String inputFileName, InputStream in, OutputStream out) throws Exception { - GeometryReader reader = new GeometryReader(); - Detector det = reader.read(in); - String detectorName = det.getDetectorName(); - try - { - conditionsManager.setDetector(detectorName, 0); - } - catch (ConditionsNotFoundException x) - { - throw new RuntimeException("Failed to setup conditions system for detector: " + detectorName, x); - } - Document doc = convertDetectorToPandora(det); - XMLOutputter outputter = new XMLOutputter(); - if (out != null) - { - outputter.setFormat(Format.getPrettyFormat()); - outputter.output(doc, out); - out.close(); - } + GeometryReader reader = new GeometryReader(); + Detector det = reader.read(in); + String detectorName = det.getDetectorName(); + try + { + conditionsManager.setDetector(detectorName, 0); + } + catch (ConditionsNotFoundException x) + { + throw new RuntimeException("Failed to setup conditions system for detector: " + detectorName, x); + } + Document doc = convertDetectorToPandora(det); + XMLOutputter outputter = new XMLOutputter(); + if (out != null) + { + outputter.setFormat(Format.getPrettyFormat()); + outputter.output(doc, out); + out.close(); + } } - public Document convertDetectorToPandora(Detector detector) + public Document convertDetectorToPandora(Detector detector) { - // Setup XML output document. - Document outputDoc = new Document(); - Element root = new Element("pandoraSetup"); - outputDoc.setRootElement(root); - Element calorimeters = new Element("calorimeters"); - root.addContent(calorimeters); - - // Add basic detector data element. - Element detectorTag = new Element("detector"); - detectorTag.setAttribute("name", detector.getDetectorName()); - root.addContent(detectorTag); - - // Setup CalorimeterCalibration conditions. - ConditionsSet calorimeterCalibration = null; - try - { - calorimeterCalibration = conditionsManager.getConditions("CalorimeterCalibration"); - } - catch (Exception x) - { - } - boolean haveCalCalib = (calorimeterCalibration == null) ? false : true; - - // Process the subdetectors. - for (Subdetector subdetector : detector.getSubdetectors().values()) - { - //System.out.println(subdetector.getName()); - // Only handle calorimeters that are planar. - if (subdetector instanceof AbstractPolyhedraCalorimeter) - { - Element calorimeter = new Element("calorimeter"); - AbstractPolyhedraCalorimeter polycal = (AbstractPolyhedraCalorimeter) subdetector; - - // Look for specific calorimeter types in the compact - // description. - Calorimeter.CalorimeterType calType = polycal.getCalorimeterType(); - if (calType.equals(HAD_BARREL) || calType.equals(HAD_ENDCAP) || calType.equals(EM_ENDCAP) || calType.equals(EM_BARREL) || calType.equals(MUON_BARREL) || calType.equals(MUON_ENDCAP)) - { - // Set basic parameters in pandora calorimeter. - calorimeter.setAttribute("type", Calorimeter.CalorimeterType.toString(calType)); - calorimeter.setAttribute("innerR", Double.toString(polycal.getInnerRadius())); - calorimeter.setAttribute("innerZ", Double.toString(polycal.getInnerZ())); - calorimeter.setAttribute("innerPhi", Double.toString(polycal.getSectionPhi())); - calorimeter.setAttribute("innerSymmetryOrder", Double.toString(polycal.getNumberOfSides())); - calorimeter.setAttribute("outerR", Double.toString(polycal.getOuterRadius())); - calorimeter.setAttribute("outerZ", Double.toString(polycal.getOuterZ())); - calorimeter.setAttribute("outerPhi", Double.toString(polycal.getSectionPhi())); - calorimeter.setAttribute("outerSymmetryOrder", Double.toString(polycal.getNumberOfSides())); - calorimeter.setAttribute("collection", subdetector.getReadout().getName()); - - // Get the cell sizes from the segmentation. - List<Double> cellSizes = getCellSizes(subdetector); - - // For endcaps, X is U, and Y is V. - if (subdetector.isEndcap()) - { - calorimeter.setAttribute("cellSizeU", Double.toString(cellSizes.get(0))); - calorimeter.setAttribute("cellSizeV", Double.toString(cellSizes.get(1))); - } - // The UV mapping is flipped around for barrel. X is V, and Y is U. - else if (subdetector.isBarrel()) - { - calorimeter.setAttribute("cellSizeU", Double.toString(cellSizes.get(1))); - calorimeter.setAttribute("cellSizeV", Double.toString(cellSizes.get(0))); - } - - // Create identifier description and add to subdet. - calorimeter.addContent(makeIdentifierDescription(polycal)); - - // Add the calorimeter. - calorimeters.addContent(calorimeter); - - LayerStack layers = polycal.getLayering().getLayerStack(); - - Element layersElem = new Element("layers"); - layersElem.setAttribute("nlayers", Integer.toString(layers.getNumberOfLayers())); - - calorimeter.addContent(layersElem); - - double layerD = 0.; - - if (polycal.isBarrel()) - { - layerD = polycal.getInnerRadius(); - } - else if (polycal.isEndcap()) - { - layerD = polycal.getInnerZ(); - } - - CalorimeterConditions subdetectorCalorimeterConditions = null; - - if (haveCalCalib) - { - subdetectorCalorimeterConditions = new CalorimeterConditions((Calorimeter) subdetector, calorimeterCalibration); - } - - // Set MIP energy from calibration. - if (haveCalCalib) - { - calorimeter.setAttribute("mipEnergy", xfrac.format(subdetectorCalorimeterConditions.getMipEnergy())); - calorimeter.setAttribute("mipSigma", xfrac.format(subdetectorCalorimeterConditions.getMipSigma())); - calorimeter.setAttribute("mipCut", xfrac.format(subdetectorCalorimeterConditions.getMipCut())); - calorimeter.setAttribute("timeCut", xfrac.format(subdetectorCalorimeterConditions.getTimeCut())); - } - // Set MIP energy from Bethe-Bloche calculation. - // TODO Check accuracy of this algorithm. - else - { - List<LayerSlice> sensors = subdetector.getLayering().getLayerStack().getLayer(0).getSensors(); - LayerSlice sensor = sensors.get(0); - IMaterial sensorMaterial = MaterialStore.getInstance().get(sensor.getMaterial().getName()); - - ParticleType particleType = ParticlePropertyManager.getParticlePropertyProvider().get(13); - - Hep3Vector p = new BasicHep3Vector(-6.8641, -7.2721, 1.2168e-7); - - double emip = BetheBlochCalculator.computeBetheBloch(sensorMaterial, p, particleType.getMass(), particleType.getCharge(), sensor.getThickness()); - - // Set MIP Energy from Bethe Bloche. - calorimeter.setAttribute("mipEnergy", xfrac.format(emip)); - - // Set defaults for CalCalib parameters. - calorimeter.setAttribute("mipSigma", "0"); - calorimeter.setAttribute("mipCut", "0"); - calorimeter.setAttribute("timeCut", xfrac.format(Double.MAX_VALUE)); - } - - double totalX0 = 0; - - for (int i = 0; i < layers.getNumberOfLayers(); i++) - { - //System.out.println(" layer " + i); - Layer layer = layers.getLayer(i); - - Element layerElem = new Element("layer"); - layersElem.addContent(layerElem); - - // Set radiation and interaction lengths. - double intLen = 0; - double radLen = 0; - for (int j = 0; j < layer.getNumberOfSlices(); j++) - { - LayerSlice slice = layer.getSlice(j); - //System.out.println(" slice " + j + " " + slice.getMaterial().getName()); - double x0 = slice.getMaterial().getRadiationLength(); - //System.out.println(" x0_mat_D="+x0); - //System.out.println(" x0_mat="+slice.getMaterial().getRadiationLength()); - radLen += slice.getThickness() / (x0*10); - //System.out.println(" radLen="+radLen); - - double lambda = slice.getMaterial().getNuclearInteractionLength(); - intLen += slice.getThickness() / (lambda*10); - } - //System.out.println(" x0_lyr_tot=" + radLen); - - - totalX0 += radLen; - - //System.out.println(" layer " + i + " " + radLen); - - layerElem.setAttribute("radLen", xlen.format(radLen)); - layerElem.setAttribute("intLen", xlen.format(intLen)); - - // Set distance to IP. - double layerD2 = layerD + layer.getThicknessToSensitiveMid(); - layerElem.setAttribute("distanceToIp", xthick.format(layerD2)); - - // Set cell thickness. - layerElem.setAttribute("cellThickness", xthick.format(layer.getThickness())); - - // Set EM and HAD sampling fractions from - // CalorimeterCalibration conditions, if present. - if (haveCalCalib) - { - SamplingLayerRange layerRange = subdetectorCalorimeterConditions.getSamplingLayerRange(i); - if (calType == EM_BARREL || calType == EM_ENDCAP) - { - layerElem.setAttribute("samplingFraction", xfrac.format(layerRange.getEMSampling())); - } - if (calType == HAD_BARREL || calType == HAD_ENDCAP) - { - layerElem.setAttribute("samplingFraction", xfrac.format(layerRange.getHADSampling())); - } - if (calType == MUON_BARREL || calType == MUON_ENDCAP) - { - layerElem.setAttribute("samplingFraction", xfrac.format(layerRange.getHADSampling())); - } - layerElem.setAttribute("emSamplingFraction", xfrac.format(layerRange.getEMSampling())); - layerElem.setAttribute("hadSamplingFraction", xfrac.format(layerRange.getHADSampling())); - } - // Set from base SamplingFraction conditions. May throw - // an exception if neither CalorimeterCalibration - // or SamplingFractions conditions exists. - else - { - double samplingFraction = SamplingFractionManager.defaultInstance().getSamplingFraction(subdetector, i); - layerElem.setAttribute("emSamplingFraction", xfrac.format(samplingFraction)); - layerElem.setAttribute("hadSamplingFraction", xfrac.format(samplingFraction)); - } - - // Increment layer distance by thickness of layer. - layerD += layer.getThickness(); - } - - //System.out.println(" X0 Sum = " + totalX0); - } - - // Set digital flag. - try - { - // Set digital attribute from conditions, if present. - ConditionsSet conditions = conditionsManager.getConditions("SamplingFractions/" + subdetector.getName()); - boolean isDigital = conditions.getBoolean("digital"); - calorimeter.setAttribute("digital", String.valueOf(isDigital)); - } - catch (Exception x) - { - calorimeter.setAttribute("digital", "false"); - } - } - } - - // TODO clean up the hard coded assumptions on coil geometry - double coilRadLen = 0; - double coilIntLen = 0; - int coilLayers = 0; - double coilInnerR = 0; - double coilOuterR = 0; - double bfield = 0; - double coilMaxZ = 0; - try - { - MultiLayerTracker c = (MultiLayerTracker) detector.getSubdetector("SolenoidCoilBarrel"); - if (c != null) - { - coilLayers = c.getNumberOfLayers(); - coilInnerR = c.getInnerR()[0]; - coilOuterR = c.getInnerR()[coilLayers-1] + c.getLayerThickness(coilLayers-1); - for (int layern = 0; layern != c.getNumberOfLayers(); layern++) - { - for (LayerSlice slice : c.getLayer(layern).getSlices()) - { - double x0 = slice.getMaterial().getRadiationLength(); - double sliceRadLen = slice.getThickness() / (x0*10); - double lambda = slice.getMaterial().getNuclearInteractionLength(); - double sliceIntLen = slice.getThickness() / (lambda*10); - - coilRadLen += sliceRadLen; - coilIntLen += sliceIntLen; - } - } - //calculate average interaction/radiation length in coil material - coilRadLen = coilRadLen/(coilOuterR-coilInnerR); - coilIntLen = coilIntLen/(coilOuterR-coilInnerR); - } - } - catch (ClassCastException e) - { - throw new RuntimeException(e); - } - try - { - Solenoid s = (Solenoid) detector.getFields().get("GlobalSolenoid"); - if (s != null) - { - bfield = s.getField(new BasicHep3Vector(0, 0, 0)).z(); - coilMaxZ = s.getZMax(); - } - } - catch (ClassCastException e) - { - throw new RuntimeException(e); - } - - Element coil = new Element("coil"); - coil.setAttribute("radLen", xlen.format(coilRadLen)); - coil.setAttribute("intLen", xlen.format(coilIntLen)); - coil.setAttribute("innerR", Double.toString(coilInnerR)); - coil.setAttribute("outerR", Double.toString(coilOuterR)); - coil.setAttribute("z", Double.toString(coilMaxZ)); - coil.setAttribute("bfield", Double.toString(bfield)); - root.addContent(coil); - - Tube tube = (Tube) detector.getTrackingVolume().getLogicalVolume().getSolid(); - Element tracking = new Element("tracking"); - tracking.setAttribute("innerR", Double.toString(tube.getInnerRadius())); - tracking.setAttribute("outerR", Double.toString(tube.getOuterRadius())); - tracking.setAttribute("z", Double.toString(tube.getZHalfLength())); - root.addContent(tracking); - - return outputDoc; + // Setup XML output document. + Document outputDoc = new Document(); + Element root = new Element("pandoraSetup"); + outputDoc.setRootElement(root); + Element calorimeters = new Element("calorimeters"); + root.addContent(calorimeters); + + // Add basic detector data element. + Element detectorTag = new Element("detector"); + detectorTag.setAttribute("name", detector.getDetectorName()); + root.addContent(detectorTag); + + // Setup CalorimeterCalibration conditions. + ConditionsSet calorimeterCalibration = null; + try + { + calorimeterCalibration = conditionsManager.getConditions("CalorimeterCalibration"); + } + catch (Exception x) + { + } + boolean haveCalCalib = (calorimeterCalibration == null) ? false : true; + + // Process the subdetectors. + for (Subdetector subdetector : detector.getSubdetectors().values()) + { + //System.out.println(subdetector.getName()); + // Only handle calorimeters that are planar. + if (subdetector instanceof AbstractPolyhedraCalorimeter) + { + Element calorimeter = new Element("calorimeter"); + AbstractPolyhedraCalorimeter polycal = (AbstractPolyhedraCalorimeter) subdetector; + + // Look for specific calorimeter types in the compact + // description. + Calorimeter.CalorimeterType calType = polycal.getCalorimeterType(); + if (calType.equals(HAD_BARREL) || calType.equals(HAD_ENDCAP) || calType.equals(EM_ENDCAP) || calType.equals(EM_BARREL) || calType.equals(MUON_BARREL) || calType.equals(MUON_ENDCAP)) + { + // Set basic parameters in pandora calorimeter. + calorimeter.setAttribute("type", Calorimeter.CalorimeterType.toString(calType)); + calorimeter.setAttribute("innerR", Double.toString(polycal.getInnerRadius())); + calorimeter.setAttribute("innerZ", Double.toString(polycal.getInnerZ())); + calorimeter.setAttribute("innerPhi", Double.toString(polycal.getSectionPhi())); + calorimeter.setAttribute("innerSymmetryOrder", Double.toString(polycal.getNumberOfSides())); + calorimeter.setAttribute("outerR", Double.toString(polycal.getOuterRadius())); + calorimeter.setAttribute("outerZ", Double.toString(polycal.getOuterZ())); + calorimeter.setAttribute("outerPhi", Double.toString(polycal.getSectionPhi())); + calorimeter.setAttribute("outerSymmetryOrder", Double.toString(polycal.getNumberOfSides())); + calorimeter.setAttribute("collection", subdetector.getReadout().getName()); + + // Get the cell sizes from the segmentation. + List<Double> cellSizes = getCellSizes(subdetector); + + // For endcaps, X is U, and Y is V. + if (subdetector.isEndcap()) + { + calorimeter.setAttribute("cellSizeU", Double.toString(cellSizes.get(0))); + calorimeter.setAttribute("cellSizeV", Double.toString(cellSizes.get(1))); + } + // The UV mapping is flipped around for barrel. X is V, and Y is U. + else if (subdetector.isBarrel()) + { + calorimeter.setAttribute("cellSizeU", Double.toString(cellSizes.get(1))); + calorimeter.setAttribute("cellSizeV", Double.toString(cellSizes.get(0))); + } + + // Create identifier description and add to subdet. + calorimeter.addContent(makeIdentifierDescription(polycal)); + + // Add the calorimeter. + calorimeters.addContent(calorimeter); + + LayerStack layers = polycal.getLayering().getLayerStack(); + + Element layersElem = new Element("layers"); + layersElem.setAttribute("nlayers", Integer.toString(layers.getNumberOfLayers())); + + calorimeter.addContent(layersElem); + + double layerD = 0.; + + if (polycal.isBarrel()) + { + layerD = polycal.getInnerRadius(); + } + else if (polycal.isEndcap()) + { + layerD = polycal.getInnerZ(); + } + + CalorimeterConditions subdetectorCalorimeterConditions = null; + + if (haveCalCalib) + { + subdetectorCalorimeterConditions = new CalorimeterConditions((Calorimeter) subdetector, calorimeterCalibration); + } + + // Set MIP energy from calibration. + if (haveCalCalib) + { + calorimeter.setAttribute("mipEnergy", xfrac.format(subdetectorCalorimeterConditions.getMipEnergy())); + calorimeter.setAttribute("mipSigma", xfrac.format(subdetectorCalorimeterConditions.getMipSigma())); + calorimeter.setAttribute("mipCut", xfrac.format(subdetectorCalorimeterConditions.getMipCut())); + calorimeter.setAttribute("timeCut", xfrac.format(subdetectorCalorimeterConditions.getTimeCut())); + } + // Set MIP energy from Bethe-Bloche calculation. + // TODO Check accuracy of this algorithm. + else + { + List<LayerSlice> sensors = subdetector.getLayering().getLayerStack().getLayer(0).getSensors(); + LayerSlice sensor = sensors.get(0); + IMaterial sensorMaterial = MaterialStore.getInstance().get(sensor.getMaterial().getName()); + + ParticleType particleType = ParticlePropertyManager.getParticlePropertyProvider().get(13); + + Hep3Vector p = new BasicHep3Vector(-6.8641, -7.2721, 1.2168e-7); + + double emip = BetheBlochCalculator.computeBetheBloch(sensorMaterial, p, particleType.getMass(), particleType.getCharge(), sensor.getThickness()); + + // Set MIP Energy from Bethe Bloche. + calorimeter.setAttribute("mipEnergy", xfrac.format(emip)); + + // Set defaults for CalCalib parameters. + calorimeter.setAttribute("mipSigma", "0"); + calorimeter.setAttribute("mipCut", "0"); + calorimeter.setAttribute("timeCut", xfrac.format(Double.MAX_VALUE)); + } + + double totalX0 = 0; + + for (int i = 0; i < layers.getNumberOfLayers(); i++) + { + //System.out.println(" layer " + i); + Layer layer = layers.getLayer(i); + + Element layerElem = new Element("layer"); + layersElem.addContent(layerElem); + + // Set radiation and interaction lengths. + double intLen = 0; + double radLen = 0; + for (int j = 0; j < layer.getNumberOfSlices(); j++) + { + LayerSlice slice = layer.getSlice(j); + //System.out.println(" slice " + j + " " + slice.getMaterial().getName()); + double x0 = slice.getMaterial().getRadiationLength(); + //System.out.println(" x0_mat_D="+x0); + //System.out.println(" x0_mat="+slice.getMaterial().getRadiationLength()); + radLen += slice.getThickness() / (x0*10); + //System.out.println(" radLen="+radLen); + + double lambda = slice.getMaterial().getNuclearInteractionLength(); + intLen += slice.getThickness() / (lambda*10); + } + //System.out.println(" x0_lyr_tot=" + radLen); + + totalX0 += radLen; + + //System.out.println(" layer " + i + " " + radLen); + + layerElem.setAttribute("radLen", xlen.format(radLen)); + layerElem.setAttribute("intLen", xlen.format(intLen)); + + // Set distance to IP. + double layerD2 = layerD + layer.getThicknessToSensitiveMid(); + layerElem.setAttribute("distanceToIp", xthick.format(layerD2)); + + // Set cell thickness. + layerElem.setAttribute("cellThickness", xthick.format(layer.getThickness())); + + // Set EM and HAD sampling fractions from + // CalorimeterCalibration conditions, if present. + if (haveCalCalib) + { + SamplingLayerRange layerRange = subdetectorCalorimeterConditions.getSamplingLayerRange(i); + if (calType == EM_BARREL || calType == EM_ENDCAP) + { + layerElem.setAttribute("samplingFraction", xfrac.format(layerRange.getEMSampling())); + } + if (calType == HAD_BARREL || calType == HAD_ENDCAP) + { + layerElem.setAttribute("samplingFraction", xfrac.format(layerRange.getHADSampling())); + } + if (calType == MUON_BARREL || calType == MUON_ENDCAP) + { + layerElem.setAttribute("samplingFraction", xfrac.format(layerRange.getHADSampling())); + } + layerElem.setAttribute("emSamplingFraction", xfrac.format(layerRange.getEMSampling())); + layerElem.setAttribute("hadSamplingFraction", xfrac.format(layerRange.getHADSampling())); + } + // Set from base SamplingFraction conditions. May throw + // an exception if neither CalorimeterCalibration + // or SamplingFractions conditions exists. + else + { + double samplingFraction = SamplingFractionManager.defaultInstance().getSamplingFraction(subdetector, i); + layerElem.setAttribute("emSamplingFraction", xfrac.format(samplingFraction)); + layerElem.setAttribute("hadSamplingFraction", xfrac.format(samplingFraction)); + } + + // Increment layer distance by thickness of layer. + layerD += layer.getThickness(); + } + + //System.out.println(" X0 Sum = " + totalX0); + } + + // Set digital flag. + try + { + // Set digital attribute from conditions, if present. + ConditionsSet conditions = conditionsManager.getConditions("SamplingFractions/" + subdetector.getName()); + boolean isDigital = conditions.getBoolean("digital"); + calorimeter.setAttribute("digital", String.valueOf(isDigital)); + } + catch (Exception x) + { + calorimeter.setAttribute("digital", "false"); + } + } + } + + // TODO clean up the hard coded assumptions on coil geometry + double coilRadLen = 0; + double coilIntLen = 0; + int coilLayers = 0; + double coilInnerR = 0; + double coilOuterR = 0; + double bfield = 0; + double coilMaxZ = 0; + try + { + MultiLayerTracker c = (MultiLayerTracker) detector.getSubdetector("SolenoidCoilBarrel"); + if (c != null) + { + coilLayers = c.getNumberOfLayers(); + coilInnerR = c.getInnerR()[0]; + coilOuterR = c.getInnerR()[coilLayers-1] + c.getLayerThickness(coilLayers-1); + for (int layern = 0; layern != c.getNumberOfLayers(); layern++) + { + for (LayerSlice slice : c.getLayer(layern).getSlices()) + { + double x0 = slice.getMaterial().getRadiationLength(); + double sliceRadLen = slice.getThickness() / (x0*10); + double lambda = slice.getMaterial().getNuclearInteractionLength(); + double sliceIntLen = slice.getThickness() / (lambda*10); + + coilRadLen += sliceRadLen; + coilIntLen += sliceIntLen; + } + } + //calculate average interaction/radiation length in coil material + coilRadLen = coilRadLen/(coilOuterR-coilInnerR); + coilIntLen = coilIntLen/(coilOuterR-coilInnerR); + } + } + catch (ClassCastException e) + { + throw new RuntimeException(e); + } + try + { + Solenoid s = (Solenoid) detector.getFields().get("GlobalSolenoid"); + if (s != null) + { + bfield = s.getField(new BasicHep3Vector(0, 0, 0)).z(); + coilMaxZ = s.getZMax(); + } + } + catch (ClassCastException e) + { + throw new RuntimeException(e); + } + + Element coil = new Element("coil"); + coil.setAttribute("radLen", xlen.format(coilRadLen)); + coil.setAttribute("intLen", xlen.format(coilIntLen)); + coil.setAttribute("innerR", Double.toString(coilInnerR)); + coil.setAttribute("outerR", Double.toString(coilOuterR)); + coil.setAttribute("z", Double.toString(coilMaxZ)); + coil.setAttribute("bfield", Double.toString(bfield)); + root.addContent(coil); + + Tube tube = (Tube) detector.getTrackingVolume().getLogicalVolume().getSolid(); + Element tracking = new Element("tracking"); + tracking.setAttribute("innerR", Double.toString(tube.getInnerRadius())); + tracking.setAttribute("outerR", Double.toString(tube.getOuterRadius())); + tracking.setAttribute("z", Double.toString(tube.getZHalfLength())); + root.addContent(tracking); + + return outputDoc; } Element makeIdentifierDescription(Subdetector subdet) { - IDDescriptor descr = subdet.getIDDecoder().getIDDescription(); - Element id = new Element("id"); - for (int i = 0, j = descr.fieldCount(); i < j; i++) - { - Element field = new Element("field"); - field.setAttribute("name", descr.fieldName(i)); - field.setAttribute("length", Integer.toString(descr.fieldLength(i))); - field.setAttribute("start", Integer.toString(descr.fieldStart(i))); - field.setAttribute("signed", Boolean.toString(descr.isSigned(i))); - - id.addContent(field); - } - return id; + IDDescriptor descr = subdet.getIDDecoder().getIDDescription(); + Element id = new Element("id"); + for (int i = 0, j = descr.fieldCount(); i < j; i++) + { + Element field = new Element("field"); + field.setAttribute("name", descr.fieldName(i)); + field.setAttribute("length", Integer.toString(descr.fieldLength(i))); + field.setAttribute("start", Integer.toString(descr.fieldStart(i))); + field.setAttribute("signed", Boolean.toString(descr.isSigned(i))); + + id.addContent(field); + } + return id; } - private List<Double> getCellSizes(Subdetector subdetector) + private List<Double> getCellSizes(Subdetector subdetector) { - List<Double> cellSizes = new ArrayList<Double>(); - BaseIDDecoder dec = (BaseIDDecoder) subdetector.getReadout().getIDDecoder(); - if (dec instanceof AbstractCartesianGrid) - { - AbstractCartesianGrid cgrid = (AbstractCartesianGrid) dec; - if (cgrid.getGridSizeX() != 0) - { - cellSizes.add(cgrid.getGridSizeX()); - } - if (cgrid.getGridSizeY() != 0) - { - cellSizes.add(cgrid.getGridSizeY()); - } - if (cgrid.getGridSizeZ() != 0) - { - cellSizes.add(cgrid.getGridSizeZ()); - } - } - if (cellSizes.size() != 2) - throw new RuntimeException("Only 2 cell dimensions are allowed."); - return cellSizes; + List<Double> cellSizes = new ArrayList<Double>(); + BaseIDDecoder dec = (BaseIDDecoder) subdetector.getReadout().getIDDecoder(); + if (dec instanceof AbstractCartesianGrid) + { + AbstractCartesianGrid cgrid = (AbstractCartesianGrid) dec; + if (cgrid.getGridSizeX() != 0) + { + cellSizes.add(cgrid.getGridSizeX()); + } + if (cgrid.getGridSizeY() != 0) + { + cellSizes.add(cgrid.getGridSizeY()); + } + if (cgrid.getGridSizeZ() != 0) + { + cellSizes.add(cgrid.getGridSizeZ()); + } + } + if (cellSizes.size() != 2) + throw new RuntimeException("Only 2 cell dimensions are allowed."); + return cellSizes; } - public String getOutputFormat() + public String getOutputFormat() { - return "pandora"; + return "pandora"; } - public FileFilter getFileFilter() + public FileFilter getFileFilter() { - return new PandoraFileFilter(); + return new PandoraFileFilter(); } - private static class PandoraFileFilter extends FileFilter + private static class PandoraFileFilter extends FileFilter { - public boolean accept(java.io.File file) - { - return file.getName().endsWith(".xml"); - } + public boolean accept(java.io.File file) + { + return file.getName().endsWith(".xml"); + } - public String getDescription() - { - return "Pandora Geometry file (*.xml)"; - } + public String getDescription() + { + return "Pandora Geometry file (*.xml)"; + } } -} + } #endif } DECLARE_APPLY(DD4hepGeometry2PANDORA,create_lcdd); diff --git a/DDCore/src/plugins/StandardPlugins.cpp b/DDCore/src/plugins/StandardPlugins.cpp index 668680b05..d79a11af9 100644 --- a/DDCore/src/plugins/StandardPlugins.cpp +++ b/DDCore/src/plugins/StandardPlugins.cpp @@ -4,7 +4,7 @@ //-------------------------------------------------------------------- // // Standard plugins necessary for nearly everything. -// +// // Author : M.Frank // //==================================================================== @@ -26,16 +26,16 @@ static void* create_lcdd_instance(const char* /* name */) { } DECLARE_CONSTRUCTOR(LCDD_constructor,create_lcdd_instance); -static long display(LCDD& lcdd,int argc,char** argv) { +static long display(LCDD& lcdd, int argc, char** argv) { TGeoManager& mgr = lcdd.manager(); const char* opt = "ogl"; - if ( argc > 0 ) { + if (argc > 0) { opt = argv[0]; } mgr.SetVisLevel(4); mgr.SetVisOption(1); TGeoVolume* vol = mgr.GetTopVolume(); - if ( vol ) { + if (vol) { vol->Draw(opt); return 1; } @@ -43,8 +43,8 @@ static long display(LCDD& lcdd,int argc,char** argv) { } DECLARE_APPLY(DD4hepGeometryDisplay,display); -static long load_compact(LCDD& lcdd,int argc,char** argv) { - for(size_t j=0; j<argc; ++j) { +static long load_compact(LCDD& lcdd, int argc, char** argv) { + for (size_t j = 0; j < argc; ++j) { string input = argv[j]; cout << "Processing compact input file : " << input << endl; lcdd.fromCompact(input); @@ -53,7 +53,7 @@ static long load_compact(LCDD& lcdd,int argc,char** argv) { } DECLARE_APPLY(DD4hepCompactLoader,load_compact); -static long load_xml(LCDD& lcdd,int argc,char** argv) { +static long load_xml(LCDD& lcdd, int argc, char** argv) { string input = argv[0]; cout << "Processing compact input file : " << input << endl; lcdd.fromXML(input); @@ -61,17 +61,17 @@ static long load_xml(LCDD& lcdd,int argc,char** argv) { } DECLARE_APPLY(DD4hepXMLLoader,load_xml); -static long load_volmgr(LCDD& lcdd,int,char**) { +static long load_volmgr(LCDD& lcdd, int, char**) { try { LCDDImp* imp = dynamic_cast<LCDDImp*>(&lcdd); imp->m_volManager = VolumeManager(lcdd, "World", imp->world(), Readout(), VolumeManager::TREE); cout << "++ Volume manager populated and loaded." << endl; } - catch(const exception& e) { - throw runtime_error(string(e.what())+"\n" - "DD4hep: while programming VolumeManager. Are your volIDs correct?"); + catch (const exception& e) { + throw runtime_error(string(e.what()) + "\n" + "DD4hep: while programming VolumeManager. Are your volIDs correct?"); } - catch(...) { + catch (...) { throw runtime_error("UNKNOWN exception while programming VolumeManager. Are your volIDs correct?"); } return 1; -- GitLab