diff --git a/Modules/AlgorithmsExt/include/mitkPointLocator.h b/Modules/AlgorithmsExt/include/mitkPointLocator.h index 47f79e7c9c..2dfc9eeaed 100644 --- a/Modules/AlgorithmsExt/include/mitkPointLocator.h +++ b/Modules/AlgorithmsExt/include/mitkPointLocator.h @@ -1,218 +1,220 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef _MITK_POINT_LOCATOR__H__ #define _MITK_POINT_LOCATOR__H__ #include "MitkAlgorithmsExtExports.h" #include #include "mitkPointSet.h" #include // forward declarations class vtkPointSet; class ANNkd_tree; namespace mitk { /** * Convenience wrapper around ANN to provide fast nearest neighbour searches. * Usage: set your points via SetPoints( vtkPointSet* Points ) or SetPoints(mitk::PointSet*). * Then, you may query the closest point to an arbitrary coordinate by FindClosestPoint(). * There is no further call to update etc. needed. * Currently only calls for 1 nearest neighbour are supported. Feel free to add functions * for K nearest neighbours. * NOTE: At least 1 point must be contained in the point set. */ class MITKALGORITHMSEXT_EXPORT PointLocator : public itk::Object { public: mitkClassMacroItkParent(PointLocator, itk::Object); itkFactorylessNewMacro(Self); itkCloneMacro(Self); typedef int IdType; typedef ScalarType DistanceType; typedef float PixelType; typedef double CoordRepType; typedef itk::DefaultStaticMeshTraits MeshTraits; typedef itk::PointSet ITKPointSet; /** * Sets the point which will be used for nearest-neighbour searches. Note * there must be at least one point in the point set. * @param points the point set containing points for nearest neighbours searches. */ void SetPoints(vtkPointSet *points); /** * Sets the point which will be used for nearest-neighbour searches. Note * there must be at least one point in the point set. * @param points the point set containing points for nearest neighbours searches. */ void SetPoints(mitk::PointSet *points); /** * Sets the point which will be used for nearest-neighbour searches. Note * there must be at least one point in the point set. * @param pointSet the point set containing points for nearest neighbours searches. */ void SetPoints(ITKPointSet *pointSet); /** * Finds the nearest neighbour in the point set previously defined by SetPoints(). * The Id of the point is returned. Please note, that there is no case, in which * no point is found, since as a precondition at least one point has to be contained * in the point set. * @param point the query point, for whom the nearest neighbour will be determined * @returns the id of the nearest neighbour of the given point. The id corresponds to the id * which is given in the original point set. */ IdType FindClosestPoint(const double point[3]); /** * Finds the nearest neighbour in the point set previously defined by SetPoints(). * The Id of the point is returned. Please note, that there is no case, in which * no point is found, since as a precondition at least one point has to be contained * in the point set. * @param x the x coordinated of the query point, for whom the nearest neighbour will be determined * @param y the x coordinated of the query point, for whom the nearest neighbour will be determined * @param z the x coordinated of the query point, for whom the nearest neighbour will be determined * @returns the id of the nearest neighbour of the given point. The id corresponds to the id * which is given in the original point set. */ IdType FindClosestPoint(double x, double y, double z); /** * Finds the nearest neighbour in the point set previously defined by SetPoints(). * The Id of the point is returned. Please note, that there is no case, in which * no point is found, since as a precondition at least one point has to be contained * in the point set. * @param point the query point, for whom the nearest neighbour will be determined * @returns the id of the nearest neighbour of the given point. The id corresponds to the id * which is given in the original point set. */ IdType FindClosestPoint(mitk::PointSet::PointType point); /** * Finds the nearest neighbour in the point set previously defined by SetPoints(). * The minimal distance between this point and the closest point of the point set is returned. * Please note, that there is no case, in which * no point is found, since as a precondition at least one point has to be contained * in the point set. * @param point the query point, for whom the minimal distance will be determined * @returns the distance in world coordinates between the nearest point in point set and the given point */ DistanceType GetMinimalDistance(mitk::PointSet::PointType point); /** * Finds the nearest neighbour in the point set previously defined by SetPoints(). * The Index and minimal distance between this point and the closest point of the point set is returned. * Please note, that there is no case, in which * no point is found, since as a precondition at least one point has to be contained * in the point set. * @param point the query point, for whom the minimal distance will be determined + * @param id + * @param dist * @returns the index of and distance (in world coordinates) between the nearest point in point set and the given * point */ bool FindClosestPointAndDistance(mitk::PointSet::PointType point, IdType *id, DistanceType *dist); protected: // // Definition of a vector of ids // typedef std::vector IdVectorType; // // ANN related typedefs, to prevent ANN from being in the global include path. // Please note, that these line are prone to failure, if the point type in // ANN changes. Please note also, that these typedefs are only used in the header // file. The implementation always refers to the original types // typedef double *MyANNpoint; typedef int MyANNidx; typedef double MyANNdist; typedef MyANNpoint *MyANNpointArray; typedef MyANNidx *MyANNidxArray; typedef MyANNdist *MyANNdistArray; /** * constructor */ PointLocator(); /** * destructor */ ~PointLocator() override; /** * Initializes the ann search tree using previously defined points */ void InitANN(); /** * releases all memory occupied by the ann search tree and internal point set arrays */ void DestroyANN(); /** * Finds the nearest neighbour in the point set previously defined by SetPoints(). * The Id of the point is returned. Please note, that there is no case, in which * no point is found, since as a precondition at least one point has to be contained * in the point set. * @param point the query point, for whom the nearest neighbour will be determined * @returns the id of the nearest neighbour of the given point. The id corresponds to the id * which is given in the original point set. */ IdType FindClosestANNPoint(const MyANNpoint &point); /** * Finds the minimal distance between the given point and a point in the previously defined point set. * The distance is returned. Please note, that there is no case, in which * no distance is found, since as a precondition at least one point has to be contained * in the point set. * @param point the query point, for whom the minimal distance to a point in the previously defined point set will * be determined * @returns the squared distance in world coordinates between the given point and the nearest neighbour. */ DistanceType GetMinimalDistance(const MyANNpoint &point); bool m_SearchTreeInitialized; IdVectorType m_IndexToPointIdContainer; vtkPoints *m_VtkPoints; mitk::PointSet *m_MitkPoints; ITKPointSet *m_ItkPoints; // // ANN related variables // unsigned int m_ANNK; unsigned int m_ANNDimension; double m_ANNEpsilon; MyANNpointArray m_ANNDataPoints; MyANNpoint m_ANNQueryPoint; MyANNidxArray m_ANNPointIndexes; MyANNdistArray m_ANNDistances; ANNkd_tree *m_ANNTree; }; } #endif diff --git a/Modules/BasicImageProcessing/include/mitkMaskCleaningOperation.h b/Modules/BasicImageProcessing/include/mitkMaskCleaningOperation.h index a483146e70..361856b9e1 100644 --- a/Modules/BasicImageProcessing/include/mitkMaskCleaningOperation.h +++ b/Modules/BasicImageProcessing/include/mitkMaskCleaningOperation.h @@ -1,58 +1,58 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkMaskClearningOperation_h #define mitkMaskClearningOperation_h #include #include namespace mitk { /** \brief Executes operations to clean-up Masks. * - * It is assumed that the segmentation is of type + * It is assumed that the segmentation is of type "unsigned short" */ class MITKBASICIMAGEPROCESSING_EXPORT MaskCleaningOperation { public: /** \brief Limits a Mask to a given Range * * Removes all elements of a mask that are not within the given range. If lowerLimitOn is true, all voxels that * cover voxels with an intensity below lowerLimit will be set to 0 in the resulting mask. Similar, all voxels * that cover voxels with an intensity above upperLimit will be set to 0 if upperLimitOn is true. * * Parameter * - mitk::Image::Pointer image : Grey-Scale image * - mitk::Image::Pointer mask : Original mask * - optional: bool lowerLimitOn : If true, voxels below lowerLimit are not masked, default false * - optional: double lowerLimit : Lower Threshold limit, default 0 * - optional: bool upperLimitOn : If true, voxels above upperLimit are not masked, default false * - optional: double upperLimit : Lower Threshold limit, default 1 */ static Image::Pointer RangeBasedMasking(Image::Pointer & image, Image::Pointer & mask, bool lowerLimitOn=false, double lowerLimit=0, bool upperLimitOn=false, double upperLimit=1); /** \brief Removes outlier from a mask * * Removes all elements of a mask that are not within the range \f$ [\mu - 3 \sigma , \mu + 3 \sigma\] \f$ * * Parameter * - mitk::Image::Pointer image : Grey-Scale image * - mitk::Image::Pointer mask : Original mask */ static Image::Pointer MaskOutlierFiltering(Image::Pointer & image, Image::Pointer & mask); }; } #endif // mitkMaskClearningOperation_h diff --git a/Modules/Core/TestingHelper/include/mitkRenderingTestHelper.h b/Modules/Core/TestingHelper/include/mitkRenderingTestHelper.h index 070a3d87d9..ff0ccf657b 100644 --- a/Modules/Core/TestingHelper/include/mitkRenderingTestHelper.h +++ b/Modules/Core/TestingHelper/include/mitkRenderingTestHelper.h @@ -1,212 +1,215 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkRenderingTestHelper_h #define mitkRenderingTestHelper_h #include #include #include #include #include class vtkRenderWindow; class vtkRenderer; namespace mitk { class MITKTESTINGHELPER_EXPORT RenderingTestHelper { public: /** @brief Generate a rendering test helper object including a render window of the size width * height (in pixel). + @param width + @param height @param argc Number of parameters. (here: Images) "Usage: [filename1 filenam2 -V referenceScreenshot (optional -T /directory/to/save/differenceImage)] @param argv Given parameters. If no data is inserted via commandline, you can add data later via AddNodeToDataStorage(). - @param renderingMode The rendering mode. + @param antiAliasing The anti-aliasing mode. **/ RenderingTestHelper( int width, int height, int argc, char *argv[], AntiAliasing antiAliasing = AntiAliasing::None); /** @brief Generate a rendering test helper object including a render window of the size width * height (in * pixel).*/ RenderingTestHelper( int width, int height, AntiAliasing antiAliasing = AntiAliasing::None); /** Default destructor */ ~RenderingTestHelper(); /** @brief Getter for the vtkRenderer. **/ vtkRenderer *GetVtkRenderer(); /** @brief Getter for the vtkRenderWindow which should be used to call vtkRegressionTestImage. **/ vtkRenderWindow *GetVtkRenderWindow(); /** @brief Method can be used to save a screenshot (e.g. reference screenshot as a .png file. @param fileName The filename of the new screenshot (including path). **/ void SaveAsPNG(std::string fileName); /** * @brief SetStopRenderWindow Convenience method to make the renderwindow hold after rendering. Usefull for * debugging. - * @param flag Flag indicating whether the renderwindow should automatically close (false, default) or stay open + * @param automaticallyCloseRenderWindow Flag indicating whether the renderwindow should automatically close (false, default) or stay open * (true). Usefull for debugging. */ void SetAutomaticallyCloseRenderWindow(bool automaticallyCloseRenderWindow); /** @brief This method set the property of the member datastorage + @param propertyKey @param property Set a property for each image in the datastorage m_DataStorage. If you want to set the property for a single data node, use GetDataStorage() and set the property yourself for the destinct node. **/ void SetImageProperty(const char *propertyKey, mitk::BaseProperty *property); /** @brief Set the view direction of the renderwindow (e.g. sagittal, coronal, axial) **/ void SetViewDirection(mitk::SliceNavigationController::ViewDirection viewDirection); /** @brief Reorient the slice (e.g. rotation and translation like the swivel mode). **/ void ReorientSlices(mitk::Point3D origin, mitk::Vector3D rotation); /** @brief Render everything into an mitkRenderWindow. Call SetViewDirection() and SetProperty() before this method. **/ void Render(); /** @brief Returns the datastorage, in order to modify the data inside a rendering test. **/ mitk::DataStorage::Pointer GetDataStorage(); /** * @brief SetMapperID Change between Standard2D and 3D mappers. * @param id Enum mitk::BaseRenderer::StandardMapperSlot which defines the mapper. */ void SetMapperID(mitk::BaseRenderer::StandardMapperSlot id); /** * @brief AddNodeToStorage Add a node to the datastorage and perform a reinit which is necessary for rendering. * @param node The data you want to add. */ void AddNodeToStorage(mitk::DataNode::Pointer node); /** * @brief SetMapperIDToRender3D Convenience method to render in a 3D renderwindow. * @warning Does not add helper objects like the image planes to render images in 3D. */ void SetMapperIDToRender3D(); /** * @brief SetMapperIDToRender2D Convenience method to render in a 2D renderwindow. */ void SetMapperIDToRender2D(); /** * @brief SaveReferenceScreenShot Convenience method to save a reference screen shot. * @param fileName Path/to/save/the/png/file. */ void SaveReferenceScreenShot(std::string fileName); /** * @brief CompareRenderWindowAgainstReference Convenience method to compare the image rendered in the internal renderwindow against a reference screen shot. * Usage of vtkTesting::Test: vtkTesting::Test( argc, argv, vtkRenderWindow, threshold ) Set a vtkRenderWindow containing the desired scene. This is automatically rendered. vtkTesting::Test() automatically searches in argc and argv[] for a path a valid image with -V. If the test failed with the first image (foo.png) it checks if there are images of the form foo_N.png (where N=1,2,3...) and compare against them. This allows for multiple valid images. * @param argc Number of arguments. * @param argv Arguments must(!) contain the term "-V Path/To/Valid/Image.png" * @param threshold Allowed difference between two images. Default = 10.0 and was taken from VTK. * @return True if the images are equal regarding the threshold. False in all other cases. */ bool CompareRenderWindowAgainstReference(int argc, char *argv[], double threshold = 10.0); /** * @brief The ArgcHelperClass class is a convinience class to convert a vector * of strings to the standard c++ argv and argc arguments. This is necessary for * the vtkTesting::Test, since is requires the reference image (and other * optional parameters) via command line. */ class ArgcHelperClass { private: /** * Members for conversion. */ std::vector argv; std::vector> argvec; public: ArgcHelperClass(const std::vector &argstrings) : argv(argstrings.size() + 1), argvec(argstrings.size() + 1) { std::vector cmdArgs; cmdArgs.push_back(mitk::IOUtil::GetProgramPath()); cmdArgs.insert(cmdArgs.end(), argstrings.begin(), argstrings.end()); for (std::size_t i = 0; i < cmdArgs.size(); ++i) { argvec[i].assign(cmdArgs[i].begin(), cmdArgs[i].end()); argvec[i].push_back('\0'); argv[i] = &argvec[i][0]; } } char **GetArgv() { return &argv[0]; } int GetArgc() { return argv.size(); } }; protected: /** * @brief Initialize Internal method to initialize the renderwindow and set the datastorage. * @param width Height of renderwindow. * @param height Width of renderwindow. - * @param renderingMode The rendering mode. + * @param antiAliasing The anti-aliasing mode. */ void Initialize( int width, int height, AntiAliasing antiAliasing = AntiAliasing::None); /** @brief This method tries to load the given file into a member datastorage, in order to render it. - @param fileName The filename of the file to be loaded (including path). + @param filename The filename of the file to be loaded (including path). **/ void AddToStorage(const std::string &filename); /** @brief This method tries to parse the given argv for files (e.g. images) and load them into a member datastorage, in order to render it. @param argc Number of parameters. @param argv Given parameters. **/ void SetInputFileNames(int argc, char *argv[]); mitk::RenderWindow::Pointer m_RenderWindow; //<< Contains the mitkRenderWindow into which the test renders the data mitk::DataStorage::Pointer m_DataStorage; //<< Contains the mitkDataStorage which contains the data to be rendered bool m_AutomaticallyCloseRenderWindow; //<< Flag indicating whether the renderwindow should automatically close (true, // default) or stay open (false). Usefull for debugging. }; } // namespace mitk #endif diff --git a/Modules/Core/include/mitkIMimeTypeProvider.h b/Modules/Core/include/mitkIMimeTypeProvider.h index cbaa27ea5e..a891013803 100644 --- a/Modules/Core/include/mitkIMimeTypeProvider.h +++ b/Modules/Core/include/mitkIMimeTypeProvider.h @@ -1,68 +1,68 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKIMIMETYPEPROVIDER_H #define MITKIMIMETYPEPROVIDER_H #include #include #include #include #include namespace mitk { /** - * @ingroupg IO + * @ingroup IO * @ingroup MicroServices_Interfaces * * @brief The IMimeTypeProvider service interface allows to query all registered * mime types. * * Mime types are added to the system by registering a service object of type * CustomMimeType and the registered mime types can be queried bei either using direct * look-ups in the service registry or calling the methods of this service interface. * * This service interface also allows to infer the mime type of a file on the file * system. The heuristics for infering the actual mime type is implementation specific. * * @note This is a core service * * @sa CustomMimeType * @sa CoreServices::GetMimeTypeProvider() */ struct MITKCORE_EXPORT IMimeTypeProvider { virtual ~IMimeTypeProvider(); virtual std::vector GetMimeTypes() const = 0; virtual std::vector GetMimeTypesForFile(const std::string &filePath) const = 0; virtual std::vector GetMimeTypesForCategory(const std::string &category) const = 0; virtual MimeType GetMimeTypeForName(const std::string &name) const = 0; /** * @brief Get a sorted and unique list of mime-type categories. * @return A sorted, unique list of mime-type categories. */ virtual std::vector GetCategories() const = 0; }; } MITK_DECLARE_SERVICE_INTERFACE(mitk::IMimeTypeProvider, "org.mitk.IMimeTypeProvider") #endif // MITKIMIMETYPEPROVIDER_H diff --git a/Modules/Core/include/mitkIOUtil.h b/Modules/Core/include/mitkIOUtil.h index 4732415513..24f878efa2 100644 --- a/Modules/Core/include/mitkIOUtil.h +++ b/Modules/Core/include/mitkIOUtil.h @@ -1,429 +1,434 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKIOUTIL_H #define MITKIOUTIL_H #include #include #include #include #include #include #include #include #include #include namespace us { class ModuleResource; } namespace mitk { /** * \ingroup IO * * \brief A utility class to load and save data from/to the local file system. * * \see QmitkIOUtil */ class MITKCORE_EXPORT IOUtil { public: /**Struct that containes information regarding the current loading process. (e.g. Path that should be loaded, all found readers for the load path,...). It is set be IOUtil and used to pass information via the option callback in load operations. */ struct MITKCORE_EXPORT LoadInfo { LoadInfo(const std::string &path); std::string m_Path; std::vector m_Output; FileReaderSelector m_ReaderSelector; bool m_Cancel; }; /**Struct that is the base class for option callbacks used in load operations. The callback is used by IOUtil, if more than one suitable reader was found or the a reader containes options that can be set. The callback allows to change option settings and select the reader that should be used (via loadInfo). */ struct MITKCORE_EXPORT ReaderOptionsFunctorBase { virtual bool operator()(LoadInfo &loadInfo) const = 0; }; struct MITKCORE_EXPORT SaveInfo { SaveInfo(const BaseData *baseData, const MimeType &mimeType, const std::string &path); bool operator<(const SaveInfo &other) const; /// The BaseData object to save. const BaseData *m_BaseData; /// Contains a set of IFileWriter objects. FileWriterSelector m_WriterSelector; /// The selected mime-type, used to restrict results from FileWriterSelector. MimeType m_MimeType; /// The path to write the BaseData object to. std::string m_Path; /// Flag indicating if sub-sequent save operations are to be canceled. bool m_Cancel; }; /**Struct that is the base class for option callbacks used in save operations. The callback is used by IOUtil, if more than one suitable writer was found or the a writer containes options that can be set. The callback allows to change option settings and select the writer that should be used (via saveInfo). */ struct MITKCORE_EXPORT WriterOptionsFunctorBase { virtual bool operator()(SaveInfo &saveInfo) const = 0; }; /** * Get the file system path where the running executable is located. * * @return The location of the currently running executable, without the filename. */ static std::string GetProgramPath(); /** * Get the default temporary path. * * @return The default path for temporary data. */ static std::string GetTempPath(); /** * Returns the Directory Seperator for the current OS. * * @return the Directory Seperator for the current OS, i.e. "\\" for Windows and "/" otherwise. */ static char GetDirectorySeparator(); /** * Create and open a temporary file. * * This method generates a unique temporary filename from \c templateName, creates * and opens the file using the output stream \c tmpStream and returns the name of * the newly create file. * * The \c templateName argument must contain six consective 'X' characters ("XXXXXX") * and these are replaced with a string that makes the filename unique. * * The file is created with read and write permissions for owner only. * * @param tmpStream The output stream for writing to the temporary file. * @param templateName An optional template for the filename. * @param path An optional path where the temporary file should be created. Defaults * to the default temp path as returned by GetTempPath(). * @return The filename of the created temporary file. * * @throw mitk::Exception if the temporary file could not be created. */ static std::string CreateTemporaryFile(std::ofstream &tmpStream, const std::string &templateName = "XXXXXX", std::string path = std::string()); /** * Create and open a temporary file. * * This method generates a unique temporary filename from \c templateName, creates * and opens the file using the output stream \c tmpStream and the specified open * mode \c mode and returns the name of the newly create file. The open mode is always - * OR'd with \begin{code}std::ios_base::out | std::ios_base::trunc\end{code}. + * OR'd with std::ios_base::out | std::ios_base::trunc. * * The \c templateName argument must contain six consective 'X' characters ("XXXXXX") * and these are replaced with a string that makes the filename unique. * * The file is created with read and write permissions for owner only. * * @param tmpStream The output stream for writing to the temporary file. * @param mode The open mode for the temporary file stream. * @param templateName An optional template for the filename. * @param path An optional path where the temporary file should be created. Defaults * to the default temp path as returned by GetTempPath(). * @return The filename of the created temporary file. * * @throw mitk::Exception if the temporary file could not be created. */ static std::string CreateTemporaryFile(std::ofstream &tmpStream, std::ios_base::openmode mode, const std::string &templateName = "XXXXXX", std::string path = std::string()); /** * Creates an empty temporary file. * * This method generates a unique temporary filename from \c templateName and creates * this file. * * The file is created with read and write permissions for owner only. * * --- * This version is potentially unsafe because the created temporary file is not kept open * and could be used by another process between calling this method and opening the returned * file path for reading or writing. * --- * * @return The filename of the created temporary file. * @param templateName An optional template for the filename. * @param path An optional path where the temporary file should be created. Defaults * to the default temp path as returned by GetTempPath(). * @throw mitk::Exception if the temporary file could not be created. */ static std::string CreateTemporaryFile(const std::string &templateName = "XXXXXX", std::string path = std::string()); /** * Create a temporary directory. * * This method generates a uniquely named temporary directory from \c templateName. * The last set of six consecutive 'X' characters in \c templateName is replaced * with a string that makes the directory name unique. * * The directory is created with read, write and executable permissions for owner only. * * @param templateName An optional template for the directory name. * @param path An optional path where the temporary directory should be created. Defaults * to the default temp path as returned by GetTempPath(). * @return The filename of the created temporary file. * * @throw mitk::Exception if the temporary directory could not be created. */ static std::string CreateTemporaryDirectory(const std::string &templateName = "XXXXXX", std::string path = std::string()); /** * @brief Load a file into the given DataStorage. * * This method calls Load(const std::vector&, DataStorage&) with a * one-element vector. * * @param path The absolute file name including the file extension. * @param storage A DataStorage object to which the loaded data will be added. * @param optionsCallback Pointer to a callback instance. The callback is used by * the load operation if more the suitable reader was found or the reader has options * that can be set. * @return The set of added DataNode objects. * @throws mitk::Exception if \c path could not be loaded. * * @sa Load(const std::vector&, DataStorage&) */ static DataStorage::SetOfObjects::Pointer Load(const std::string &path, DataStorage &storage, const ReaderOptionsFunctorBase *optionsCallback = nullptr); /** * @brief Load a file into the given DataStorage given user defined IFileReader::Options. * * This method calls Load(const std::vector&, DataStorage&) with a * one-element vector. * * @param path The absolute file name including the file extension. * @param options IFileReader option instance that should be used if selected reader * has options. * @param storage A DataStorage object to which the loaded data will be added. * @return The set of added DataNode objects. * @throws mitk::Exception if \c path could not be loaded. * * @sa Load(const std::vector&, DataStorage&) */ static DataStorage::SetOfObjects::Pointer Load(const std::string &path, const IFileReader::Options &options, DataStorage &storage); /** * @brief Load a file and return the loaded data. * * This method calls Load(const std::vector&) with a * one-element vector. * * @param path The absolute file name including the file extension. * @param optionsCallback Pointer to a callback instance. The callback is used by * the load operation if more the suitable reader was found or the reader has options * that can be set. * @return The set of added DataNode objects. * @throws mitk::Exception if \c path could not be loaded. * * @sa Load(const std::vector&, DataStorage&) */ static std::vector Load(const std::string &path, const ReaderOptionsFunctorBase *optionsCallback = nullptr); template static typename T::Pointer Load(const std::string& path, const ReaderOptionsFunctorBase *optionsCallback = nullptr) { return dynamic_cast(Load(path, optionsCallback).at(0).GetPointer()); } /** * @brief Load a file and return the loaded data. * * This method calls Load(const std::vector&) with a * one-element vector. * * @param path The absolute file name including the file extension. * @param options IFileReader option instance that should be used if selected reader * has options. * @return The set of added DataNode objects. * @throws mitk::Exception if \c path could not be loaded. * * @sa Load(const std::vector&, DataStorage&) */ static std::vector Load(const std::string &path, const IFileReader::Options &options); template static typename T::Pointer Load(const std::string& path, const IFileReader::Options &options) { return dynamic_cast(Load(path, options).at(0).GetPointer()); } /** * @brief Loads a list of file paths into the given DataStorage. * * If an entry in \c paths cannot be loaded, this method will continue to load * the remaining entries into \c storage and throw an exception afterwards. * * @param paths A list of absolute file names including the file extension. * @param storage A DataStorage object to which the loaded data will be added. * @param optionsCallback Pointer to a callback instance. The callback is used by * the load operation if more the suitable reader was found or the reader has options * that can be set. * @return The set of added DataNode objects. * @throws mitk::Exception if an entry in \c paths could not be loaded. */ static DataStorage::SetOfObjects::Pointer Load(const std::vector &paths, DataStorage &storage, const ReaderOptionsFunctorBase *optionsCallback = nullptr); static std::vector Load(const std::vector &paths, const ReaderOptionsFunctorBase *optionsCallback = nullptr); /** * @brief Loads the contents of a us::ModuleResource and returns the corresponding mitk::BaseData * @param usResource a ModuleResource, representing a BaseData object * @param mode Optional parameter to set the openmode of the stream * @return The set of loaded BaseData objects. \c Should contain either one or zero elements, since a resource * stream * respresents one object. * @throws mitk::Exception if no reader was found for the stream. */ static std::vector Load(const us::ModuleResource &usResource, std::ios_base::openmode mode = std::ios_base::in); template static typename T::Pointer Load(const us::ModuleResource &usResource, std::ios_base::openmode mode = std::ios_base::in) { return dynamic_cast(Load(usResource, mode).at(0).GetPointer()); } /** * @brief Save a mitk::BaseData instance. * @param data The data to save. * @param path The path to the image including file name and and optional file extension. * If no extension is set, the default extension and mime-type for the * BaseData type of \c data is used. + * @param setPathProperty * @throws mitk::Exception if no writer for \c data is available or the writer * is not able to write the image. */ static void Save(const mitk::BaseData *data, const std::string &path, bool setPathProperty = false); /** * @brief Save a mitk::BaseData instance. * @param data The data to save. * @param path The path to the image including file name and an optional file extension. * If no extension is set, the default extension and mime-type for the * BaseData type of \c data is used. * @param options The IFileWriter options to use for the selected writer. + * @param setPathProperty * @throws mitk::Exception if no writer for \c data is available or the writer * is not able to write the image. */ static void Save(const mitk::BaseData *data, const std::string &path, const IFileWriter::Options &options, bool setPathProperty = false); /** * @brief Save a mitk::BaseData instance. * @param data The data to save. * @param mimeType The mime-type to use for writing \c data. * @param path The path to the image including file name and an optional file extension. * @param addExtension If \c true, an extension according to the given \c mimeType * is added to \c path if it does not contain one. If \c path already contains * a file name extension, it is not checked for compatibility with \c mimeType. + * @param setPathProperty * * @throws mitk::Exception if no writer for the combination of \c data and \c mimeType is * available or the writer is not able to write the image. */ static void Save(const mitk::BaseData *data, const std::string &mimeType, const std::string &path, bool addExtension = true, bool setPathProperty = false); /** * @brief Save a mitk::BaseData instance. * @param data The data to save. * @param mimeType The mime-type to use for writing \c data. * @param path The path to the image including file name and an optional file extension. * @param options Configuration data for the used IFileWriter instance. * @param addExtension If \c true, an extension according to the given \c mimeType * is added to \c path if it does not contain one. If \c path already contains * a file name extension, it is not checked for compatibility with \c mimeType. + * @param setPathProperty * * @throws mitk::Exception if no writer for the combination of \c data and \c mimeType is * available or the writer is not able to write the image. */ static void Save(const mitk::BaseData *data, const std::string &mimeType, const std::string &path, const mitk::IFileWriter::Options &options, bool addExtension = true, bool setPathProperty = false); /** * @brief Use SaveInfo objects to save BaseData instances. * * This is a low-level method for directly working with SaveInfo objects. Usually, * the Save() methods taking a BaseData object as an argument are more appropriate. * * @param saveInfos A list of SaveInfo objects for saving contained BaseData objects. + * @param setPathProperty * * @see Save(const mitk::BaseData*, const std::string&) */ static void Save(std::vector &saveInfos, bool setPathProperty = false); protected: static std::string Load(std::vector &loadInfos, DataStorage::SetOfObjects *nodeResult, DataStorage *ds, const ReaderOptionsFunctorBase *optionsCallback); static std::string Save(const BaseData *data, const std::string &mimeType, const std::string &path, WriterOptionsFunctorBase *optionsCallback, bool addExtension, bool setPathProperty); static std::string Save(std::vector &saveInfos, WriterOptionsFunctorBase *optionsCallback, bool setPathProperty); private: struct Impl; }; } #endif // MITKIOUTIL_H diff --git a/Modules/Core/include/mitkIPropertyPersistence.h b/Modules/Core/include/mitkIPropertyPersistence.h index a778e87602..50b17a941b 100644 --- a/Modules/Core/include/mitkIPropertyPersistence.h +++ b/Modules/Core/include/mitkIPropertyPersistence.h @@ -1,117 +1,115 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkIPropertyPersistence_h #define mitkIPropertyPersistence_h #include #include namespace mitk { /** \ingroup MicroServices_Interfaces * \brief Interface of property persistence service * * This service allows you to manage persistence info for base data properties. * Persistent properties will be saved if the file format supports custom key value pairs like the .nrrd file - * format.\n + * format.\n * \remark The service supports the use of regular expressions (regex; ECMAscript syntax) * for property names and persistance keys to specifiy persistence rules in a generic way. The getter of the - * interface + * interface * (GetInfo and GetInfoByKey) will always ensure that the return containes no regex, thus name and key in the results - * can directly be used. For details on how the result names and keys are determined, please @TODO - * + * can directly be used. */ class MITKCORE_EXPORT IPropertyPersistence { public: virtual ~IPropertyPersistence(); using InfoResultType = std::list; using MimeTypeNameType = PropertyPersistenceInfo::MimeTypeNameType; /** \brief Add persistence info for a specific base data property. * If there is already a property info instance for the passed * property name and the same info, it won't be added. Info instances * are regarded equal, if the mime types are equal. * You may enforce to overwrite the old equal info for a property name * by the overwrite parameter. * - * \param[in] propertyName Name of the property. * \param[in] info Persistence info of the property. * \param[in] overwrite Overwrite already existing persistence info. * \return True if persistence info was added successfully. */ virtual bool AddInfo(const PropertyPersistenceInfo *info, bool overwrite = false) = 0; /** \brief Get the persistence info for a specific base data property. * \param[in] propertyName Name of the property. * \param[in] allowNameRegEx Indicates if also added info instances with regexs are being checked. * \return Property persistence info or null pointer if no persistence info is available. */ virtual InfoResultType GetInfo(const std::string &propertyName, bool allowNameRegEx = true) const = 0; /** \brief Get the persistence info for a specific base data property and mime type. * * \param[in] propertyName Name of the property. * \param[in] mime Name of the mime type the info is specified for. * \param[in] allowMimeWildCard Indicates if wildcard is allowed. If it is allowed, the method will first try to find * the specified info. * If no info was found but an info exists with the mime type name PropertyPersistenceInfo::ANY_MIMETYPE_NAME(), the * later info will be * returned as fall back option. * \param[in] allowNameRegEx Indicates if also added info instances with regexs are being checked. * \return Property persistence info or null pointer if no persistence info is available. */ virtual InfoResultType GetInfo(const std::string &propertyName, const MimeTypeNameType &mime, bool allowMimeWildCard = false, bool allowNameRegEx = true) const = 0; /** \brief Get the persistence info that will use the specified key. * - * \param[in] propertyName Name of the property. + * \param[in] persistenceKey Name of the property. * \param[in] allowKeyRegEx Indicates if also added info instances with regexs for the key are being checked. * \return Property persistence info or null pointer if no persistence info is available. */ virtual InfoResultType GetInfoByKey(const std::string &persistenceKey, bool allowKeyRegEx = true) const = 0; /** \brief Check if a specific base data property has persistence info. * * \param[in] propertyName Name of the property. * \param[in] allowNameRegEx Indicates if also added info instances with regexs are being checked. * \return True if the property has persistence info, false otherwise. */ virtual bool HasInfo(const std::string &propertyName, bool allowNameRegEx = true) const = 0; /** \brief Remove all persistence info. */ virtual void RemoveAllInfo() = 0; /** \brief Remove persistence info instances of a specific property name/regex. * * \param[in] propertyName Registered name or regex that should be removed. */ virtual void RemoveInfo(const std::string &propertyName) = 0; /** \brief Remove persistence info instances of a specific property name/regex and mime type. * * \param[in] propertyName Registered name or regex that should be removed. * \param[in] mime Name of the mime type. */ virtual void RemoveInfo(const std::string &propertyName, const MimeTypeNameType &mime) = 0; }; } MITK_DECLARE_SERVICE_INTERFACE(mitk::IPropertyPersistence, "org.mitk.IPropertyPersistence") #endif diff --git a/Modules/Core/include/mitkInteractionKeyEvent.h b/Modules/Core/include/mitkInteractionKeyEvent.h index 9625743a51..edf8437fbb 100644 --- a/Modules/Core/include/mitkInteractionKeyEvent.h +++ b/Modules/Core/include/mitkInteractionKeyEvent.h @@ -1,62 +1,59 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKINTERACTIONKEYEVENT_H_ #define MITKINTERACTIONKEYEVENT_H_ #include "itkObject.h" #include "itkObjectFactory.h" #include "mitkBaseRenderer.h" #include "mitkCommon.h" #include "mitkInteractionEvent.h" #include "mitkInteractionEventConst.h" #include "mitkInteractionPositionEvent.h" #include #include /* * Note: A Click with the MiddleButton is to be handled with MousePressEvents */ namespace mitk { - /** - * \class InteractionKeyEvent - * \brief Handles key events. - * Takes a std::string for pressed key or special key description, mitk::ModifierKeys for modifiers - * \ingroup Interaction. - */ - + /** \brief Handles key events + * Takes a std::string for pressed key or special key description, mitk::ModifierKeys for modifiers + * \ingroup Interaction + */ class MITKCORE_EXPORT InteractionKeyEvent : public InteractionEvent { public: mitkClassMacro(InteractionKeyEvent, InteractionEvent) mitkNewMacro3Param(Self, BaseRenderer*, const std::string&, ModifierKeys); bool IsSuperClassOf(const InteractionEvent::Pointer &baseClass) const override; ModifierKeys GetModifiers() const; std::string GetKey() const; protected: InteractionKeyEvent(BaseRenderer *, const std::string &key, ModifierKeys modifiers); ~InteractionKeyEvent() override; bool IsEqual(const InteractionEvent &) const override; private: std::string m_Key; ModifierKeys m_Modifiers; }; } /* namespace mitk */ #endif /* MITKINTERACTIONKEYEVENT_H_ */ diff --git a/Modules/Core/include/mitkMaterial.h b/Modules/Core/include/mitkMaterial.h index cfb2c36e4d..271a6bb2dc 100644 --- a/Modules/Core/include/mitkMaterial.h +++ b/Modules/Core/include/mitkMaterial.h @@ -1,453 +1,453 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef _MITK_MATERIAL_H_ #define _MITK_MATERIAL_H_ #include #include #include #include #include #include #include namespace mitk { /** * Encapsulates 3D visualization properties which are forwarded to vtk for * color mapping. This includes color, specular coefficient and power, opacity * interpolation type (flat, gouraud, phong) and representation (points, * wireframe or surface). * * @see vtkProperty */ class MITKCORE_EXPORT Material : public itk::Object { public: mitkClassMacroItkParent(Material, itk::Object); typedef itk::RGBPixel Color; enum InterpolationType { Flat, Gouraud, Phong }; enum RepresentationType { Points, Wireframe, Surface }; /** * Constructor. Materials are set to the following default values: * Color (0.5, 0.5, 0.5) color coefficient 1.0, specular color (1.0, 1.0, 1.0), * specular coefficient 1.0, specular power 10, opacity 1.0, interpolation * Gouraud, representation Surface. */ static Pointer New() { Pointer smartPtr = new Material(); smartPtr->UnRegister(); return smartPtr; } /** * Constructor. All values besides the given ones are set to defaults as * described in the default constructor * @param color the material color in RGB. Each RGB value should be in the * range [0..1] * @param opacity the opacity of the material. 0.0 means fully transparent * and 1.0 means solid. */ static Pointer New(Color color, double opacity = 1.0f) { Pointer smartPtr = new Material(color, opacity); smartPtr->UnRegister(); return smartPtr; } /** * Constructor. All values besides the given ones are set to defaults as * described in the default constructor * @param red the red component of the materials color (range [0..1]) * @param green the green component of the materials color (range [0..1]) * @param blue the blue component of the materials color (range [0..1]) * @param opacity the opacity of the material. 0.0 means fully transparent * and 1.0 means solid. */ static Pointer New(double red, double green, double blue, double opacity = 1.0f) { Pointer smartPtr = new Material(red, green, blue, opacity); smartPtr->UnRegister(); return smartPtr; } /** * Constructor. All values besides the given ones are set to defaults as * described in the default constructor * @param red the red component of the materials color (range [0..1]) * @param green the green component of the materials color (range [0..1]) * @param blue the blue component of the materials color (range [0..1]) * @param colorCoefficient a scaling factor for the color coefficient which * will be multiplied with each color component (range [0..1]). * @param specularCoefficient controls in combination with the specular power * how shiny the material will appear (range [0..1]). * @param specularPower controls in combination with the specular coefficient * how shiny the material will appear (range [0..inf]). * @param opacity the opacity of the material. 0.0 means fully transparent * and 1.0 means solid. */ static Pointer New(double red, double green, double blue, double colorCoefficient, double specularCoefficient, double specularPower, double opacity) { Pointer smartPtr = new Material(red, green, blue, colorCoefficient, specularCoefficient, specularPower, opacity); smartPtr->UnRegister(); return smartPtr; } /** * Constructor. All values besides the given ones are set to defaults as * described in the default constructor * * @param color the material color in RGB. Each RGB value should be in the * range [0..1] * @param colorCoefficient a scaling factor for the color coefficient which * will be multiplied with each color component (range [0..1]). * @param specularCoefficient controls in combination with the specular power * how shiny the material will appear (range [0..1]). * @param specularPower controls in combination with the specular coefficient * how shiny the material will appear (range [0..inf]). * @param opacity the opacity of the material. 0.0 means fully transparent * and 1.0 means solid. */ static Pointer New( Color color, double colorCoefficient, double specularCoefficient, double specularPower, double opacity) { Pointer smartPtr = new Material(color, colorCoefficient, specularCoefficient, specularPower, opacity); smartPtr->UnRegister(); return smartPtr; } /** * Copy constructor */ mitkNewMacro1Param(Material, const Material &); /** * Copy constructor, provided for convinience. The values are copied from property * and afterwards the values provided for red green blue and opacity are written into the object. */ static Pointer New( const Material &property, double red, double green, double blue, double opacity = 1.0, std::string name = "") { Pointer smartPtr = new Material(property, red, green, blue, opacity, name); smartPtr->UnRegister(); return smartPtr; } virtual bool Assignable(const Material &other) const; virtual Material &operator=(const Material &other); /* Sets the materials color in RGB space. The rgb components have to be * in the range [0..1] * @param color the new color of the material */ virtual void SetColor(Color color); /** * Sets the materials color in RGB space. The rgb components have to be * in the range [0..1] * @param red the red component of the materials color (range [0..1]) * @param green the green component of the materials color (range [0..1]) * @param blue the blue component of the materials color (range [0..1]) */ virtual void SetColor(double red, double green, double blue); /** * Sets a attenuation coefficient for the color. A value of 0 results in * a black object. VAlid range is [0..1] * @param coefficient the color attenuation coefficient */ virtual void SetColorCoefficient(double coefficient); /** * Sets the specular color * @param color the specular color in RGB. Each RGB value should be in the * range [0..1] */ virtual void SetSpecularColor(Color color); /** * Sets the specular color * @param red the red component of the specular color (range [0..1]) * @param green the green component of the specular color (range [0..1]) * @param blue the blue component of the specular color (range [0..1]) */ virtual void SetSpecularColor(double red, double green, double blue); /** * Sets the specular coefficient which controls the shininess of the object * together with the specular power * @param specularCoefficient the new specular coefficient. Valid range * is [0..1] */ virtual void SetSpecularCoefficient(double specularCoefficient); /** * Sets the specular power which controls the shininess of the object * together with the specular coefficient - * @param specularCoefficient the new specular coefficient. Valid range + * @param specularPower the new specular coefficient. Valid range * is [0..inf] */ virtual void SetSpecularPower(double specularPower); /** * Sets the opacity of the material, which controls how transparent the * object appears. Valid range is [0..1], where 0 means fully transparent * and 1 means a solid surface. * @param opacity the new opacity of the material */ virtual void SetOpacity(double opacity); /** * Sets the surface interpolation method of the object rendered using the * given materials. Valid Interopation types are Flat, Gouraud and Phong. * See any computer graphics book for their meaning * @param interpolation the interpolation method used for rendering of * surfaces. */ virtual void SetInterpolation(InterpolationType interpolation); /** * Sets the surface representation method of the object rendered using the * given materials. Valid Interopation types are Points, Wireframe and * Surface. * @param representation the representation method used for rendering of * surfaces. */ virtual void SetRepresentation(RepresentationType representation); /** * Set/Get the width of a Line. The width is expressed in screen units. The default is 1.0. */ virtual void SetLineWidth(float lineWidth); /** * @returns the color of the material */ virtual Color GetColor() const; /** * @returns the color coefficient of the material. Range is [0..1] */ virtual double GetColorCoefficient() const; /** * @returns the specular color of the material in rgb values, which * range from 0 .. 1 */ virtual Color GetSpecularColor() const; /** * @returns the specular coefficient used for rendering. Range is [0..1] */ virtual double GetSpecularCoefficient() const; /** * @returns the specular power. Ranges from 0 to infinity */ virtual double GetSpecularPower() const; /** * @returns the opacity of the material. Ranges from 0 to 1 */ virtual double GetOpacity() const; /** * @returns the interpolation method used for rendering. */ virtual InterpolationType GetInterpolation() const; /** * @returns the representation type used for rendering. */ virtual RepresentationType GetRepresentation() const; /** * @returns the interpolation method used for rendering using the predefined * vtk constants. */ virtual int GetVtkInterpolation() const; /** * @returns the representation type used for rendering using the predefined * vtk constants. */ virtual int GetVtkRepresentation() const; /** * @returns the line width used for wireframe rendering as a fraction of screen units */ virtual float GetLineWidth() const; /** * Fills the current materials with the properties of the * given material. * @param property the materials which should be copied in the * current materials */ virtual void Initialize(const Material &property); /** * comparison operator which uses the member variables for * comparison */ virtual bool operator==(const Material &property) const; /** * Dumps the properties to the out stream out */ void PrintSelf(std::ostream &os, itk::Indent) const override; /** * Sets an optional name which may be associated with the material property * Please note, that this name is NOT forwarded to the data tree node * as the node name */ itkSetMacro(Name, std::string); /** * returns the name associated with the material property */ itkGetConstMacro(Name, std::string); protected: /** * Constructor. Materials are set to the following default values: * Color (0.5, 0.5, 0.5) color coefficient 1.0, specular color (1.0, 1.0, 1.0), * specular coefficient 1.0, specular power 10, opacity 1.0, interpolation * Gouraud, representation Surface. */ Material(); /** * Constructor. All values besides the given ones are set to defaults as * described in the default constructor * @param color the material color in RGB. Each RGB value should be in the * range [0..1] * @param opacity the opacity of the material. 0.0 means fully transparent * and 1.0 means solid. */ Material(Color color, double opacity = 1.0f); /** * Constructor. All values besides the given ones are set to defaults as * described in the default constructor * @param red the red component of the materials color (range [0..1]) * @param green the green component of the materials color (range [0..1]) * @param blue the blue component of the materials color (range [0..1]) * @param opacity the opacity of the material. 0.0 means fully transparent * and 1.0 means solid. */ Material(double red, double green, double blue, double opacity = 1.0f); /** * Constructor. All values besides the given ones are set to defaults as * described in the default constructor * @param red the red component of the materials color (range [0..1]) * @param green the green component of the materials color (range [0..1]) * @param blue the blue component of the materials color (range [0..1]) * @param colorCoefficient a scaling factor for the color coefficient which * will be multiplied with each color component (range [0..1]). * @param specularCoefficient controls in combination with the specular power * how shiny the material will appear (range [0..1]). * @param specularPower controls in combination with the specular coefficient * how shiny the material will appear (range [0..inf]). * @param opacity the opacity of the material. 0.0 means fully transparent * and 1.0 means solid. */ Material(double red, double green, double blue, double colorCoefficient, double specularCoefficient, double specularPower, double opacity); /** * Constructor. All values besides the given ones are set to defaults as * described in the default constructor * * @param color the material color in RGB. Each RGB value should be in the * range [0..1] * @param colorCoefficient a scaling factor for the color coefficient which * will be multiplied with each color component (range [0..1]). * @param specularCoefficient controls in combination with the specular power * how shiny the material will appear (range [0..1]). * @param specularPower controls in combination with the specular coefficient * how shiny the material will appear (range [0..inf]). * @param opacity the opacity of the material. 0.0 means fully transparent * and 1.0 means solid. */ Material(Color color, double colorCoefficient, double specularCoefficient, double specularPower, double opacity); /** * Copy constructor */ Material(const Material &property); /** * Copy constructor, provided for convinience. The values are copied from property * and afterwards the values provided for red green blue and opacity are written into the object. */ Material( const Material &property, double red, double green, double blue, double opacity = 1.0, std::string name = ""); virtual void InitializeStandardValues(); virtual void Update(); std::string m_Name; Color m_Color; Color m_SpecularColor; double m_ColorCoefficient; double m_SpecularCoefficient; double m_SpecularPower; double m_Opacity; float m_LineWidth; InterpolationType m_Interpolation; RepresentationType m_Representation; }; typedef itk::VectorContainer MaterialVectorContainer; } #endif diff --git a/Modules/Core/include/mitkMessage.h b/Modules/Core/include/mitkMessage.h index f610b2a919..f1c4b48617 100644 --- a/Modules/Core/include/mitkMessage.h +++ b/Modules/Core/include/mitkMessage.h @@ -1,708 +1,697 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkMessageHIncluded #define mitkMessageHIncluded #include #include #include /** * Adds a Message<> variable and methods to add/remove message delegates to/from * this variable. */ #define mitkNewMessageMacro(msgHandleObject) \ private: \ ::mitk::Message<> m_##msgHandleObject##Message; \ \ public: \ inline void Add##msgHandleObject##Listener(const ::mitk::MessageAbstractDelegate<> &delegate) \ { \ m_##msgHandleObject##Message += delegate; \ } \ inline void Remove##msgHandleObject##Listener(const ::mitk::MessageAbstractDelegate<> &delegate) \ { \ m_##msgHandleObject##Message -= delegate; \ } #define mitkNewMessageWithReturnMacro(msgHandleObject, returnType) \ private: \ ::mitk::Message m_##msgHandleObject##Message; \ \ public: \ inline void Add##msgHandleObject##Listener(const ::mitk::MessageAbstractDelegate &delegate) \ { \ m_##msgHandleObject##Message += delegate; \ } \ inline void Remove##msgHandleObject##Listener(const ::mitk::MessageAbstractDelegate &delegate) \ { \ m_##msgHandleObject##Message -= delegate; \ } #define mitkNewMessage1Macro(msgHandleObject, type1) \ private: \ ::mitk::Message1 m_##msgHandleObject##Message; \ \ public: \ void Add##msgHandleObject##Listener(const ::mitk::MessageAbstractDelegate1 &delegate) \ { \ m_##msgHandleObject##Message += delegate; \ } \ void Remove##msgHandleObject##Listener(const ::mitk::MessageAbstractDelegate1 &delegate) \ { \ m_##msgHandleObject##Message -= delegate; \ } #define mitkNewMessage2Macro(msgHandleObject, type1, type2) \ private: \ ::mitk::Message2 m_##msgHandleObject##Message; \ \ public: \ void Add##msgHandleObject##Listener(const ::mitk::MessageAbstractDelegate2 &delegate) \ { \ m_##msgHandleObject##Message += delegate; \ } \ void Remove##msgHandleObject##Listener(const ::mitk::MessageAbstractDelegate2 &delegate) \ { \ m_##msgHandleObject##Message -= delegate; \ } namespace mitk { template class MessageAbstractDelegate { public: virtual ~MessageAbstractDelegate() {} virtual A Execute() const = 0; virtual bool operator==(const MessageAbstractDelegate *cmd) const = 0; virtual MessageAbstractDelegate *Clone() const = 0; }; template class MessageAbstractDelegate1 { public: virtual ~MessageAbstractDelegate1() {} virtual A Execute(T t) const = 0; virtual bool operator==(const MessageAbstractDelegate1 *cmd) const = 0; virtual MessageAbstractDelegate1 *Clone() const = 0; }; template class MessageAbstractDelegate2 { public: virtual ~MessageAbstractDelegate2() {} virtual A Execute(T t, U u) const = 0; virtual bool operator==(const MessageAbstractDelegate2 *cmd) const = 0; virtual MessageAbstractDelegate2 *Clone() const = 0; }; template class MessageAbstractDelegate3 { public: virtual ~MessageAbstractDelegate3() {} virtual A Execute(T t, U u, V v) const = 0; virtual bool operator==(const MessageAbstractDelegate3 *cmd) const = 0; virtual MessageAbstractDelegate3 *Clone() const = 0; }; template class MessageAbstractDelegate4 { public: virtual ~MessageAbstractDelegate4() {} virtual A Execute(T t, U u, V v, W w) const = 0; virtual bool operator==(const MessageAbstractDelegate4 *cmd) const = 0; virtual MessageAbstractDelegate4 *Clone() const = 0; }; /** * This class essentially wraps a function pointer with signature * A(R::*function)(). A is the return type of your callback function * and R the type of the class implementing the function. * * Use this class to add a callback function to * messages without parameters. */ template class MessageDelegate : public MessageAbstractDelegate { public: // constructor - takes pointer to an object and pointer to a member and stores // them in two private variables MessageDelegate(R *object, A (R::*memberFunctionPointer)()) : m_Object(object), m_MemberFunctionPointer(memberFunctionPointer) { } ~MessageDelegate() override {} // override function "Call" A Execute() const override { return (m_Object->*m_MemberFunctionPointer)(); // execute member function } bool operator==(const MessageAbstractDelegate *c) const override { const MessageDelegate *cmd = dynamic_cast *>(c); if (!cmd) return false; if ((void *)this->m_Object != (void *)cmd->m_Object) return false; if (this->m_MemberFunctionPointer != cmd->m_MemberFunctionPointer) return false; return true; } MessageAbstractDelegate *Clone() const override { return new MessageDelegate(m_Object, m_MemberFunctionPointer); } private: R *m_Object; // pointer to object A (R::*m_MemberFunctionPointer)(); // pointer to member function }; /** * This class essentially wraps a function pointer with signature * A(R::*function)(T). A is the return type of your callback function, * R the type of the class implementing the function and T the type * of the argument. * * Use this class to add a callback function to * messages with one parameter. * * If you need more parameters, use MessageDelegate2 etc. */ template class MessageDelegate1 : public MessageAbstractDelegate1 { public: // constructor - takes pointer to an object and pointer to a member and stores // them in two private variables MessageDelegate1(R *object, A (R::*memberFunctionPointer)(T)) : m_Object(object), m_MemberFunctionPointer(memberFunctionPointer) { } ~MessageDelegate1() override {} // override function "Call" A Execute(T t) const override { return (m_Object->*m_MemberFunctionPointer)(t); // execute member function } bool operator==(const MessageAbstractDelegate1 *c) const override { const MessageDelegate1 *cmd = dynamic_cast *>(c); if (!cmd) return false; if ((void *)this->m_Object != (void *)cmd->m_Object) return false; if (this->m_MemberFunctionPointer != cmd->m_MemberFunctionPointer) return false; return true; } MessageAbstractDelegate1 *Clone() const override { return new MessageDelegate1(m_Object, m_MemberFunctionPointer); } private: R *m_Object; // pointer to object A (R::*m_MemberFunctionPointer)(T); // pointer to member function }; template class MessageDelegate2 : public MessageAbstractDelegate2 { public: // constructor - takes pointer to an object and pointer to a member and stores // them in two private variables MessageDelegate2(R *object, A (R::*memberFunctionPointer)(T, U)) : m_Object(object), m_MemberFunctionPointer(memberFunctionPointer) { } ~MessageDelegate2() override {} // override function "Call" A Execute(T t, U u) const override { return (m_Object->*m_MemberFunctionPointer)(t, u); // execute member function } bool operator==(const MessageAbstractDelegate2 *c) const override { const MessageDelegate2 *cmd = dynamic_cast *>(c); if (!cmd) return false; if ((void *)this->m_Object != (void *)cmd->m_Object) return false; if (this->m_MemberFunctionPointer != cmd->m_MemberFunctionPointer) return false; return true; } MessageAbstractDelegate2 *Clone() const override { return new MessageDelegate2(m_Object, m_MemberFunctionPointer); } private: R *m_Object; // pointer to object A (R::*m_MemberFunctionPointer)(T, U); // pointer to member function }; template class MessageDelegate3 : public MessageAbstractDelegate3 { public: // constructor - takes pointer to an object and pointer to a member and stores // them in two private variables MessageDelegate3(R *object, A (R::*memberFunctionPointer)(T, U, V)) : m_Object(object), m_MemberFunctionPointer(memberFunctionPointer) { } ~MessageDelegate3() override {} // override function "Call" A Execute(T t, U u, V v) const override { return (m_Object->*m_MemberFunctionPointer)(t, u, v); // execute member function } bool operator==(const MessageAbstractDelegate3 *c) const override { const MessageDelegate3 *cmd = dynamic_cast *>(c); if (!cmd) return false; if ((void *)this->m_Object != (void *)cmd->m_Object) return false; if (this->m_MemberFunctionPointer != cmd->m_MemberFunctionPointer) return false; return true; } MessageAbstractDelegate3 *Clone() const override { return new MessageDelegate3(m_Object, m_MemberFunctionPointer); } private: R *m_Object; // pointer to object A (R::*m_MemberFunctionPointer)(T, U, V); // pointer to member function }; template class MessageDelegate4 : public MessageAbstractDelegate4 { public: // constructor - takes pointer to an object and pointer to a member and stores // them in two private variables MessageDelegate4(R *object, A (R::*memberFunctionPointer)(T, U, V, W)) : m_Object(object), m_MemberFunctionPointer(memberFunctionPointer) { } virtual ~MessageDelegate4() {} // override function "Call" virtual A Execute(T t, U u, V v, W w) const { return (m_Object->*m_MemberFunctionPointer)(t, u, v, w); // execute member function } bool operator==(const MessageAbstractDelegate4 *c) const { const MessageDelegate4 *cmd = dynamic_cast *>(c); if (!cmd) return false; if ((void *)this->m_Object != (void *)cmd->m_Object) return false; if (this->m_MemberFunctionPointer != cmd->m_MemberFunctionPointer) return false; return true; } MessageAbstractDelegate4 *Clone() const { return new MessageDelegate4(m_Object, m_MemberFunctionPointer); } private: R *m_Object; // pointer to object A (R::*m_MemberFunctionPointer)(T, U, V, W); // pointer to member function }; template class MessageBase { public: typedef std::vector ListenerList; virtual ~MessageBase() { for (auto iter = m_Listeners.begin(); iter != m_Listeners.end(); ++iter) { delete *iter; } } MessageBase() {} MessageBase(const MessageBase &o) { for (typename ListenerList::iterator iter = o.m_Listeners.begin(); iter != o.m_Listeners.end(); ++iter) { m_Listeners.push_back((*iter)->Clone()); } } MessageBase &operator=(const MessageBase &o) { MessageBase tmp(o); std::swap(tmp.m_Listeners, this->m_Listeners); return *this; } void AddListener(const AbstractDelegate &delegate) const { AbstractDelegate *msgCmd = delegate.Clone(); m_Mutex.Lock(); for (auto iter = m_Listeners.begin(); iter != m_Listeners.end(); ++iter) { if ((*iter)->operator==(msgCmd)) { delete msgCmd; m_Mutex.Unlock(); return; } } m_Listeners.push_back(msgCmd); m_Mutex.Unlock(); } void operator+=(const AbstractDelegate &delegate) const { this->AddListener(delegate); } void RemoveListener(const AbstractDelegate &delegate) const { m_Mutex.Lock(); for (auto iter = m_Listeners.begin(); iter != m_Listeners.end(); ++iter) { if ((*iter)->operator==(&delegate)) { delete *iter; m_Listeners.erase(iter); m_Mutex.Unlock(); return; } } m_Mutex.Unlock(); } void operator-=(const AbstractDelegate &delegate) const { this->RemoveListener(delegate); } const ListenerList &GetListeners() const { return m_Listeners; } bool HasListeners() const { return !m_Listeners.empty(); } bool IsEmpty() const { return m_Listeners.empty(); } protected: /** * \brief List of listeners. * - * This is declared mutable for a reason: Imagine an object that sends out notifications, e.g. - * - * \code - class Database { - public: - Message Modified; - }; - * \endcode - * - * Now imaginge someone gets a const Database object, because he/she should not write to the + * This is declared mutable for a reason: Imagine an object that sends out notifications and + * someone gets a const Database object, because he/she should not write to the * database. He/she should anyway be able to register for notifications about changes in the database * -- this is why AddListener and RemoveListener are declared const. m_Listeners must be * mutable so that AddListener and RemoveListener can modify it regardless of the object's constness. */ mutable ListenerList m_Listeners; mutable itk::SimpleFastMutexLock m_Mutex; }; /** * \brief Event/message/notification class. * * \sa mitk::BinaryThresholdTool * \sa QmitkBinaryThresholdToolGUI * * This totally ITK, Qt, VTK, whatever toolkit independent class * allows one class to send out messages and another class to * receive these message. This class is templated over the * return type (A) of the callback functions. * There are variations of this class * (Message1, Message2, etc.) for sending * one, two or more parameters along with the messages. * * This is an implementation of the Observer pattern. * * \li There is no guarantee about the order of which observer is notified first. At the moment the observers which * register first will be notified first. * \li Notifications are synchronous, by direct method calls. There is no support for asynchronous messages. * * To conveniently add methods for registering/unregistering observers * to Message variables of your class, you can use the mitkNewMessageMacro * macros. - * - * Here is an example how to use the macros and templates: - * - * \code - * - * // An object to be send around - * class Law - * { - * private: - * std::string m_Description; - * - * public: - * - * Law(const std::string law) : m_Description(law) - * { } - * - * std::string GetDescription() const - * { - * return m_Description; - * } - * }; - * - * // The NewtonMachine will issue specific events - * class NewtonMachine - * { - * mitkNewMessageMacro(AnalysisStarted); - * mitkNewMessage1Macro(AnalysisStopped, bool); - * mitkNewMessage1Macro(LawDiscovered, const Law&); - * - * public: - * - * void StartAnalysis() - * { - * // send the "started" signal - * m_AnalysisStartedMessage(); - * - * // we found a new law of nature by creating one :-) - * Law massLaw("F=ma"); - * m_LawDiscoveredMessage(massLaw); - * } - * - * void StopAnalysis() - * { - * // send the "stop" message with false, indicating - * // that no error occured - * m_AnalysisStoppedMessage(false); - * } - * }; - * - * class Observer - * { - * private: - * - * NewtonMachine* m_Machine; - * - * public: - * - * Observer(NewtonMachine* machine) : m_Machine(machine) - * { - * // Add "observers", i.e. function pointers to the machine - * m_Machine->AddAnalysisStartedListener( - * ::mitk::MessageDelegate(this, &Observer::MachineStarted)); - * m_Machine->AddAnalysisStoppedListener( - * ::mitk::MessageDelegate1(this, &Observer::MachineStopped)); - * m_Machine->AddLawDiscoveredListener( - * ::mitk::MessageDelegate1(this, &Observer::LawDiscovered)); - * } - * - * ~Observer() - * { - * // Always remove your observers when finished - * m_Machine->RemoveAnalysisStartedListener( - * ::mitk::MessagDelegate(this, &Observer::MachineStarted)); - * m_Machine->RemoveAnalysisStoppedListener( - * ::mitk::MessageDelegate1(this, &Observer::MachineStopped)); - * m_Machine->RemoveLawDiscoveredListener( - * ::mitk::MessageDelegate1(this, &Observer::LawDiscovered)); - * } - * - * void MachineStarted() - * { - * std::cout << "Observed machine has started" << std::endl; - * } - * - * void MachineStopped(bool error) - * { - * std::cout << "Observed machine stopped " << (error ? "with an error" : "") << std::endl; - * } - * - * void LawDiscovered(const Law& law) - * { - * std::cout << "New law of nature discovered: " << law.GetDescription() << std::endl; - * } - * }; - * - * NewtonMachine newtonMachine; - * Observer observer(&newtonMachine); - * - * // This will send two events to registered observers - * newtonMachine.StartAnalysis(); - * // This will send one event to registered observers - * newtonMachine.StopAnalysis(); - * - * \endcode - * - * Another example of how to use these message classes can be - * found in the directory Testing, file mitkMessageTest.cpp - * */ template class Message : public MessageBase> { public: typedef MessageBase> Super; typedef typename Super::ListenerList ListenerList; void Send() { ListenerList listeners; { this->m_Mutex.Lock(); listeners.assign(this->m_Listeners.begin(), this->m_Listeners.end()); this->m_Mutex.Unlock(); } for (auto iter = listeners.begin(); iter != listeners.end(); ++iter) { // notify each listener (*iter)->Execute(); } } void operator()() { this->Send(); } }; // message with 1 parameter and return type template class Message1 : public MessageBase> { public: typedef MessageBase> Super; typedef typename Super::ListenerList ListenerList; void Send(T t) { ListenerList listeners; { this->m_Mutex.Lock(); listeners.assign(this->m_Listeners.begin(), this->m_Listeners.end()); this->m_Mutex.Unlock(); } for (auto iter = listeners.begin(); iter != listeners.end(); ++iter) { // notify each listener (*iter)->Execute(t); } } void operator()(T t) { this->Send(t); } }; // message with 2 parameters and return type template class Message2 : public MessageBase> { public: typedef MessageBase> Super; typedef typename Super::ListenerList ListenerList; void Send(T t, U u) { ListenerList listeners; { this->m_Mutex.Lock(); listeners.assign(this->m_Listeners.begin(), this->m_Listeners.end()); this->m_Mutex.Unlock(); } for (auto iter = listeners.begin(); iter != listeners.end(); ++iter) { // notify each listener (*iter)->Execute(t, u); } } void operator()(T t, U u) { this->Send(t, u); } }; // message with 3 parameters and return type template class Message3 : public MessageBase> { public: typedef MessageBase> Super; typedef typename Super::ListenerList ListenerList; void Send(T t, U u, V v) { ListenerList listeners; { this->m_Mutex.Lock(); listeners.assign(this->m_Listeners.begin(), this->m_Listeners.end()); this->m_Mutex.Unlock(); } for (typename ListenerList::iterator iter = listeners.begin(); iter != listeners.end(); ++iter) { // notify each listener (*iter)->Execute(t, u, v); } } void operator()(T t, U u, V v) { this->Send(t, u, v); } }; // message with 4 parameters and return type template class Message4 : public MessageBase> { public: typedef MessageBase> Super; typedef typename Super::ListenerList ListenerList; void Send(T t, U u, V v, W w) { ListenerList listeners; { this->m_Mutex.Lock(); listeners.assign(this->m_Listeners.begin(), this->m_Listeners.end()); this->m_Mutex.Unlock(); } for (typename ListenerList::iterator iter = listeners.begin(); iter != listeners.end(); ++iter) { // notify each listener (*iter)->Execute(t, u, v, w); } } void operator()(T t, U u, V v, W w) { this->Send(t, u, v, w); } }; +/* Here is an example how to use the macros and templates: +* +* // An object to be send around +* class Law +* { +* private: +* std::string m_Description; +* +* public: +* +* Law(const std::string law) : m_Description(law) +* { } +* +* std::string GetDescription() const +* { +* return m_Description; +* } +* }; +* +* // The NewtonMachine will issue specific events +* class NewtonMachine +* { +* mitkNewMessageMacro(AnalysisStarted); +* mitkNewMessage1Macro(AnalysisStopped, bool); +* mitkNewMessage1Macro(LawDiscovered, const Law&); +* +* public: +* +* void StartAnalysis() +* { +* // send the "started" signal +* m_AnalysisStartedMessage(); +* +* // we found a new law of nature by creating one :-) +* Law massLaw("F=ma"); +* m_LawDiscoveredMessage(massLaw); +* } +* +* void StopAnalysis() +* { +* // send the "stop" message with false, indicating +* // that no error occured +* m_AnalysisStoppedMessage(false); +* } +* }; +* +* class Observer +* { +* private: +* +* NewtonMachine* m_Machine; +* +* public: +* +* Observer(NewtonMachine* machine) : m_Machine(machine) +* { +* // Add "observers", i.e. function pointers to the machine +* m_Machine->AddAnalysisStartedListener( +* ::mitk::MessageDelegate(this, &Observer::MachineStarted)); +* m_Machine->AddAnalysisStoppedListener( +* ::mitk::MessageDelegate1(this, &Observer::MachineStopped)); +* m_Machine->AddLawDiscoveredListener( +* ::mitk::MessageDelegate1(this, &Observer::LawDiscovered)); +* } +* +* ~Observer() +* { +* // Always remove your observers when finished +* m_Machine->RemoveAnalysisStartedListener( +* ::mitk::MessagDelegate(this, &Observer::MachineStarted)); +* m_Machine->RemoveAnalysisStoppedListener( +* ::mitk::MessageDelegate1(this, &Observer::MachineStopped)); +* m_Machine->RemoveLawDiscoveredListener( +* ::mitk::MessageDelegate1(this, &Observer::LawDiscovered)); +* } +* +* void MachineStarted() +* { +* std::cout << "Observed machine has started" << std::endl; +* } +* +* void MachineStopped(bool error) +* { +* std::cout << "Observed machine stopped " << (error ? "with an error" : "") << std::endl; +* } +* +* void LawDiscovered(const Law& law) +* { +* std::cout << "New law of nature discovered: " << law.GetDescription() << std::endl; +* } +* }; +* +* NewtonMachine newtonMachine; +* Observer observer(&newtonMachine); +* +* // This will send two events to registered observers +* newtonMachine.StartAnalysis(); +* // This will send one event to registered observers +* newtonMachine.StopAnalysis(); +* +* Another example of how to use these message classes can be +* found in the directory Testing, file mitkMessageTest.cpp +* +*/ + } // namespace #endif diff --git a/Modules/Core/include/mitkPlaneGeometry.h b/Modules/Core/include/mitkPlaneGeometry.h index ad7644a739..f06e23e30d 100644 --- a/Modules/Core/include/mitkPlaneGeometry.h +++ b/Modules/Core/include/mitkPlaneGeometry.h @@ -1,608 +1,614 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ /** * \brief Describes the geometry of a plane object * * Describes a two-dimensional manifold, i.e., to put it simply, * an object that can be described using a 2D coordinate-system. * * PlaneGeometry can map points between 3D world coordinates * (in mm) and the described 2D coordinate-system (in mm) by first projecting * the 3D point onto the 2D manifold and then calculating the 2D-coordinates * (in mm). These 2D-mm-coordinates can be further converted into * 2D-unit-coordinates (e.g., pixels), giving a parameter representation of * the object with parameter values inside a rectangle * (e.g., [0,0]..[width, height]), which is the bounding box (bounding range * in z-direction always [0]..[1]). * * A PlaneGeometry describes the 2D representation within a 3D object (derived from BaseGeometry). For example, * a single CT-image (slice) is 2D in the sense that you can access the * pixels using 2D-coordinates, but is also 3D, as the pixels are really * voxels, thus have an extension (thickness) in the 3rd dimension. * * * Optionally, a reference BaseGeometry can be specified, which usually would * be the geometry associated with the underlying dataset. This is currently * used for calculating the intersection of inclined / rotated planes * (represented as PlaneGeometry) with the bounding box of the associated * BaseGeometry. * * \warning The PlaneGeometry are not necessarily up-to-date and not even * initialized. As described in the previous paragraph, one of the * Generate-/Copy-/UpdateOutputInformation methods have to initialize it. * mitk::BaseData::GetPlaneGeometry() makes sure, that the PlaneGeometry is * up-to-date before returning it (by setting the update extent appropriately * and calling UpdateOutputInformation). * * Rule: everything is in mm (or ms for temporal information) if not * stated otherwise. * \ingroup Geometry */ #ifndef PLANEGEOMETRY_H_HEADER_INCLUDED_C1C68A2C #define PLANEGEOMETRY_H_HEADER_INCLUDED_C1C68A2C #include "mitkBaseGeometry.h" #include "mitkRestorePlanePositionOperation.h" #include #include namespace mitk { template class Line; typedef Line Line3D; class PlaneGeometry; /** \deprecatedSince{2014_10} This class is deprecated. Please use PlaneGeometry instead. */ DEPRECATED(typedef PlaneGeometry Geometry2D); /** * \brief Describes a two-dimensional, rectangular plane * * \ingroup Geometry */ class MITKCORE_EXPORT PlaneGeometry : public BaseGeometry { public: mitkClassMacro(PlaneGeometry, BaseGeometry); /** Method for creation through the object factory. */ itkFactorylessNewMacro(Self); itkCloneMacro(Self); enum PlaneOrientation { Axial, Sagittal, Frontal, // also known as "Coronal" in mitk. None // This defines the PlaneGeometry for the 3D renderWindow which // curiously also needs a PlaneGeometry. This should be reconsidered some time. }; virtual void IndexToWorld(const Point2D &pt_units, Point2D &pt_mm) const; virtual void WorldToIndex(const Point2D &pt_mm, Point2D &pt_units) const; //##Documentation //## @brief Convert (continuous or discrete) index coordinates of a \em vector //## \a vec_units to world coordinates (in mm) //## @deprecated First parameter (Point2D) is not used. If possible, please use void IndexToWorld(const // mitk::Vector2D& vec_units, mitk::Vector2D& vec_mm) const. //## For further information about coordinates types, please see the Geometry documentation virtual void IndexToWorld(const mitk::Point2D &atPt2d_untis, const mitk::Vector2D &vec_units, mitk::Vector2D &vec_mm) const; //##Documentation //## @brief Convert (continuous or discrete) index coordinates of a \em vector //## \a vec_units to world coordinates (in mm) //## For further information about coordinates types, please see the Geometry documentation virtual void IndexToWorld(const mitk::Vector2D &vec_units, mitk::Vector2D &vec_mm) const; //##Documentation //## @brief Convert world coordinates (in mm) of a \em vector //## \a vec_mm to (continuous!) index coordinates. //## @deprecated First parameter (Point2D) is not used. If possible, please use void WorldToIndex(const // mitk::Vector2D& vec_mm, mitk::Vector2D& vec_units) const. //## For further information about coordinates types, please see the Geometry documentation virtual void WorldToIndex(const mitk::Point2D &atPt2d_mm, const mitk::Vector2D &vec_mm, mitk::Vector2D &vec_units) const; //##Documentation //## @brief Convert world coordinates (in mm) of a \em vector //## \a vec_mm to (continuous!) index coordinates. //## For further information about coordinates types, please see the Geometry documentation virtual void WorldToIndex(const mitk::Vector2D &vec_mm, mitk::Vector2D &vec_units) const; /** * \brief Initialize a plane with orientation \a planeorientation * (default: axial) with respect to \a BaseGeometry (default: identity). * Spacing also taken from \a BaseGeometry. * * \warning A former version of this method created a geometry with unit * spacing. For unit spacing use * * \code * // for in-plane unit spacing: * thisgeometry->SetSizeInUnits(thisgeometry->GetExtentInMM(0), * thisgeometry->GetExtentInMM(1)); * // additionally, for unit spacing in normal direction (former version * // did not do this): * thisgeometry->SetExtentInMM(2, 1.0); * \endcode */ virtual void InitializeStandardPlane(const BaseGeometry *geometry3D, PlaneOrientation planeorientation = Axial, ScalarType zPosition = 0, bool frontside = true, bool rotated = false, bool top = true); /** * \brief Initialize a plane with orientation \a planeorientation * (default: axial) with respect to \a BaseGeometry (default: identity). * Spacing also taken from \a BaseGeometry. * + * \param geometry3D * \param top if \a true, create plane at top, otherwise at bottom * (for PlaneOrientation Axial, for other plane locations respectively) + * \param planeorientation + * \param frontside + * \param rotated */ virtual void InitializeStandardPlane(const BaseGeometry *geometry3D, bool top, PlaneOrientation planeorientation = Axial, bool frontside = true, bool rotated = false); /** * \brief Initialize a plane with orientation \a planeorientation * (default: axial) with respect to \a transform (default: identity) * given width and height in units. * * \a Rotated means rotated by 180 degrees (1/2 rotation) within the plane. * Rotation by 90 degrees (1/4 rotation) is not implemented as of now. * * \a Frontside/Backside: * Viewed from below = frontside in the axial case; * (radiologist's view versus neuro-surgeon's view, see: * http://www.itk.org/Wiki/images/e/ed/DICOM-OrientationDiagram-Radiologist-vs-NeuroSurgeon.png ) * Viewed from front = frontside in the coronal case; * Viewed from left = frontside in the sagittal case. * * \a Cave/Caution: Currently only RPI, LAI, LPS and RAS in the three standard planes are covered, * i.e. 12 cases of 144: 3 standard planes * 48 coordinate orientations = 144 cases. */ virtual void InitializeStandardPlane(ScalarType width, ScalarType height, const AffineTransform3D *transform = nullptr, PlaneOrientation planeorientation = Axial, ScalarType zPosition = 0, bool frontside = true, bool rotated = false, bool top = true); /** * \brief Initialize plane with orientation \a planeorientation * (default: axial) given width, height and spacing. * */ virtual void InitializeStandardPlane(ScalarType width, ScalarType height, const Vector3D &spacing, PlaneOrientation planeorientation = Axial, ScalarType zPosition = 0, bool frontside = true, bool rotated = false, bool top = true); /** * \brief Initialize plane by width and height in pixels, right-/down-vector * (itk) to describe orientation in world-space (vectors will be normalized) * and spacing (default: 1.0 mm in all directions). * * The vectors are normalized and multiplied by the respective spacing before * they are set in the matrix. * * This overloaded version of InitializeStandardPlane() creates only righthanded * coordinate orientations, unless spacing contains 1 or 3 negative entries. * */ virtual void InitializeStandardPlane(ScalarType width, ScalarType height, const Vector3D &rightVector, const Vector3D &downVector, const Vector3D *spacing = nullptr); /** * \brief Initialize plane by width and height in pixels, * right-/down-vector (vnl) to describe orientation in world-space (vectors * will be normalized) and spacing (default: 1.0 mm in all directions). * * The vectors are normalized and multiplied by the respective spacing * before they are set in the matrix. * * This overloaded version of InitializeStandardPlane() creates only righthanded * coordinate orientations, unless spacing contains 1 or 3 negative entries. * */ virtual void InitializeStandardPlane(ScalarType width, ScalarType height, const VnlVector &rightVector, const VnlVector &downVector, const Vector3D *spacing = nullptr); /** * \brief Initialize plane by right-/down-vector (itk) and spacing * (default: 1.0 mm in all directions). * * The length of the right-/-down-vector is used as width/height in units, * respectively. Then, the vectors are normalized and multiplied by the * respective spacing before they are set in the matrix. */ virtual void InitializeStandardPlane(const Vector3D &rightVector, const Vector3D &downVector, const Vector3D *spacing = nullptr); /** * \brief Initialize plane by right-/down-vector (vnl) and spacing * (default: 1.0 mm in all directions). * * The length of the right-/-down-vector is used as width/height in units, * respectively. Then, the vectors are normalized and multiplied by the * respective spacing before they are set in the matrix. */ virtual void InitializeStandardPlane(const VnlVector &rightVector, const VnlVector &downVector, const Vector3D *spacing = nullptr); /** * \brief Initialize plane by origin and normal (size is 1.0 mm in * all directions, direction of right-/down-vector valid but * undefined). * \warning This function can only produce righthanded coordinate orientation, not lefthanded. */ virtual void InitializePlane(const Point3D &origin, const Vector3D &normal); /** * \brief Initialize plane by right-/down-vector. * * \warning The vectors are set into the matrix as they are, * \em without normalization! * This function creates a righthanded IndexToWorldTransform, * only a negative thickness could still make it lefthanded. */ void SetMatrixByVectors(const VnlVector &rightVector, const VnlVector &downVector, ScalarType thickness = 1.0); /** * \brief Check if matrix is a rotation matrix: * - determinant is 1? * - R*R^T is ID? * Output warning otherwise. */ static bool CheckRotationMatrix(AffineTransform3D *transform, double epsilon=mitk::eps); /** * \brief Normal of the plane * */ Vector3D GetNormal() const; /** * \brief Normal of the plane as VnlVector * */ VnlVector GetNormalVnl() const; virtual ScalarType SignedDistance(const Point3D &pt3d_mm) const; /** * \brief Calculates, whether a point is below or above the plane. There are two different *calculation methods, with or without consideration of the bounding box. */ virtual bool IsAbove(const Point3D &pt3d_mm, bool considerBoundingBox = false) const; /** * \brief Distance of the point from the plane * (bounding-box \em not considered) * */ ScalarType DistanceFromPlane(const Point3D &pt3d_mm) const; /** * \brief Signed distance of the point from the plane * (bounding-box \em not considered) * * > 0 : point is in the direction of the direction vector. */ inline ScalarType SignedDistanceFromPlane(const Point3D &pt3d_mm) const { ScalarType len = GetNormalVnl().two_norm(); if (len == 0) return 0; return (pt3d_mm - GetOrigin()) * GetNormal() / len; } /** * \brief Distance of the plane from another plane * (bounding-box \em not considered) * * Result is 0 if planes are not parallel. */ ScalarType DistanceFromPlane(const PlaneGeometry *plane) const { return fabs(SignedDistanceFromPlane(plane)); } /** * \brief Signed distance of the plane from another plane * (bounding-box \em not considered) * * Result is 0 if planes are not parallel. */ inline ScalarType SignedDistanceFromPlane(const PlaneGeometry *plane) const { if (IsParallel(plane)) { return SignedDistance(plane->GetOrigin()); } return 0; } /** * \brief Calculate the intersecting line of two planes * * \return \a true planes are intersecting * \return \a false planes do not intersect */ bool IntersectionLine(const PlaneGeometry *plane, Line3D &crossline) const; /** * \brief Calculate two points where another plane intersects the border of this plane * * \return number of intersection points (0..2). First interection point (if existing) * is returned in \a lineFrom, second in \a lineTo. */ unsigned int IntersectWithPlane2D(const PlaneGeometry *plane, Point2D &lineFrom, Point2D &lineTo) const; /** * \brief Calculate the angle between two planes * * \return angle in radiants */ double Angle(const PlaneGeometry *plane) const; /** * \brief Calculate the angle between the plane and a line * * \return angle in radiants */ double Angle(const Line3D &line) const; /** * \brief Calculate intersection point between the plane and a line * + * \param line * \param intersectionPoint intersection point * \return \a true if \em unique intersection exists, i.e., if line * is \em not on or parallel to the plane */ bool IntersectionPoint(const Line3D &line, Point3D &intersectionPoint) const; /** * \brief Calculate line parameter of intersection point between the * plane and a line * + * \param line * \param t parameter of line: intersection point is * line.GetPoint()+t*line.GetDirection() * \return \a true if \em unique intersection exists, i.e., if line * is \em not on or parallel to the plane */ bool IntersectionPointParam(const Line3D &line, double &t) const; /** * \brief Returns whether the plane is parallel to another plane * * @return true iff the normal vectors both point to the same or exactly oposit direction */ bool IsParallel(const PlaneGeometry *plane) const; /** * \brief Returns whether the point is on the plane * (bounding-box \em not considered) */ bool IsOnPlane(const Point3D &point) const; /** * \brief Returns whether the line is on the plane * (bounding-box \em not considered) */ bool IsOnPlane(const Line3D &line) const; /** * \brief Returns whether the plane is on the plane * (bounding-box \em not considered) * * @return true iff the normal vector of the planes point to the same or the exactly oposit direction and * the distance of the planes is < eps * */ bool IsOnPlane(const PlaneGeometry *plane) const; /** * \brief Returns the lot from the point to the plane */ Point3D ProjectPointOntoPlane(const Point3D &pt) const; itk::LightObject::Pointer InternalClone() const override; /** Implements operation to re-orient the plane */ void ExecuteOperation(Operation *operation) override; /** * \brief Project a 3D point given in mm (\a pt3d_mm) onto the 2D * geometry. The result is a 2D point in mm (\a pt2d_mm). * * The result is a 2D point in mm (\a pt2d_mm) relative to the upper-left * corner of the geometry. To convert this point into units (e.g., pixels * in case of an image), use WorldToIndex. * \return true projection was possible * \sa Project(const mitk::Point3D &pt3d_mm, mitk::Point3D * &projectedPt3d_mm) */ virtual bool Map(const mitk::Point3D &pt3d_mm, mitk::Point2D &pt2d_mm) const; /** * \brief Converts a 2D point given in mm (\a pt2d_mm) relative to the * upper-left corner of the geometry into the corresponding * world-coordinate (a 3D point in mm, \a pt3d_mm). * * To convert a 2D point given in units (e.g., pixels in case of an * image) into a 2D point given in mm (as required by this method), use * IndexToWorld. */ virtual void Map(const mitk::Point2D &pt2d_mm, mitk::Point3D &pt3d_mm) const; /** * \brief Set the width and height of this 2D-geometry in units by calling * SetBounds. This does \a not change the extent in mm! * * For an image, this is the number of pixels in x-/y-direction. * \note In contrast to calling SetBounds directly, this does \a not change * the extent in mm! */ virtual void SetSizeInUnits(mitk::ScalarType width, mitk::ScalarType height); /** * \brief Project a 3D point given in mm (\a pt3d_mm) onto the 2D * geometry. The result is a 3D point in mm (\a projectedPt3d_mm). * * \return true projection was possible */ virtual bool Project(const mitk::Point3D &pt3d_mm, mitk::Point3D &projectedPt3d_mm) const; /** * \brief Project a 3D vector given in mm (\a vec3d_mm) onto the 2D * geometry. The result is a 2D vector in mm (\a vec2d_mm). * * The result is a 2D vector in mm (\a vec2d_mm) relative to the * upper-left * corner of the geometry. To convert this point into units (e.g., pixels * in case of an image), use WorldToIndex. * \return true projection was possible * \sa Project(const mitk::Vector3D &vec3d_mm, mitk::Vector3D * &projectedVec3d_mm) */ virtual bool Map(const mitk::Point3D &atPt3d_mm, const mitk::Vector3D &vec3d_mm, mitk::Vector2D &vec2d_mm) const; /** * \brief Converts a 2D vector given in mm (\a vec2d_mm) relative to the * upper-left corner of the geometry into the corresponding * world-coordinate (a 3D vector in mm, \a vec3d_mm). * * To convert a 2D vector given in units (e.g., pixels in case of an * image) into a 2D vector given in mm (as required by this method), use * IndexToWorld. */ virtual void Map(const mitk::Point2D &atPt2d_mm, const mitk::Vector2D &vec2d_mm, mitk::Vector3D &vec3d_mm) const; /** * \brief Project a 3D vector given in mm (\a vec3d_mm) onto the 2D * geometry. The result is a 3D vector in mm (\a projectedVec3d_mm). * * DEPRECATED. Use Project(vector,vector) instead * * \return true projection was possible */ virtual bool Project(const mitk::Point3D &atPt3d_mm, const mitk::Vector3D &vec3d_mm, mitk::Vector3D &projectedVec3d_mm) const; /** * \brief Project a 3D vector given in mm (\a vec3d_mm) onto the 2D * geometry. The result is a 3D vector in mm (\a projectedVec3d_mm). * * \return true projection was possible */ virtual bool Project(const mitk::Vector3D &vec3d_mm, mitk::Vector3D &projectedVec3d_mm) const; /** * \brief Distance of the point from the geometry * (bounding-box \em not considered) * */ inline ScalarType Distance(const Point3D &pt3d_mm) const { return fabs(SignedDistance(pt3d_mm)); } /** * \brief Set the geometrical frame of reference in which this PlaneGeometry * is placed. * * This would usually be the BaseGeometry of the underlying dataset, but * setting it is optional. */ void SetReferenceGeometry(const mitk::BaseGeometry *geometry); /** * \brief Get the geometrical frame of reference for this PlaneGeometry. */ const BaseGeometry *GetReferenceGeometry() const; bool HasReferenceGeometry() const; static std::vector< int > CalculateDominantAxes(mitk::AffineTransform3D::MatrixType::InternalMatrixType& rotation_matrix); protected: PlaneGeometry(); PlaneGeometry(const PlaneGeometry &other); ~PlaneGeometry() override; void PrintSelf(std::ostream &os, itk::Indent indent) const override; const mitk::BaseGeometry *m_ReferenceGeometry; //##Documentation //## @brief PreSetSpacing //## //## These virtual function allows a different beahiour in subclasses. //## Do implement them in every subclass of BaseGeometry. If not needed, use //## {Superclass::PreSetSpacing();}; void PreSetSpacing(const mitk::Vector3D &aSpacing) override { Superclass::PreSetSpacing(aSpacing); }; //##Documentation //## @brief CheckBounds //## //## This function is called in SetBounds. Assertions can be implemented in this function (see PlaneGeometry.cpp). //## If you implement this function in a subclass, make sure, that all classes were your class inherits from //## have an implementation of CheckBounds //## (e.g. inheritance BaseGeometry <- A <- B. Implementation of CheckBounds in class B needs implementation in A as // well!) void CheckBounds(const BoundsArrayType &bounds) override; //##Documentation //## @brief CheckIndexToWorldTransform //## //## This function is called in SetIndexToWorldTransform. Assertions can be implemented in this function (see // PlaneGeometry.cpp). //## In Subclasses of BaseGeometry, implement own conditions or call Superclass::CheckBounds(bounds);. void CheckIndexToWorldTransform(mitk::AffineTransform3D *transform) override; private: /** * \brief Compares plane with another plane: \a true if IsOnPlane * (bounding-box \em not considered) */ virtual bool operator==(const PlaneGeometry *) const { return false; }; /** * \brief Compares plane with another plane: \a false if IsOnPlane * (bounding-box \em not considered) */ virtual bool operator!=(const PlaneGeometry *) const { return false; }; }; } // namespace mitk #endif /* PLANEGEOMETRY_H_HEADER_INCLUDED_C1C68A2C */ diff --git a/Modules/Core/include/mitkPlaneGeometryDataVtkMapper3D.h b/Modules/Core/include/mitkPlaneGeometryDataVtkMapper3D.h index 1420e06c0a..fa7ee89fcd 100644 --- a/Modules/Core/include/mitkPlaneGeometryDataVtkMapper3D.h +++ b/Modules/Core/include/mitkPlaneGeometryDataVtkMapper3D.h @@ -1,221 +1,215 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKGEOMETRY2DDATAVTKMAPPER3D_H_HEADER_INCLUDED_C196C71F #define MITKGEOMETRY2DDATAVTKMAPPER3D_H_HEADER_INCLUDED_C196C71F #include "mitkDataStorage.h" #include "mitkPlaneGeometryDataToSurfaceFilter.h" #include "mitkVtkMapper.h" #include "mitkWeakPointer.h" #include #include #include class vtkActor; class vtkPolyDataMapper; class vtkAssembly; class vtkFeatureEdges; class vtkTubeFilter; class vtkTransformPolyDataFilter; class vtkHedgeHog; namespace mitk { class PlaneGeometryData; class BaseRenderer; class ImageVtkMapper2D; class DataStorage; class PlaneGeometryDataVtkMapper3D; /** \deprecatedSince{2014_10} This class is deprecated. Please use PlaneGeometryDataVTKMapper3D instead. */ DEPRECATED(typedef PlaneGeometryDataVtkMapper3D Geometry2DDataVtkMapper3D); /** * \brief Vtk-based mapper to display a PlaneGeometry in a 3D window * \ingroup Mapper * * Uses a PlaneGeometryDataToSurfaceFilter object to create a vtkPolyData representation of a given PlaneGeometry * instance. * PlaneGeometry may either contain a common flat plane or a curved plane (ThinPlateSplineCurvedGeometry). * * The vtkPolyData object is then decorated by a colored tube on the edges and by image textures if possible * (currently this requires that there is a 2D render window rendering the same geometry as this mapper). * * Properties that influence rendering are: * * - \b "draw edges": (Bool) Toggle display of the tubed frame * - \b "color": (ColorProperty) Color of the tubed frame. * - \b "xresolution": (FloatProperty) Resolution (=number of tiles) in x direction. Only relevant for * ThinPlateSplineCurvedGeometry * - \b "yresolution": (FloatProperty) Resolution (=number of tiles) in y direction. Only relevant for * ThinPlateSplineCurvedGeometry * - \b "draw normals 3D": (BoolProperty) If true, a vtkHedgeHog is used to display normals for the generated surface * object. Useful to distinguish front and back of a plane. Hedgehogs are colored according to "front color" and "back * color" * - \b "color two sides": (BoolProperty) If true, front and back side of the plane are colored differently ("front * color" and "back color") * - \b "invert normals": (BoolProperty) Inverts front/back for display. * - \b "front color": (ColorProperty) Color for front side of the plane * - \b "back color": (ColorProperty) Color for back side of the plane * - \b "material.representation": (BoolProperty) Choose the representation to draw the mesh in (Surface, Wireframe, * Point Cloud) * - \b "surfacegeometry": TODO: Add documentation * - \b "LookupTable": (LookupTableProperty) Set the lookuptable to render with. * * Note: The following properties are set for each image individually, and thus, also influence the rendering of this * mapper: * * - \b "texture interpolation": (BoolProperty) Turn on/off the texture interpolation of each image * - \b "use color": (BoolProperty) Decide whether we want to use the color property or a lookuptable. * - \b "binary": (BoolProperty) Binary image handling: Color the value=1.0 with the color property and make the * background (value=0.0) of the image translucent. * - \b "layer": (IntProperty) Controls what image is considered "on top" of another. In the case that two should * inhabit the same space, higher layer occludes lower layer. * - \b "opacity": (FloatProperty) Set the opacity for each rendered image. * - \b "color": (FloatProperty) Set the color for each rendered image. - * - * The internal filter pipeline which combines a (sometimes deformed) 2D surface - * with a nice frame and image textures is illustrated in the following sketch: - * - * \image html mitkPlaneGeometryDataVtkMapper3D.png "Internal filter pipeline" - * */ class MITKCORE_EXPORT PlaneGeometryDataVtkMapper3D : public VtkMapper { public: mitkClassMacro(PlaneGeometryDataVtkMapper3D, VtkMapper); itkFactorylessNewMacro(Self); itkCloneMacro(Self); /** * Overloaded since the displayed color-frame of the image mustn't be * transformed after generation of poly data, but before (vertex coordinates * only) */ vtkProp *GetVtkProp(mitk::BaseRenderer *renderer) override; void UpdateVtkTransform(mitk::BaseRenderer *renderer) override; /** * \brief Get the PlaneGeometryData to map */ virtual const PlaneGeometryData *GetInput(); /** * \brief All images found when traversing the (sub-) tree starting at * \a iterator which are resliced by an ImageVtkMapper2D will be mapped. * This method is used to set the data storage to traverse. This offers * the possibility to use this mapper for other data storages (not only * the default data storage). */ virtual void SetDataStorageForTexture(mitk::DataStorage *storage); protected: typedef std::multimap LayerSortedActorList; PlaneGeometryDataVtkMapper3D(); ~PlaneGeometryDataVtkMapper3D() override; void GenerateDataForRenderer(BaseRenderer *renderer) override; void ProcessNode(DataNode *node, BaseRenderer *renderer, Surface *surface, LayerSortedActorList &layerSortedActors); void ImageMapperDeletedCallback(itk::Object *caller, const itk::EventObject &event); /** \brief general PropAssembly to hold the entire scene */ vtkAssembly *m_Prop3DAssembly; /** \brief PropAssembly to hold the planes */ vtkAssembly *m_ImageAssembly; PlaneGeometryDataToSurfaceFilter::Pointer m_SurfaceCreator; BoundingBox::Pointer m_SurfaceCreatorBoundingBox; BoundingBox::PointsContainer::Pointer m_SurfaceCreatorPointsContainer; /** \brief Edge extractor for tube-shaped frame */ vtkFeatureEdges *m_Edges; /** \brief Filter to apply object transform to the extracted edges */ vtkTransformPolyDataFilter *m_EdgeTransformer; /** \brief Source to create the tube-shaped frame */ vtkTubeFilter *m_EdgeTuber; /** \brief Mapper for the tube-shaped frame */ vtkPolyDataMapper *m_EdgeMapper; /** \brief Actor for the tube-shaped frame */ vtkActor *m_EdgeActor; /** \brief Mapper for black plane background */ vtkPolyDataMapper *m_BackgroundMapper; /** \brief Actor for black plane background */ vtkActor *m_BackgroundActor; /** \brief Transforms the suface before applying the glyph filter */ vtkTransformPolyDataFilter *m_NormalsTransformer; /** \brief Mapper for normals representation (thin lines) */ vtkPolyDataMapper *m_FrontNormalsMapper; vtkPolyDataMapper *m_BackNormalsMapper; /** \brief Generates lines for surface normals */ vtkHedgeHog *m_FrontHedgeHog; vtkHedgeHog *m_BackHedgeHog; /** \brief Actor to hold the normals arrows */ vtkActor *m_FrontNormalsActor; vtkActor *m_BackNormalsActor; /** Cleans the polyline in order to avoid phantom boundaries */ vtkCleanPolyData *m_Cleaner; /** Internal flag, if actors for normals are already added to m_Prop3DAssembly*/ bool m_NormalsActorAdded; /** \brief The DataStorage defines which part of the data tree is traversed for renderering. */ mitk::WeakPointer m_DataStorage; class MITKCORE_EXPORT ActorInfo { public: vtkActor *m_Actor; // we do not need a smart-pointer, because we delete our // connection, when the referenced mapper is destroyed itk::Object *m_Sender; unsigned long m_ObserverID; void Initialize(vtkActor *actor, itk::Object *sender, itk::Command *command); ActorInfo(); ~ActorInfo(); }; /** \brief List holding the vtkActor to map the image into 3D for each * ImageMapper */ typedef std::map ActorList; ActorList m_ImageActors; // responsiblity to remove the observer upon its destruction typedef itk::MemberCommand MemberCommandType; MemberCommandType::Pointer m_ImageMapperDeletedCommand; }; } // namespace mitk #endif /* MITKGEOMETRY2DDATAVTKMAPPER3D_H_HEADER_INCLUDED_C196C71F */ diff --git a/Modules/Core/include/mitkPointOperation.h b/Modules/Core/include/mitkPointOperation.h index 49461abe01..446141d852 100755 --- a/Modules/Core/include/mitkPointOperation.h +++ b/Modules/Core/include/mitkPointOperation.h @@ -1,86 +1,84 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKPOINTOPERATION_H #define MITKPOINTOPERATION_H #include "mitkNumericTypes.h" #include "mitkOperation.h" #include namespace mitk { - //##Documentation - //## @brief Operation that handles all actions on one Point. - //## - //## Stores everything for Adding, Moving and Deleting a Point. - //## @ingroup Undo + /** @brief Operation that handles all actions on one Point. + * Stores everything for Adding, Moving and Deleting a Point. + * @ingroup Undo + */ class MITKCORE_EXPORT PointOperation : public Operation { public: - //##Documentation - //##@brief Operation that handles all actions on one Point. - //## - //## @param operationType is the type of the operation (see mitkOperation.h; e.g. move or add; Information for - // StateMachine::ExecuteOperation()); - //## @param point is the information of the point to add or is the information to change a point into - //## @param index is e.g. the position in a list which describes the element to change + /** @brief Operation that handles all actions on one Point. + * @param operationType is the type of the operation (see mitkOperation.h; e.g. move or add; Information for StateMachine::ExecuteOperation()); + * @param point is the information of the point to add or is the information to change a point into + * @param index is e.g. the position in a list which describes the element to change + * @param selected + * @param type + */ PointOperation(OperationType operationType, Point3D point, int index = -1, bool selected = true, PointSpecificationType type = PTUNDEFINED); - //##Documentation - //##@brief Operation that handles all actions on one Point. - //## - //## @param operationType is the type of the operation (see mitkOperation.h; e.g. move or add; Information for - // StateMachine::ExecuteOperation()); - //## @param point is the information of the point to add or is the information to change a point into - //## @param index is e.g. the position in a list which describes the element to change + /** @brief Operation that handles all actions on one Point. + * @param operationType is the type of the operation (see mitkOperation.h; e.g. move or add; Information for StateMachine::ExecuteOperation()); + * @param timeInMS + * @param point is the information of the point to add or is the information to change a point into + * @param index is e.g. the position in a list which describes the element to change + * @param selected + * @param type + */ PointOperation(OperationType operationType, ScalarType timeInMS, Point3D point, int index = -1, bool selected = true, PointSpecificationType type = PTUNDEFINED); ~PointOperation() override; Point3D GetPoint(); int GetIndex(); bool GetSelected(); PointSpecificationType GetPointType(); ScalarType GetTimeInMS() const; private: Point3D m_Point; - //##Documentation - //##@brief to declare an index where to store the point in data + /** @brief to declare an index where to store the point in data */ int m_Index; // to declare weather the point is selected or deselected bool m_Selected; - //##Documentation - //##@brief to describe the type of the point. See enum PointSpecification for different types + /** @brief to describe the type of the point. See enum PointSpecification for different types */ PointSpecificationType m_Type; ScalarType m_TimeInMS; }; } // namespace mitk #endif /* MITKPOINTOPERATION_H*/ diff --git a/Modules/Core/include/mitkPointSet.h b/Modules/Core/include/mitkPointSet.h index 2d35bc88dd..99383bfea8 100755 --- a/Modules/Core/include/mitkPointSet.h +++ b/Modules/Core/include/mitkPointSet.h @@ -1,351 +1,352 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKPointSet_H_HEADER_INCLUDED #define MITKPointSet_H_HEADER_INCLUDED #include "mitkBaseData.h" #include #include namespace mitk { /** * \brief Data structure which stores a set of points. Superclass of * mitk::Mesh. * * 3D points are grouped within a point set; for time resolved usage, one point * set is created and maintained per time step. A point entry consists of the * point coordinates and point data. * * The point data includes a point ID (unique identifier to address this point * within the point set), the selection state of the point and the type of * the point. * * For further information about different point types see * mitk::PointSpecificationType in mitkVector.h. * * Inserting a point is accompanied by an event, containing an index. The new * point is inserted into the list at the specified position. At the same time * an internal ID is generated and stored for the point. Points at specific time * steps are accessed by specifying the time step number (which defaults to 0). * * The points of itk::PointSet stores the points in a pointContainer * (MapContainer). The points are best accessed by using a ConstIterator (as * defined in MapContainer); avoid access via index. * * The class internally uses an itk::Mesh for each time step, because * mitk::Mesh is derived from mitk::PointSet and needs the itk::Mesh structure * which is also derived from itk::PointSet. Thus several typedefs which seem * to be in wrong place, are declared here (for example SelectedLinesType). * * \section mitkPointSetDisplayOptions * * The default mappers for this data structure are mitk::PointSetGLMapper2D and * mitk::PointSetVtkMapper3D. See these classes for display options which can * can be set via properties. * * \section Events * * PointSet issues the following events, for which observers can register * (the below events are grouped into a class hierarchy as indicated by * identation level; e.g. PointSetSizeChangeEvent comprises PointSetAddEvent * and PointSetRemoveEvent): * * * PointSetEvent subsumes all PointSet events * PointSetMoveEvent issued when a point of the PointSet is moved * PointSetSizeChangeEvent subsumes add and remove events * PointSetAddEvent issued when a point is added to the PointSet * PointSetRemoveEvent issued when a point is removed from the PointSet * * \ingroup PSIO * \ingroup Data */ class MITKCORE_EXPORT PointSet : public BaseData { public: mitkClassMacro(PointSet, BaseData); itkFactorylessNewMacro(Self); itkCloneMacro(Self); typedef mitk::ScalarType CoordinateType; typedef mitk::ScalarType InterpolationWeightType; static const unsigned int PointDimension = 3; static const unsigned int MaxTopologicalDimension = 3; /** * \brief struct for data of a point */ struct MITKCORE_EXPORT PointDataType { unsigned int id; // to give the point a special ID bool selected; // information about if the point is selected mitk::PointSpecificationType pointSpec; // specifies the type of the point bool operator==(const PointDataType &other) const; }; /** * \brief cellDataType, that stores all indexes of the lines, that are * selected e.g.: points A,B and C.Between A and B there is a line with * index 0. If vector of cellData contains 1 and 2, then the lines between * B and C and C and A is selected. */ typedef std::vector SelectedLinesType; typedef SelectedLinesType::iterator SelectedLinesIter; struct CellDataType { // used to set the whole cell on selected bool selected; // indexes of selected lines. 0 is between pointId 0 and 1 SelectedLinesType selectedLines; // is the polygon already finished and closed bool closed; }; typedef itk::DefaultDynamicMeshTraits MeshTraits; typedef itk::Mesh MeshType; typedef MeshType DataType; typedef Point3D PointType; typedef DataType::PointIdentifier PointIdentifier; typedef DataType::PointsContainer PointsContainer; typedef DataType::PointsContainerIterator PointsIterator; typedef DataType::PointsContainer::ConstIterator PointsConstIterator; typedef DataType::PointDataContainer PointDataContainer; typedef DataType::PointDataContainerIterator PointDataIterator; typedef DataType::PointDataContainerIterator PointDataConstIterator; void Expand(unsigned int timeSteps) override; /** \brief executes the given Operation */ void ExecuteOperation(Operation *operation) override; /** \brief returns the current size of the point-list */ virtual int GetSize(unsigned int t = 0) const; virtual unsigned int GetPointSetSeriesSize() const; /** \brief returns the pointset */ virtual DataType::Pointer GetPointSet(int t = 0) const; PointsIterator Begin(int t = 0); PointsConstIterator Begin(int t = 0) const; PointsIterator End(int t = 0); PointsConstIterator End(int t = 0) const; /** * \brief Get an iterator to the max ID element if existent. Return End() otherwise. */ PointsIterator GetMaxId(int t = 0); /** * \brief Get the point with ID id in world coordinates * * check if the ID exists. If it doesn't exist, then return 0,0,0 */ PointType GetPoint(PointIdentifier id, int t = 0) const; /** * \brief Get the point with ID id in world coordinates * * If a point exists for the ID id, the point is returned in the parameter point * and the method returns true. If the ID does not exist, the method returns false */ bool GetPointIfExists(PointIdentifier id, PointType *point, int t = 0) const; /** * \brief Set the given point in world coordinate system into the itkPointSet. */ void SetPoint(PointIdentifier id, PointType point, int t = 0); /** * \brief Set the given point in world coordinate system with the given PointSpecificationType */ void SetPoint(PointIdentifier id, PointType point, PointSpecificationType spec, int t = 0); /** * \brief Set the given point in world coordinate system into the itkPointSet. */ void InsertPoint(PointIdentifier id, PointType point, int t = 0); /** * \brief Set the given point in world coordinate system with given PointSpecificationType */ void InsertPoint(PointIdentifier id, PointType point, PointSpecificationType spec, int t); /** * \brief Insert the given point in world coordinate system with incremented max id at time step t. */ PointIdentifier InsertPoint(PointType point, int t = 0); /** * \brief Remove point with given id at timestep t, if existent */ bool RemovePointIfExists(PointIdentifier id, int t = 0); /** * \brief Remove max id point at timestep t and return iterator to precedent point */ PointsIterator RemovePointAtEnd(int t = 0); /** * \brief Swap a point at the given position (id) with the upper point (moveUpwards=true) or with the lower point * (moveUpwards=false). * If upper or lower index does not exist false is returned, if swap was successful true. */ bool SwapPointPosition(PointIdentifier id, bool moveUpwards, int t = 0); /** * \brief searches a selected point and returns the id of that point. * If no point is found, then -1 is returned */ virtual int SearchSelectedPoint(int t = 0) const; /** \brief returns true if a point exists at this position */ virtual bool IndexExists(int position, int t = 0) const; /** \brief to get the state selected/unselected of the point on the * position */ virtual bool GetSelectInfo(int position, int t = 0) const; virtual void SetSelectInfo(int position, bool selected, int t = 0); /** \brief to get the type of the point at the position and the moment */ virtual PointSpecificationType GetSpecificationTypeInfo(int position, int t) const; /** \brief returns the number of selected points */ virtual int GetNumberOfSelected(int t = 0) const; /** * \brief searches a point in the list == point +/- distance * * \param point is in world coordinates. * \param distance is in mm. + * \param t * returns -1 if no point is found * or the position in the list of the first match */ int SearchPoint(Point3D point, ScalarType distance, int t = 0) const; bool IsEmptyTimeStep(unsigned int t) const override; // virtual methods, that need to be implemented void UpdateOutputInformation() override; void SetRequestedRegionToLargestPossibleRegion() override; bool RequestedRegionIsOutsideOfTheBufferedRegion() override; bool VerifyRequestedRegion() override; void SetRequestedRegion(const itk::DataObject *data) override; // Method for subclasses virtual void OnPointSetChange(){}; protected: mitkCloneMacro(Self); PointSet(); PointSet(const PointSet &other); ~PointSet() override; void PrintSelf(std::ostream &os, itk::Indent indent) const override; ///< print content of the object to os void ClearData() override; void InitializeEmpty() override; /** \brief swaps point coordinates and point data of the points with identifiers id1 and id2 */ bool SwapPointContents(PointIdentifier id1, PointIdentifier id2, int t = 0); typedef std::vector PointSetSeries; PointSetSeries m_PointSetSeries; DataType::PointsContainer::Pointer m_EmptyPointsContainer; /** * @brief flag to indicate the right time to call SetBounds **/ bool m_CalculateBoundingBox; }; /** * @brief Equal A function comparing two pointsets for beeing identical. * @warning This method is deprecated and will not be available in the future. Use the \a bool mitk::Equal(const * mitk::PointSet& p1, const mitk::PointSet& p2) instead. * * @ingroup MITKTestingAPI * * The function compares the Geometry, the size and all points element-wise. * The parameter eps is a tolarence value for all methods which are internally used for comparion. * * @param rightHandSide Compare this against leftHandSide. * @param leftHandSide Compare this against rightHandSide. * @param eps Tolarence for comparison. You can use mitk::eps in most cases. * @param verbose Flag indicating if the user wants detailed console output or not. * @param checkGeometry if comparing point sets loaded from a file, the geometries might be different and must not be * compared. In all other cases, you should compare the geometries. * @return True, if all subsequent comparisons are true, false otherwise */ DEPRECATED(MITKCORE_EXPORT bool Equal(const mitk::PointSet *leftHandSide, const mitk::PointSet *rightHandSide, mitk::ScalarType eps, bool verbose, bool checkGeometry = true)); /** * @brief Equal A function comparing two pointsets for beeing identical. * * @ingroup MITKTestingAPI * * The function compares the Geometry, the size and all points element-wise. * The parameter eps is a tolarence value for all methods which are internally used for comparion. * * @param rightHandSide Compare this against leftHandSide. * @param leftHandSide Compare this against rightHandSide. * @param eps Tolarence for comparison. You can use mitk::eps in most cases. * @param verbose Flag indicating if the user wants detailed console output or not. * @param checkGeometry if comparing point sets loaded from a file, the geometries might be different and must not be * compared. In all other cases, you should compare the geometries. * @return True, if all subsequent comparisons are true, false otherwise */ MITKCORE_EXPORT bool Equal(const mitk::PointSet &leftHandSide, const mitk::PointSet &rightHandSide, mitk::ScalarType eps, bool verbose, bool checkGeometry = true); itkEventMacro(PointSetEvent, itk::AnyEvent); itkEventMacro(PointSetMoveEvent, PointSetEvent); itkEventMacro(PointSetSizeChangeEvent, PointSetEvent); itkEventMacro(PointSetAddEvent, PointSetSizeChangeEvent); itkEventMacro(PointSetRemoveEvent, PointSetSizeChangeEvent); itkEventMacro(PointSetExtendTimeRangeEvent, PointSetEvent); } // namespace mitk #endif /* MITKPointSet_H_HEADER_INCLUDED */ diff --git a/Modules/Core/include/mitkPointSetDataInteractor.h b/Modules/Core/include/mitkPointSetDataInteractor.h index baaabb77c6..98e156d2b2 100644 --- a/Modules/Core/include/mitkPointSetDataInteractor.h +++ b/Modules/Core/include/mitkPointSetDataInteractor.h @@ -1,186 +1,186 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkPointSetDataInteractor_h_ #define mitkPointSetDataInteractor_h_ #include "itkObject.h" #include "itkObjectFactory.h" #include "itkSmartPointer.h" #include "mitkCommon.h" #include "mitkDataInteractor.h" #include #include namespace mitk { /** * Class PointSetDataInteractor * \brief Implementation of the PointSetInteractor * * Interactor operates on a point set and supports to: * - add points * - remove points * - move single points * - move complete pointset * - select/unselect a point * * in 2d and 3d render windows. * - * \warn If this Interactor is assigned (SetDataNode) an empty mitk::DataNode it creates a point set, + * \warning If this Interactor is assigned (SetDataNode) an empty mitk::DataNode it creates a point set, * changing the point set of the assigned mitk::DataNode after this assignment will cause the mitk::PointSetDataInteractor * to not work properly. So the usage has follow this general scheme: * * \code // Set up interactor m_CurrentInteractor = mitk::PointSetDataInteractor::New(); m_CurrentInteractor->LoadStateMachine("PointSet.xml"); m_CurrentInteractor->SetEventConfig("PointSetConfig.xml"); //Create new PointSet which will receive the interaction input m_TestPointSet = mitk::PointSet::New(); // Add the point set to the mitk::DataNode *before* the DataNode is added to the mitk::PointSetDataInteractor m_TestPointSetNode->SetData(m_TestPointSet); // finally add the mitk::DataNode (which already is added to the mitk::DataStorage) to the mitk::PointSetDataInteractor m_CurrentInteractor->SetDataNode(m_TestPointSetNode); \endcode * * */ // Inherit from DataInteratcor, this provides functionality of a state machine and configurable inputs. class MITKCORE_EXPORT PointSetDataInteractor : public DataInteractor { public: mitkClassMacro(PointSetDataInteractor, DataInteractor); itkFactorylessNewMacro(Self); itkCloneMacro(Self); /** * Sets the maximum distance that is accepted when looking for a point at a certain position using the * GetPointIndexByPosition function. */ void SetAccuracy(float accuracy); /** * @brief SetMaxPoints Sets the maximal number of points for the pointset * Default ist zero, which result in infinite number of allowed points * @param maxNumber */ void SetMaxPoints(unsigned int maxNumber = 0); protected: PointSetDataInteractor(); ~PointSetDataInteractor() override; /** * Here actions strings from the loaded state machine pattern are mapped to functions of * the DataInteractor. These functions are called when an action from the state machine pattern is executed. */ void ConnectActionsAndFunctions() override; /** * This function is called when a DataNode has been set/changed. * It is used to initialize the DataNode, e.g. if no PointSet exists yet it is created * and added to the DataNode. */ void DataNodeChanged() override; /** * \brief Return index in PointSet of the point that is within given accuracy to the provided position. * * Assumes that the DataNode contains a PointSet, if so it iterates over all points * in the DataNode to check if it contains a point near the pointer position. * If a point is found its index-position is returned, else -1 is returned. */ virtual int GetPointIndexByPosition(Point3D position, unsigned int time = 0, float accuracy = -1); virtual bool CheckSelection(const InteractionEvent *interactionEvent); /** Adds a point at the given coordinates. * Every time a point is added it is also checked if the maximal number of points is reached, * and if so an InternalEvent with the signal name "MaxNumberOfPoints" is triggered. */ virtual void AddPoint(StateMachineAction *, InteractionEvent *event); /** Removes point that is selected */ virtual void RemovePoint(StateMachineAction *, InteractionEvent *interactionEvent); /** * Checks if new point is close enough to an old one, * if so, trigger the ClosedContour signal which can be caught by the state machine. */ virtual void IsClosedContour(StateMachineAction *, InteractionEvent *); /** * Moves the currently selected point to the new coodinates. */ virtual void MovePoint(StateMachineAction *, InteractionEvent *); /** * Initializes the movement, stores starting position. */ virtual void InitMove(StateMachineAction *, InteractionEvent *interactionEvent); /** * Is called when a movement is finished, changes back to regular color. */ virtual void FinishMove(StateMachineAction *, InteractionEvent *); /** * Selects a point from the PointSet as currently active. */ virtual void SelectPoint(StateMachineAction *, InteractionEvent *); /** * Unselects a point at the given coordinate. */ virtual void UnSelectPointAtPosition(StateMachineAction *, InteractionEvent *); /** * Unselects all points out of reach. */ virtual void UnSelectAll(StateMachineAction *, InteractionEvent *); /** * @brief UpdatePointSet Updates the member variable that holds the point set, evaluating the time step of the * sender. */ virtual void UpdatePointSet(StateMachineAction *stateMachineAction, InteractionEvent *); /** * Calls for inactivation of the DataInteractor */ virtual void Abort(StateMachineAction *, InteractionEvent *); /** \brief to calculate a direction vector from last point and actual * point */ Point3D m_LastPoint; /** \brief summ-vector for Movement */ Vector3D m_SumVec; // DATA PointSet::Pointer m_PointSet; int m_MaxNumberOfPoints; // maximum of allowed number of points float m_SelectionAccuracy; // accuracy that's needed to select a point // FUNCTIONS void UnselectAll(unsigned int timeStep, ScalarType timeInMs); void SelectPoint(int position, unsigned int timeStep, ScalarType timeInMS); }; } #endif diff --git a/Modules/Core/include/mitkPointSetToPointSetFilter.h b/Modules/Core/include/mitkPointSetToPointSetFilter.h index 1c847c0962..ece8df396c 100644 --- a/Modules/Core/include/mitkPointSetToPointSetFilter.h +++ b/Modules/Core/include/mitkPointSetToPointSetFilter.h @@ -1,84 +1,85 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef _mitkpointsettopointsetfilter_h #define _mitkpointsettopointsetfilter_h #include "mitkPointSetSource.h" #include namespace mitk { /** * @brief Superclass of all classes/algorithms having one or more PointSets * as input and output * @ingroup Process */ class MITKCORE_EXPORT PointSetToPointSetFilter : public PointSetSource { public: mitkClassMacro(PointSetToPointSetFilter, PointSetSource); itkFactorylessNewMacro(Self); itkCloneMacro(Self); typedef mitk::PointSet InputType; typedef mitk::PointSet OutputType; typedef InputType::Pointer InputTypePointer; typedef InputType::ConstPointer InputTypeConstPointer; using itk::ProcessObject::SetInput; /** * Sets the input of this process object * @param input the input */ virtual void SetInput(const InputType *input); /** * Sets the input n'th of this process object * @param idx the number associated with the given input + * @param input */ virtual void SetInput(const unsigned int &idx, const InputType *input); /** * @returns the input tree of the process object */ const InputType *GetInput(void); /** * @param idx the index of the input to return * @returns the input object with the given index */ const InputType *GetInput(const unsigned int &idx); protected: /** * A default constructor */ PointSetToPointSetFilter(); /** * The destructor */ ~PointSetToPointSetFilter() override; private: void operator=(const Self &); // purposely not implemented }; } // end of namespace mitk #endif diff --git a/Modules/Core/include/mitkProgressBar.h b/Modules/Core/include/mitkProgressBar.h index f635a861b6..fbcd793c85 100644 --- a/Modules/Core/include/mitkProgressBar.h +++ b/Modules/Core/include/mitkProgressBar.h @@ -1,79 +1,79 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKPROGRESSBAR_H #define MITKPROGRESSBAR_H #include #include namespace mitk { class ProgressBarImplementation; //##Documentation //## @brief Sending a message to the applications ProgressBar //## //## Holds a GUI dependent ProgressBarImplementation and sends the progress further. //## All mitk-classes use this class to display progress on GUI-ProgressBar. //## The mainapplication has to set the internal held ProgressBarImplementation with SetImplementationInstance(..). //## @ingroup Interaction class MITKCORE_EXPORT ProgressBar : public itk::Object { public: itkTypeMacro(ProgressBar, itk::Object); //##Documentation //## @brief static method to get the GUI dependent ProgressBar-instance //## so the methods for steps to do and progress can be called //## No reference counting, cause of decentral static use! static ProgressBar *GetInstance(); //##Documentation //## @brief Supply a GUI- dependent ProgressBar. Has to be set by the application //## to connect the application dependent subclass of mitkProgressBar void RegisterImplementationInstance(ProgressBarImplementation *implementation); void UnregisterImplementationInstance(ProgressBarImplementation *implementation); //##Documentation //## @brief Adds steps to totalSteps. void AddStepsToDo(unsigned int steps); //##Documentation //## @brief Explicitly reset progress bar. void Reset(); //##Documentation //## @brief Sets the current amount of progress to current progress + steps. - //## @param: steps the number of steps done since last Progress(int steps) call. + //## @param steps the number of steps done since last Progress(int steps) call. void Progress(unsigned int steps = 1); //##Documentation //## @brief Sets whether the current progress value is displayed. void SetPercentageVisible(bool visible); protected: typedef std::vector ProgressBarImplementationsList; typedef ProgressBarImplementationsList::iterator ProgressBarImplementationsListIterator; ProgressBar(); ~ProgressBar() override; ProgressBarImplementationsList m_Implementations; static ProgressBar *m_Instance; }; } // end namespace mitk #endif /* define MITKPROGRESSBAR_H */ diff --git a/Modules/Core/include/mitkPropertyRelationRuleBase.h b/Modules/Core/include/mitkPropertyRelationRuleBase.h index 87cd98e69f..2ea5eadefa 100644 --- a/Modules/Core/include/mitkPropertyRelationRuleBase.h +++ b/Modules/Core/include/mitkPropertyRelationRuleBase.h @@ -1,392 +1,403 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkPropertyRelationRuleBase_h #define mitkPropertyRelationRuleBase_h #include "mitkIPropertyOwner.h" #include "mitkIdentifiable.h" #include "mitkException.h" #include "mitkNodePredicateBase.h" #include "mitkPropertyKeyPath.h" #include #include namespace mitk { /**Base class to standardize/abstract/encapsulate rules and business logic to detect and define (property/data based) relations in MITK. Following important definitions must be regarded when using/implementing/specifing rule classes: - Releations represented by rules are directed relations that point from a source IPropertyOwner (Source) to a destination IPropertyOwner (Destination). - Rule can be abstract (indicated by IsAbstract()) or concrete. Abstract rules cannot be used to connect relations. Abstract rules can only be used to detect/indicate or disconnect relations. Therefore, in contrast to concrete rules, abstract rules can be used to indicate several relations that are established be "derived" rules. See e.g. GenericIDRelationRule: in its abstract state it cannot connect but be used to detect any type of generic ID relation. - A concrete rule ID (rule ID of a concrete rule) always "implements" a concrete relation type. E.g. In DICOM the way to express the source image relation to an input image and to a mask would be nearly the same and only differs by the encoded purpose. One may implement an interim or joined class that manages the mutual stuff, but the registered instances must be one concrete rule for "DICOM source input image" and one concrete rule for "DICOM source mask" and both rules must have distinct rule IDs. - Source may have several relations of a rule to different Destinations. Destination may have several relations of a rule from different Sources. But a specific source destination pair may have only one relation of a specific rule id (concrete rule). A specific source destination pair may however have multiple relations for an abstract rule. - The deletion of a Destination in the storage does not remove the relation implicitly. It becomes a "zombie" relation but it should still be documented, even if the destination is unknown. One has to explicitly disconnect a zombie relation to get rid of it. - Each relation has its own UID (relationUID) that can be used to address it. The basic concept of the rule design is that we have two layers of relation identification: Layer 1 is the ID-layer which uses the IIdentifiable interface and UIDs if available to encode "hard" relations. Layer 2 is the Data-layer which uses the properties of Source and Destination to deduce if there is a relation of the rule type. The ID-layer is completely implemented by this base class. The base class falls back to the Data-layer (implemented by the concrete rule class) if the ID-layer is not sufficient or it is explicitly stated to (only) look at the data layer. Reasons for the introduction of the ID-layer are: 1st, data-defined relations may be weak (several Destinations are possible; e.g. DICOM source images may point to several loaded mitk images). But if explicitly a relation was connected it should be deduceable. 2nd, checks on a UID are faster then unnecessary data deduction. Rules use relation instance identifing (RII) properties in order to manage their relations that are stored in the Source. The RII-properties follow the following naming schema: - "MITK.Relations..[relationUID|destinationUID|ruleID|]" - - : The unique index of the relation for the Source. Used to assign/group the properties to + "MITK.Relations.\.[relationUID|destinationUID|ruleID|\]" + - \: The unique index of the relation for the Source. Used to assign/group the properties to their relation. In the default implementation of this class the instance id is an positive integer (i>0). - relationUID: The UID of the relation. Set by the ID-layer (so by this class) - destinationUID: The UID of the Destination. Set by the ID-layer (so by this class) if Destination implements IIdentifiable. - ruleID: The identifier of the concrete rule that sets the property. Is specified by the derived class and set automaticaly be this base class. - : Information needed by the Data-layer (so derived classes) to find the relationUID */ class MITKCORE_EXPORT PropertyRelationRuleBase : public itk::Object { public: mitkClassMacroItkParent(PropertyRelationRuleBase, itk::Object); itkCloneMacro(Self); itkCreateAnotherMacro(Self); using RuleIDType = std::string; using RelationUIDType = Identifiable::UIDType; using RelationUIDVectorType = std::vector; /** Enum class for different types of relations. */ enum class RelationType { None = 0, /**< Two IPropertyOwner have no relation under the rule.*/ Data = 1, /**< Two IPropertyOwner have a relation, but it is "only" deduced from the Data-layer (so a bit "weaker" as ID). Reasons for the missing ID connection could be that Destintination has not IIdentifiable implemented.*/ ID = 2, /**< Two IPropertyOwner have a relation and are explictly connected via the ID of IIdentifiable of the Destination.*/ Complete = 3 /**< Two IPropertyOwner have a relation and are fully explictly connected (via data layer and ID layer).*/ }; using RelationVectorType = std::vector; /** Returns the generic root path for relation rules ("MITK.Relations").*/ static PropertyKeyPath GetRootKeyPath(); using InstanceIDType = std::string; /** Returns the property key path for a RII property. - * @param propName If not empty a PropertyPath element will added (with the passed value) after the element. + * @param propName If not empty a PropertyPath element will added (with the passed value) after the \ element. * @param instanceID If not empty, the PropertyKeyPath is only for a specific instance. If empty, * it is wildcarded and will match RIIs property of any instance.*/ static PropertyKeyPath GetRIIPropertyKeyPath(const std::string propName, const InstanceIDType& instanceID); /** Returns the property key path for RII RelationUID properties. * @param instanceID If not empty, the PropertyKeyPath is only for a specific instance. If empty, * it is wildcarded and will match RII RelationUIDs property of any instance.*/ static PropertyKeyPath GetRIIRelationUIDPropertyKeyPath(const InstanceIDType& instanceID = ""); /** Returns the property key path for RII RuleID properties. * @param instanceID If not empty, the PropertyKeyPath is only for a specific instance. If empty, * it is wildcarded and will match RII RuleIDs property of any instance.*/ static PropertyKeyPath GetRIIRuleIDPropertyKeyPath(const InstanceIDType& instanceID = ""); /** Returns the property key path for RII DestinationUID properties. * @param instanceID If not empty, the PropertyKeyPath is only for a specific instance. If empty, * it is wildcarded and will match RII DestinationUIDs property of any instance.*/ static PropertyKeyPath GetRIIDestinationUIDPropertyKeyPath(const InstanceIDType& instanceID = ""); /** Returns an ID string that identifies the rule class. @post The returned rule ID must met the preconditions of a PropertyKeyPath element name (see mitk::PropertyKeyPath*/ virtual RuleIDType GetRuleID() const = 0; /** Returns a human readable string that can be used to describe the rule. Does not need to be unique.*/ virtual std::string GetDisplayName() const = 0; /** Returns a human readable string that can be used to describe the role of a source in context of the rule * instance.*/ virtual std::string GetSourceRoleName() const = 0; /** Returns a human readable string that can be used to describe the role of a destionation in context of the rule * instance.*/ virtual std::string GetDestinationRoleName() const = 0; /** Returns if the instance is a abstract rule (true). Default implementation is true. Overwrite and reimplement if another behavior is needed.*/ virtual bool IsAbstract() const; /** This method checks if owner is eligible to be a Source for the rule. The default implementation returns a True for every valid IPropertyProvider (so only a null_ptr results into false). May be reimplement by derived rules if they have requirements on potential Sources).*/ virtual bool IsSourceCandidate(const IPropertyProvider *owner) const; /** This method checks if owner is eligible to be a Destination for the rule. The default implementation returns a True for every valid IPropertyProvider (so only a null_ptr results into false). May be reimplement by derived rules if they have requirements on potential Sources).*/ virtual bool IsDestinationCandidate(const IPropertyProvider *owner) const; /** Returns true if the passed owner is a Source of a relation defined by the rule. @pre owner must be a pointer to a valid IPropertyProvider instance.*/ bool IsSource(const IPropertyProvider *owner) const; /** Returns all relation types of the passed IPropertyOwner instances. @remark Abstract rules may have several relationtypes between the instances (from different supported concrete rules), that cover both ID and Data relations; thus it returns a vector of RelationTypes. @result Vector of all relation types that exist between the given instances. Empty vector equals none relation at all. @pre source must be a pointer to a valid IPropertyProvider instance. @pre destination must be a pointer to a valid IPropertyProvider instance. */ RelationVectorType GetRelationTypes(const IPropertyProvider* source, const IPropertyProvider* destination) const; /** Indicates if passed IPropertyOwner instances have a relation of a certain type. @remark Abstract rules may also indicate RelationType::Complete if there are multiple relations (from different supported concrete rules), that cover both ID and Data relations. + @param source + @param destination @param requiredRelation Defines the type of relation that should be present. None: does not matter which one, as long as at least one is present. Data: Only data layer exclusive connections, ID: Only ID layer exclusive connections. Complete: Only relations that are connected on both layers. @pre source must be a pointer to a valid IPropertyProvider instance. @pre destination must be a pointer to a valid IPropertyProvider instance. */ bool HasRelation(const IPropertyProvider *source, const IPropertyProvider *destination, RelationType requiredRelation = RelationType::None) const; /** Returns a vector of relation UIDs for all relations of this rule instance that are defined for the passed source. @pre source must be a pointer to a valid IPropertyOwner instance. + @param source @param layer Defines the layer the relations must be reflected. None: does not matter which one, as long as at least one is present. Data: Only data layer exclusive connections, ID: Only ID layer exclusive connections. Complete: Only relations that are connected on both layers.*/ RelationUIDVectorType GetExistingRelations(const IPropertyProvider *source, RelationType layer = RelationType::None) const; /** Returns the relation UID(s) for the passed source and destination of this rule instance. If the rule is abstract multiple relation UIDs might be returned. In case of concrete rule only one relation UID. @pre source must be a pointer to a valid IPropertyOwner instance. @pre destination must be a pointer to a valid IPropertyOwner instance.*/ RelationUIDVectorType GetRelationUIDs(const IPropertyProvider *source, const IPropertyProvider *destination) const; /** Returns the relation UID for the passed source and destination of this rule instance. If the passed instances have no relation, no ID can be deduced and an exception will be thrown. If more than one relation is found, also an exception will be thrown. Thus only use this convenience method, if you are sure that one(!) relation UID can exist. @pre source must be a pointer to a valid IPropertyOwner instance. @pre destination must be a pointer to a valid IPropertyOwner instance. @pre Source and destination have one relation; otherwise if no relation exists a NoPropertyRelationException is thrown; if more than one relation exists a default MITK expception is thrown.*/ RelationUIDType GetRelationUID(const IPropertyProvider *source, const IPropertyProvider *destination) const; /**Predicate that can be used to find nodes that qualify as source for that rule (but must not be a source yet). Thus all nodes where IsSourceCandidate() returns true. */ NodePredicateBase::ConstPointer GetSourceCandidateIndicator() const; /**Predicate that can be used to find nodes that qualify as destination for that rule (but must not be a destination yet). Thus all nodes where IsDestinationCandidate() returns true. */ NodePredicateBase::ConstPointer GetDestinationCandidateIndicator() const; /**Predicate that can be used to find nodes that are Sources of that rule and connected. Thus all nodes where IsSource() returns true.*/ NodePredicateBase::ConstPointer GetConnectedSourcesDetector() const; /**Predicate that can be used to find nodes that are as source related to the passed Destination under the rule @param destination Pointer to the Destination instance that should be used for detection. @param exclusiveRelation Defines if only special types of relations should detected. None: All relations (default); Data: must be a data relation (so Data or Complete); ID: must be an ID relation (so ID or Complete); Complete: only complete relations. @pre Destination must be a valid instance.*/ NodePredicateBase::ConstPointer GetSourcesDetector( const IPropertyProvider *destination, RelationType exclusiveRelation = RelationType::None) const; /**Predicate that can be used to find nodes that are as Destination related to the passed Source under the rule @param source Pointer to the Source instance that should be used for detection. @param exclusiveRelation Defines if only special types of relations should detected. None: All relations (default); Data: must be a data relation (so Data or Complete); ID: must be an ID relation (so ID or Complete); Complete: only complete relations. @pre Source must be a valid instance.*/ NodePredicateBase::ConstPointer GetDestinationsDetector( const IPropertyProvider *source, RelationType exclusiveRelation = RelationType::None) const; /**Returns a predicate that can be used to find the Destination of the passed Source for a given relationUID. @param source Pointer to the Source instance that should be used for detection. + @param relationUID @pre source must be a valid instance. @pre relationUID must identify a relation of the passed source and rule. (This must be in the return of this->GetExistingRelations(source). */ NodePredicateBase::ConstPointer GetDestinationDetector(const IPropertyProvider *source, RelationUIDType relationUID) const; /**Disconnect the passed instances by modifing source. One can specify which layer should be disconnected via the argument "layer". Default is the complete disconnection. All RII-properties or properties that define the connection on the data layer in the source for the passed destination will be removed. @pre source must be a valid instance. @pre destination must be a valid instance. + @param source + @param destination @param layer Defines the way of disconnection. Data: Only the remove the connection on the data layer. ID: Only remove the connection on the ID layer. Complete: Remove the connection on all layers. If a connection does not exist on a selected layer, it is silently ignored.*/ void Disconnect(IPropertyOwner *source, const IPropertyProvider *destination, RelationType layer = RelationType::Complete) const; /**Disconnect the source from the passed relationUID (usefull for "zombie relations"). One can specify which layer should be disconnected via the argument "layer". Default is the complete disconnection. All RII-properties or properties that define the connection on the data layer in the source for the passed destination will be removed. If the relationUID is not part of the source. Nothing will be changed. @pre source must be a valid instance. + @param source + @param relationUID @param layer Defines the way of disconnection. Data: Only the remove the connection on the data layer. ID: Only remove the connection on the ID layer. Complete: Remove the connection on all layers. If a connection does not exist on a selected layer, it is silently ignored.*/ void Disconnect(IPropertyOwner *source, RelationUIDType relationUID, RelationType layer = RelationType::Complete) const; /**Returns the list of PropertyKeyPaths of all properties that are relevant for a given relation. @param source Pointer to the Source instance that containes the potential properties. @param relationUID UID of the relation that is relevant for the requested properties. @param layer Indicates which layer is requested. ID: returns all RII properties that belong to the relation. Data: returns all properties that are relevant/belong to the data layer of the relation. Complete: returns all properties (ID+Data) @pre source must be a valid instance. @pre relationUID must identify a relation of the passed source and rule. (This must be in the return of this->GetExistingRelations(source). */ std::vector GetReleationPropertyPaths(const IPropertyProvider* source, RelationUIDType relationUID, RelationType layer = RelationType::Data) const; protected: PropertyRelationRuleBase() = default; ~PropertyRelationRuleBase() override = default; using InstanceIDVectorType = std::vector; static InstanceIDType NULL_INSTANCE_ID(); /** Returns the instance IDs for the passed source and destination for this rule instance. If the passed source and destination instances has no explicit relation on the ID layer (Connected_ID), an empty vector will be returned. @remark Per definition of property relation rules only 0 or 1 instance should be found for one provider pair and concrete rule. But there might be more then one instanceID because either 1) the rule is abstract and supports multiple rule IDs or 2) the data layer may be ambiguous and therefore multiple relation instances of the rule instance could match. The implementation of this function should report all relation instances. The calling function will take care. @pre source must be a pointer to a valid IPropertyProvider instance. @pre destination must be a pointer to a valid IPropertyProvider instance.*/ InstanceIDVectorType GetInstanceID_IDLayer(const IPropertyProvider *source, const IPropertyProvider *destination) const; using DataRelationUIDVectorType = std::vector< std::pair >; /** Returns the ReleationUIDs of all relations that are defined by the data layer of source for this rule instance and, if defined, destination. If the passed source (and destination) instance has no relation on the data layer, an empty vector will be returned. @remark Per definition for property relation rules only 0 or 1 instance should be found for one provider pair and concrete rule. But there might be more then one instance because either 1) the rule is abstract and supports multiple rule IDs or 2) the data layer may be ambiguous (e.g. because the destination was not specified) and therefore multiple relation instances of the rule instance could match. The implementation of this function should report all relation instances. The calling function will take care. - @pre source must be a pointer to a valid IPropertyProvider instance. + @param source @param destination Destination the find relations should point to. If destination is NULL any relation on the data layer for this rule and source are wanted. @param instances_IDLayer List of releation instances that are already defined by the ID layer. The implementation of this - function should only cover releations that are not already resembled in the passed relarions_IDLayer.*/ + function should only cover releations that are not already resembled in the passed relarions_IDLayer. + @pre source must be a pointer to a valid IPropertyProvider instance.*/ virtual DataRelationUIDVectorType GetRelationUIDs_DataLayer(const IPropertyProvider * source, const IPropertyProvider * destination, const InstanceIDVectorType& instances_IDLayer) const = 0; /**Helper function that deduces the relation UID of the given relation instance. If it cannot be deduced an NoPropertyRelationException is thrown.*/ RelationUIDType GetRelationUIDByInstanceID(const IPropertyProvider *source, const InstanceIDType &instanceID) const; /**Helper function that deduces the relation instance ID given the relation UID. If it cannot be deduced an NoPropertyRelationException is thrown.*/ InstanceIDType GetInstanceIDByRelationUID(const IPropertyProvider *source, const RelationUIDType &relationUID) const; /**Explicitly connects the passed instances. Afterwards they have a relation of Data (if data layer is supported), ID (if a destination implements IIdentifiable) or Complete (if Data and ID could be connected). If the passed instance are already connected the old connection will be overwritten (and raised to the highest possible connection level). @remark This method has protected visibility in the base implementation, because it is a design decision of derived rule classes which interface they want to offer for connecting. It may just be made public (e.g. GenericIDRelationRule) or used by own implementations. @pre source must be a valid instance. @pre destination must be a valid instance. @pre the rule instance must not be abstract. @return Return the relation uid of the relation connected by this method call*/ RelationUIDType Connect(IPropertyOwner *source, const IPropertyProvider *destination) const; /**Is called by Connect() to ensure that source has correctly set properties to resemble the relation on the data layer. This means that the method should set the properties that describe and encode the relation on the data layer (data-layer-specific relation properties). If the passed instance are already connected, the old settings should be overwritten. Connect() will ensure that source and destination are valid pointers. + @param source + @param destination @param instanceID is the ID for the relation instance that should be connected. Existance of the relation instance is ensured. @pre source must be a valid instance. @pre destination must be a valid instance.*/ virtual void Connect_datalayer(IPropertyOwner *source, const IPropertyProvider *destination, const InstanceIDType &instanceID) const = 0; /**This method is called by Disconnect() to remove all properties of the relation from the source that are set by Connect_datalayer(). @remark This method should remove all properties that are set for a specific relation by Connect_datalayer(...). If the relationUID is not part of the source, nothing will be changed. Disconnect() ensures that source is a valid pointer if called. @remark Disconnect() ensures that sourece is valid and only invokes if instance exists.*/ virtual void Disconnect_datalayer(IPropertyOwner *source, const RelationUIDType & relationUID) const = 0; /** Returns if the passed rule ID is supported/relevant for the rule. Either because it is the very ID of the rule (default implementation) or because it is an abstract rule which also supports the rule ID. @return true: If the rule ID can handle the rule ID. false: the rule does not support the rule ID.*/ virtual bool IsSupportedRuleID(const RuleIDType& ruleID) const; /** Helper function that generates a reg ex that can be used to find a specific RII property for the rule instance. - * @param propName If not empty a PropertyPath element will be added (with the passed value) after the element. + * @param propName If not empty a PropertyPath element will be added (with the passed value) after the \ element. * @param instanceID If not empty only for the reg ex will only valid for the passed instanceID. Otherwise for all.*/ std::string GetRIIPropertyRegEx(const std::string propName = "", const InstanceIDType &instanceID = "") const; /**Helper function that deduces the instance ID out of a property name. If it cannot be deduced an MITK exception is thrown.*/ static InstanceIDType GetInstanceIDByPropertyName(const std::string propName); /**Helper function that retrives the rule ID of a relation instance of a passed source. @pre source must be valid. @pre source must have a relation instance with this ID*/ RuleIDType GetRuleIDByInstanceID(const IPropertyProvider *source, const InstanceIDType &instanceID) const; /**Helper function that retrives the destination UID of a relation instance of a passed source. If the relation has no destination UID, an empty string will be returned. @pre source must be valid.*/ std::string GetDestinationUIDByInstanceID(const IPropertyProvider * source, const InstanceIDType & instanceID) const; itk::LightObject::Pointer InternalClone() const override; /** helper method that serves as a workaround until T24729 is done. Please remove if T24728 is done then could directly use owner->GetPropertyKeys() again.*/ static std::vector GetPropertyKeys(const IPropertyProvider *owner); /** Helper method that tries to cast the provider to the Identifiable interface.*/ const Identifiable* CastProviderAsIdentifiable(const mitk::IPropertyProvider* provider) const; private: /** Creats a relation UID*/ static RelationUIDType CreateRelationUID(); /**Prepares a new relation instance. Therefore an unused and valid instance ID for the passed source will be genarated and a relationUID property with the relationUID will be set to block the instance ID. The instance ID will be returned. @remark The method is guarded by a class wide mutex to avoid racing conditions in a scenario where rules are used concurrently.*/ InstanceIDType CreateNewRelationInstance(IPropertyOwner *source, const RelationUIDType &relationUID) const; }; /**Exception that is used by PropertyRelationRuleBase based classes to indicate that two objects have no relation.*/ class NoPropertyRelationException : public Exception { public: mitkExceptionClassMacro(NoPropertyRelationException, Exception) }; } // namespace mitk #endif diff --git a/Modules/Core/include/mitkReferenceCountWatcher.h b/Modules/Core/include/mitkReferenceCountWatcher.h index 517a6b2e0e..c5e451fe88 100644 --- a/Modules/Core/include/mitkReferenceCountWatcher.h +++ b/Modules/Core/include/mitkReferenceCountWatcher.h @@ -1,101 +1,93 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "itkCommand.h" #include #include namespace mitk { //##Documentation //## @brief Keeps track of the reference count of an object even if //## it is destroyed. - //## - //## Example usage: - //## \code - //## SomeFilter* filter = GetSomeFilter(); - //## ReferenceCountWatcher::Pointer filterWatcher; - //## filterWatcher = new ReferenceCountWatcher(filter, "name of filter"); - //## filterWatcher->GetReferenceCount(); - //## \endcode //## @ingroup Testing class ReferenceCountWatcher : public itk::Object { public: typedef itk::SimpleMemberCommand CommandType; mitkClassMacroItkParent(ReferenceCountWatcher, itk::Object); protected: //##Documentation //## @brief Object to be watched itk::Object *m_Object; //##Documentation //## @brief Optional comment, e.g. for debugging output std::string m_Comment; //##Documentation //## @brief If \a true, \a m_Object is no longer valid //## and the returned reference count will be 0. bool m_Deleted; //##Documentation //## @brief itk::Command to get a notification when the object //## is deleted. CommandType::Pointer m_DeleteCommand; public: //##Documentation //## @brief Constructor requiring object to be watched and allowing //## an optional comment. ReferenceCountWatcher(itk::Object *o, const char *comment = "") : m_Object(o), m_Comment(comment), m_Deleted(false), m_ObserverTag(0) { m_DeleteCommand = CommandType::New(); m_DeleteCommand->SetCallbackFunction(this, &ReferenceCountWatcher::DeleteObserver); if (m_Object != nullptr) m_ObserverTag = m_Object->AddObserver(itk::DeleteEvent(), m_DeleteCommand); m_ReferenceCount = 0; } //##Documentation //## @brief Destructor: remove observer ~ReferenceCountWatcher() override { if ((m_Deleted == false) && (m_Object != nullptr)) { m_Object->RemoveObserver(m_ObserverTag); } } //##Documentation //## @brief Return the reference count of the watched object or //## 0 if it has been destroyed int GetReferenceCount() const override { if (m_Object == nullptr) return -1; if (m_Deleted) return 0; return m_Object->GetReferenceCount(); } //##Documentation //## @brief Return the optional string comment itkGetStringMacro(Comment); protected: //##Documentation //## @brief Callback called on itk::DeleteEvent() of wathched object. void DeleteObserver() { m_Deleted = true; } unsigned long m_ObserverTag; }; } diff --git a/Modules/Core/include/mitkRenderWindow.h b/Modules/Core/include/mitkRenderWindow.h index 64911a9143..c146d959e4 100644 --- a/Modules/Core/include/mitkRenderWindow.h +++ b/Modules/Core/include/mitkRenderWindow.h @@ -1,93 +1,93 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKRENDERWINDOW_H_HEADER_INCLUDED_C1C40D66ASDF #define MITKRENDERWINDOW_H_HEADER_INCLUDED_C1C40D66ASDF #include #include "mitkRenderWindowBase.h" namespace mitk { class vtkEventProvider; /** * \brief mitkRenderWindow integrates the MITK rendering mechanism into VTK and * is NOT QT dependent * * * \ingroup Renderer */ class MITKCORE_EXPORT RenderWindow : public mitk::RenderWindowBase, public itk::Object { public: mitkClassMacroItkParent(RenderWindow, itk::Object); itkFactorylessNewMacro(Self); itkCloneMacro(Self); mitkNewMacro1Param(Self, vtkRenderWindow*); mitkNewMacro2Param(Self, vtkRenderWindow *, const char *); ~RenderWindow() override; vtkRenderWindow *GetVtkRenderWindow() override; vtkRenderWindowInteractor *GetVtkRenderWindowInteractor() override; // Set Layout Index to define the Layout Type void SetLayoutIndex(unsigned int layoutIndex); // Get Layout Index to define the Layout Type unsigned int GetLayoutIndex(); // MenuWidget need to update the Layout Design List when Layout had changed void LayoutDesignListChanged(int layoutDesignIndex); void FullScreenMode(bool state); /** * \brief Convenience method to set the size of an mitkRenderWindow. * * This method sets the size of the vtkRenderWindow and tells the * rendering that the size has changed -> adapts displayGeometry, etc. */ void SetSize(int width, int height); /** * \brief Initializes the mitkVtkEventProvider to listen to the * currently used vtkInteractorStyle. * * This method makes sure that the internal mitkVtkEventProvider * listens to the correct vtkInteractorStyle. * This makes sure that VTK-Events are correctly translated into * MITK-Events. * - * \warn This method needs to be called MANUALLY as soon as the MapperID + * \warning This method needs to be called MANUALLY as soon as the MapperID * for this RenderWindow is changed or the vtkInteractorStyle is modified * somehow else! */ void ReinitEventProvider(); protected: RenderWindow(vtkRenderWindow *existingRenderWindow = nullptr, const char *name = "unnamed renderer"); void ResetView(); vtkRenderWindow *m_vtkRenderWindow; vtkRenderWindowInteractor *m_vtkRenderWindowInteractor; vtkEventProvider *m_vtkMitkEventProvider; private: }; } // namespace #endif /* MITKRENDERWINDOW_H_HEADER_INCLUDED_C1C40D66ASDF */ diff --git a/Modules/Core/include/mitkRestorePlanePositionOperation.h b/Modules/Core/include/mitkRestorePlanePositionOperation.h index 80b67b70a7..094f9b19b1 100644 --- a/Modules/Core/include/mitkRestorePlanePositionOperation.h +++ b/Modules/Core/include/mitkRestorePlanePositionOperation.h @@ -1,78 +1,61 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkRestorePlanePositionOperation_h_Included #define mitkRestorePlanePositionOperation_h_Included #include "mitkCommon.h" #include "mitkNumericTypes.h" #include "mitkPointOperation.h" namespace mitk { - //##Documentation - //## TODO - class MITKCORE_EXPORT RestorePlanePositionOperation : public Operation { public: - //##Documentation - //##@brief Operation that handles all actions on one Point. - //## - //## @param operationType is the type of the operation (see mitkOperation.h; e.g. move or add; Information for - // StateMachine::ExecuteOperation()); - //## @param width - //## @param height - //## @param spacing - //## @param pos - //## @param direction - //## @param transform - // PointOperation(OperationType operationType, Point3D point, int index = -1, bool selected = true, - // PointSpecificationType type = PTUNDEFINED); - RestorePlanePositionOperation(OperationType operationType, ScalarType width, ScalarType height, Vector3D spacing, unsigned int pos, Vector3D direction, AffineTransform3D::Pointer transform); ~RestorePlanePositionOperation() override; Vector3D GetDirectionVector(); ScalarType GetWidth(); ScalarType GetHeight(); Vector3D GetSpacing(); unsigned int GetPos(); AffineTransform3D::Pointer GetTransform(); private: Vector3D m_Spacing; Vector3D m_DirectionVector; ScalarType m_Width; ScalarType m_Height; unsigned int m_Pos; AffineTransform3D::Pointer m_Transform; }; } // namespace mitk #endif diff --git a/Modules/DataTypesExt/include/mitkLabeledImageLookupTable.h b/Modules/DataTypesExt/include/mitkLabeledImageLookupTable.h index f30b6f1d5a..fd3f5630a5 100644 --- a/Modules/DataTypesExt/include/mitkLabeledImageLookupTable.h +++ b/Modules/DataTypesExt/include/mitkLabeledImageLookupTable.h @@ -1,112 +1,112 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKMITKLABELEDIMAGELOOKUPTABLE_H #define MITKMITKLABELEDIMAGELOOKUPTABLE_H #include "MitkDataTypesExtExports.h" #include "mitkLevelWindow.h" #include "mitkLookupTable.h" #include #include namespace mitk { /** * A lookup table for 2D mapping of labeled images. The lookup table supports * images with up to 256 unsigned labels. Negative labels are not supported. * Please use the level/window settings as given by the GetLevelWindow() method * to make sure, that the colors are rendered correctly. * The colors are initialized with random colors as default. As background * the label 0 is assumed. The color for the background is set to fully transparent * as default. */ class MITKDATATYPESEXT_EXPORT LabeledImageLookupTable : public LookupTable { public: /** * Standard mitk typedefs are generated by the mitkClassMacro */ mitkClassMacro(LabeledImageLookupTable, LookupTable); /** - * Make this object constructable by the ::New() Method. + * Make this object constructable by the ::%New() Method. */ itkFactorylessNewMacro(Self); itkCloneMacro(Self); /** * The data type for a label. Currently only images with labels * in the range [0,255] are supported. */ typedef unsigned char LabelType; LabeledImageLookupTable &operator=(const LookupTable &other) override; /** * Sets the color for a given label * @param label The pixel value used as a label in the image * @param r The red component of the rgba color value. Values sould be given in the range [0,1] * @param g The green component of the rgba color value. Values sould be given in the range [0,1] * @param b The blue component of the rgba color value. Values sould be given in the range [0,1] * @param a The alpha component of the rgba color value. Values sould be given in the range [0,1]. Default is 1. */ virtual void SetColorForLabel( const LabelType &label, const double &r, const double &g, const double &b, const double a = 1.0); /** * Determines the color which will be used for coloring a given label. * @param label the label for which the color should be returned * @returns an rgba array containing the color information for the given label. * Color components are expressed as [0,1] double values. */ virtual double *GetColorForLabel(const LabelType &label); /** * Provides access to level window settings, which should be used * in combination with the LUTs generated by this filter (at lease for * 2D visualization. If you use other level/window settings, it is not * guaranteed, that scalar values are mapped to the correct colors. */ mitk::LevelWindow GetLevelWindow() { return m_LevelWindow; } protected: /** * Default constructor. Protected to prevent "normal" creation */ LabeledImageLookupTable(); LabeledImageLookupTable(const LabeledImageLookupTable &other); /** * Virtual destructor */ ~LabeledImageLookupTable() override; /** * Generates a random rgb color value. Values for rgb are in the range * [0,1] */ virtual void GenerateRandomColor(double &r, double &g, double &b); /** * Generates a radnom number drawn from a uniform * distribution in the range [0,1]. */ virtual double GenerateRandomNumber(); mitk::LevelWindow m_LevelWindow; private: itk::LightObject::Pointer InternalClone() const override; }; } #endif diff --git a/Modules/DataTypesExt/include/mitkLineOperation.h b/Modules/DataTypesExt/include/mitkLineOperation.h index cee666c7ec..6b486d19d8 100644 --- a/Modules/DataTypesExt/include/mitkLineOperation.h +++ b/Modules/DataTypesExt/include/mitkLineOperation.h @@ -1,57 +1,55 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKLINEOPERATION_H_INCLUDED #define MITKLINEOPERATION_H_INCLUDED #include "MitkDataTypesExtExports.h" #include "mitkCellOperation.h" #include "mitkCommon.h" namespace mitk { - //##Documentation - //## @brief Operation, that holds everything necessary for an operation on a line. - //## - //## Stores everything for de-/ selecting, inserting , moving and removing a line. - //## @ingroup Undo + /** @brief Operation, that holds everything necessary for an operation on a line. + * Stores everything for de-/ selecting, inserting , moving and removing a line. + * @ingroup Undo + */ class MITKDATATYPESEXT_EXPORT LineOperation : public mitk::CellOperation { public: mitkClassMacro(LineOperation, CellOperation); - //##Documentation - //##@brief constructor. - //## - //## @param operationType is the type of that operation (see mitkOperation.h; e.g. move or add; Information for - //StateMachine::ExecuteOperation()); - //## @param cellId Id of the cell - //## @param vector is for movement - //## @param pIdA and pIdB are Id's of two points - //## @param id is the Id of a line in a cell + /** @brief constructor. + * @param operationType is the type of that operation (see mitkOperation.h; e.g. move or add; Information for StateMachine::ExecuteOperation()); + * @param cellId Id of the cell + * @param vector is for movement + * @param pIdA and pIdB are Id's of two points + * @param pIdB + * @param id is the Id of a line in a cell + */ LineOperation(OperationType operationType, int cellId, Vector3D vector, int pIdA = -1, int pIdB = -1, int id = -1); LineOperation(OperationType operationType, int cellId = -1, int pIdA = -1, int pIdB = -1, int id = -1); ~LineOperation() override{}; // int GetCellId(); int GetPIdA(); int GetPIdB(); int GetId(); protected: // int m_CellId; int m_PIdA; int m_PIdB; int m_Id; }; } // namespace mitk #endif /* MITKLINEOPERATION_H_INCLUDED*/ diff --git a/Modules/IGT/Algorithms/mitkNavigationDataLandmarkTransformFilter.h b/Modules/IGT/Algorithms/mitkNavigationDataLandmarkTransformFilter.h index ef20fd7f6b..6b1da856d8 100644 --- a/Modules/IGT/Algorithms/mitkNavigationDataLandmarkTransformFilter.h +++ b/Modules/IGT/Algorithms/mitkNavigationDataLandmarkTransformFilter.h @@ -1,184 +1,183 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKNavigationDataLandmarkTransformFilter_H_HEADER_INCLUDED_ #define MITKNavigationDataLandmarkTransformFilter_H_HEADER_INCLUDED_ #include #include #include #include #include namespace mitk { /**Documentation * \brief NavigationDataLandmarkTransformFilter applies a itk-landmark-transformation * defined by source and target pointsets. * * Before executing the filter SetSourceLandmarks and SetTargetLandmarks must be called. Before both source * and target landmarks are set, the filter performs an identity transform. * If source or target points are changed after calling SetXXXPoints, the corresponding SetXXXPoints * method has to be called again to apply the changes. * If UseICPInitialization is false (standard value, or set with SetUseICPInitialization(false) or UseICPInitializationOff()) * then source landmarks and target landmarks with the same ID must correspond to each other. * (--> source landmark with ID x will be mapped to target landmark with ID x). * If you do not know the correspondences, call SetUseICPInitialization(true) or UseICPInitializationOn() * to let the filter guess the correspondences during initialization with an iterative closest point search. * This is only possible, if at least 6 source and target landmarks are available. * * \ingroup IGT */ class MITKIGT_EXPORT NavigationDataLandmarkTransformFilter : public NavigationDataToNavigationDataFilter { public: mitkClassMacro(NavigationDataLandmarkTransformFilter, NavigationDataToNavigationDataFilter); itkFactorylessNewMacro(Self); itkCloneMacro(Self); typedef std::vector ErrorVector; typedef itk::VersorRigid3DTransform< double > LandmarkTransformType; /** *\brief Set points used as source points for landmark transform. * */ virtual void SetSourceLandmarks(mitk::PointSet::Pointer sourcePointSet); /** *\brief Set points used as target points for landmark transform * */ virtual void SetTargetLandmarks(mitk::PointSet::Pointer targetPointSet); virtual bool IsInitialized() const; /** *\brief Returns the Fiducial Registration Error * */ mitk::ScalarType GetFRE() const; /** *\brief Returns the standard deviation of the Fiducial Registration Error * */ mitk::ScalarType GetFREStdDev() const; /** *\brief Returns the Root Mean Square of the registration error * */ mitk::ScalarType GetRMSError() const; /** *\brief Returns the minimum registration error / best fitting landmark distance * */ mitk::ScalarType GetMinError() const; /** *\brief Returns the maximum registration error / worst fitting landmark distance * */ mitk::ScalarType GetMaxError() const; /** *\brief Returns the absolute maximum registration error * */ mitk::ScalarType GetAbsMaxError() const; /** *\brief Returns a vector with the euclidean distance of each transformed source point to its respective target point * */ const ErrorVector& GetErrorVector() const; itkSetMacro(UseICPInitialization, bool); ///< If set to true, source and target point correspondences are established with iterative closest point optimization itkGetMacro(UseICPInitialization, bool); ///< If set to true, source and target point correspondences are established with iterative closest point optimization itkBooleanMacro(UseICPInitialization); ///< If set to true, source and target point correspondences are established with iterative closest point optimization itkGetConstObjectMacro(LandmarkTransform, LandmarkTransformType); ///< returns the current landmark transform protected: typedef itk::Image< signed short, 3> ImageType; // only because itk::LandmarkBasedTransformInitializer must be templated over two imagetypes typedef itk::LandmarkBasedTransformInitializer< LandmarkTransformType, ImageType, ImageType > TransformInitializerType; typedef TransformInitializerType::LandmarkPointContainer LandmarkPointContainer; typedef itk::QuaternionRigidTransform QuaternionTransformType; /** * \brief Constructor **/ NavigationDataLandmarkTransformFilter(); ~NavigationDataLandmarkTransformFilter() override; /** * \brief transforms input NDs according to the calculated LandmarkTransform * */ void GenerateData() override; /**Documentation * \brief perform an iterative closest point matching to find corresponding landmarks that will be used for landmark transform calculation * * Perform ICP optimization to match source landmarks to target landmarks. Landmark containers must contain * at least 6 landmarks for the optimization. * after ICP, landmark correspondences are established and the source landmarks are sorted, so that * corresponding landmarks have the same indices. * - * \param[in] sources Source landmarks that will be mapped to the target landmarks + * \param[in,out] sources Source landmarks that will be mapped to the target landmarks. The sources container will be sorted, + * so that landmarks have the same index as their corresponding target landmarks. * \param[in] targets Target landmarks onto which the source landmarks will be mapped - * \param[out] sources The sources container will be sorted, - so that landmarks have the same index as their corresponding target landmarks * \return true if ICP was successful and sources are sorted , false otherwise */ bool FindCorrespondentLandmarks(LandmarkPointContainer& sources, const LandmarkPointContainer& targets) const; /** * \brief initializes the transform using source and target PointSets * * if UseICPInitialization is true, FindCorrespondentLandmarks() will be used to sort the source landmarks in order to * establish corresponding landmark pairs before the landmark transform is build */ void InitializeLandmarkTransform(LandmarkPointContainer& sources, const LandmarkPointContainer& targets); /** * \brief calculates the transform using source and target PointSets */ void UpdateLandmarkTransform(const LandmarkPointContainer &sources, const LandmarkPointContainer &targets); ///< void AccumulateStatistics(ErrorVector& vector); ///< calculate error metrics for the transforms. void PrintSelf( std::ostream& os, itk::Indent indent ) const override; ///< print object info to ostream mitk::ScalarType m_ErrorMean; ///< Fiducial Registration Error mitk::ScalarType m_ErrorStdDev; ///< standard deviation of the Fiducial Registration Error mitk::ScalarType m_ErrorRMS; ///< Root Mean Square of the registration error mitk::ScalarType m_ErrorMin; ///< minimum registration error / best fitting landmark distance mitk::ScalarType m_ErrorMax; ///< maximum registration error / worst fitting landmark distance mitk::ScalarType m_ErrorAbsMax; ///< the absolute maximum registration error LandmarkPointContainer m_SourcePoints; ///< positions of the source points LandmarkPointContainer m_TargetPoints; ///< positions of the target points TransformInitializerType::Pointer m_LandmarkTransformInitializer; ///< landmark based transform initializer LandmarkTransformType::Pointer m_LandmarkTransform; ///< transform calculated from source and target points QuaternionTransformType::Pointer m_QuatLandmarkTransform; ///< transform needed to rotate orientation QuaternionTransformType::Pointer m_QuatTransform; ///< further transform needed to rotate orientation ErrorVector m_Errors; ///< stores the euclidean distance of each transformed source landmark and its respective target landmark bool m_UseICPInitialization; ///< find source <--> target point correspondences with iterative closest point optimization }; } // namespace mitk #endif /* MITKNavigationDataLandmarkTransformFilter_H_HEADER_INCLUDED_ */ diff --git a/Modules/IGT/Algorithms/mitkNavigationDataToIGTLMessageFilter.h b/Modules/IGT/Algorithms/mitkNavigationDataToIGTLMessageFilter.h index 2378204f95..b16d9b8e82 100644 --- a/Modules/IGT/Algorithms/mitkNavigationDataToIGTLMessageFilter.h +++ b/Modules/IGT/Algorithms/mitkNavigationDataToIGTLMessageFilter.h @@ -1,169 +1,169 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef _MITKNAVIGATIONDATATOIGTLMessageFILTER_H__ #define _MITKNAVIGATIONDATATOIGTLMessageFILTER_H__ #include "mitkCommon.h" #include "mitkPointSet.h" #include "mitkIGTLMessageSource.h" #include "mitkNavigationData.h" #include "mitkNavigationDataSource.h" namespace mitk { /**Documentation * * \brief This filter creates IGTL messages from mitk::NavigaitionData objects * * * \ingroup IGT * */ class MITKIGT_EXPORT NavigationDataToIGTLMessageFilter : public IGTLMessageSource { public: mitkClassMacro(NavigationDataToIGTLMessageFilter, IGTLMessageSource); itkFactorylessNewMacro(Self); itkCloneMacro(Self); /**Documentation * \brief There are four different operation modes. * * - ModeSendQTransMsg: every input NavigationData is processed into one * output message that contains a position and a orientation (quaternion). * - ModeSendTransMsg: every input NavigationData is processed into one * output message that contains a 4x4 transformation. * - ModeSendQTDataMsg:all input NavigationData is processed into one single * output message that contains a position and orientation (quaternion) for * each navigation data. * - ModeSendTDataMsg:all input NavigationData is processed into one single * output message that contains a 4x4 transformation for * each navigation data. */ enum OperationMode { ModeSendQTransMsg, ModeSendTransMsg, ModeSendQTDataMsg, ModeSendTDataMsg }; /** * \brief filter execute method */ void GenerateData() override; using Superclass::SetInput; /** * \brief Sets one input NavigationData */ virtual void SetInput(const mitk::NavigationData *NavigationData); /** * \brief Sets the input NavigationData at a specific index */ virtual void SetInput(unsigned int idx, const NavigationData* nd); /** * \brief Returns the input of this filter */ const mitk::NavigationData* GetInput(); /** * \brief Returns the input number idx of this filter */ const mitk::NavigationData* GetInput(unsigned int idx); /** * \brief Sets the mode of this filter. * * See OperationMode for the behavior in the different modes - * \warn A call to this method will change the number of outputs of the filter. + * \warning A call to this method will change the number of outputs of the filter. * After calling this method, all previously acquired pointers to outputs are invalid * Always set the operation mode first, then get the outputs with GetOutput() */ virtual void SetOperationMode(OperationMode mode); /** * \brief returns the mode of this filter. * * See OperationMode for the behavior in the different modes */ itkGetConstMacro(OperationMode, OperationMode); /** * empty implementation to prevent calling of the superclass method that * would try to copy information from the input NavigationData to the output * PointSet, which makes no sense! */ void GenerateOutputInformation() override {}; /** *\brief Connects the input of this filter to the outputs of the given * NavigationDataSource * * This method does not support smartpointer. use FilterX.GetPointer() to * retrieve a dumbpointer. */ virtual void ConnectTo(mitk::NavigationDataSource * UpstreamFilter); protected: NavigationDataToIGTLMessageFilter(); ~NavigationDataToIGTLMessageFilter() override; /** * \brief Generates the output * */ // virtual void GenerateData(); /** * \brief Generates the output for ModeSendQTDataMsg * */ virtual void GenerateDataModeSendQTDataMsg(); /** * \brief Generates the output for ModeSendTDataMsg */ virtual void GenerateDataModeSendTDataMsg(); /** * \brief Generates the output for ModeSendQTransMsg * */ virtual void GenerateDataModeSendQTransMsg(); /** * \brief Generates the output for ModeSendTransMsg */ virtual void GenerateDataModeSendTransMsg(); /** * \brief create output objects according to OperationMode for all inputs */ virtual void CreateOutputsForAllInputs(); OperationMode m_OperationMode; ///< Stores the mode. See enum OperationMode // unsigned int m_RingBufferSize; ///< Stores the ringbuffer size unsigned int m_CurrentTimeStep; ///< Indicates the current timestamp // unsigned int m_NumberForMean; ///< Number of Navigation Data, which should be averaged /** Converts a mitk::IGTTimestamp (double, milliseconds) to an OpenIGTLink timestamp */ igtl::TimeStamp::Pointer ConvertToIGTLTimeStamp(double IGTTimeStamp); /** Measurement class to calculate latency and frame count */ }; } // namespace mitk #endif // _MITKNAVIGATIONDATATOIGTLMessageFILTER_H__ diff --git a/Modules/IGT/Algorithms/mitkNavigationDataToPointSetFilter.h b/Modules/IGT/Algorithms/mitkNavigationDataToPointSetFilter.h index 3850298b2a..c3284ce805 100644 --- a/Modules/IGT/Algorithms/mitkNavigationDataToPointSetFilter.h +++ b/Modules/IGT/Algorithms/mitkNavigationDataToPointSetFilter.h @@ -1,155 +1,155 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef _MITKNAVIGATIONDATATOPOINTSETFILTER_H__ #define _MITKNAVIGATIONDATATOPOINTSETFILTER_H__ #include "mitkCommon.h" #include "mitkPointSet.h" #include "mitkPointSetSource.h" #include "mitkNavigationData.h" #include "MitkIGTExports.h" namespace mitk { /**Documentation * * \brief This filter creates mitk::PointSet objects from mitk::NavigaitionData objects * * This filter has two modes that can be set with SetOperationMode(). * - Mode3D: every input NavigationData is processed into one output pointset. For each call to Update() a point with the ND position will be added to the PointSet * - Mode4D: one output pointset is generated that contains one point for each input NavigationData. Each call to Update() adds a new timestep to the PointSet that contains new positions for the points. * * \ingroup IGT * */ class MITKIGT_EXPORT NavigationDataToPointSetFilter : public PointSetSource { public: mitkClassMacro(NavigationDataToPointSetFilter, PointSetSource); itkFactorylessNewMacro(Self); itkCloneMacro(Self); /**Documentation * \brief There are two different operation modes. * * - Mode3D: every input NavigationData is processed into one output pointset that contains a point with the ND position for each Update() * - Mode3DMean: a defined number of input NavigationData is used to generate a mean position and processed into one output pointset that contains a point with the ND position for each Update() * - Mode4D: one output pointset is generated that contains one point for each input NavigationData. Each call to Update() adds a new timestep to the PointSet that contains new positions for the points. * The RingBufferSize limits the number of timesteps in the 4D mode. It currently does _not_ limit the number of points in the 3D mode. */ enum OperationMode { Mode3D, Mode3DMean, Mode4D }; /**Documentation * \brief Sets the size for the ring buffer. * * The size determines the maximum number of timesteps in 4D mode and the number of points in 3D mode of the output PointSet */ itkSetMacro(RingBufferSize, unsigned int); /** * \brief Sets the number of Navigation Data, which should be averaged. */ itkSetMacro(NumberForMean, unsigned int); /** * \brief Gets the number of Navigation Data, which should be averaged. */ itkGetMacro(NumberForMean, unsigned int); /** * \brief filter execute method */ void GenerateData() override; using Superclass::SetInput; /** * \brief Sets one input NavigationData */ virtual void SetInput(const mitk::NavigationData *NavigationData); /** * \brief Sets the input NavigationData at a specific index */ virtual void SetInput(unsigned int idx, const NavigationData* nd); /** * \brief Returns the input of this filter */ const mitk::NavigationData* GetInput(); /** * \brief Returns the input number idx of this filter */ const mitk::NavigationData* GetInput(unsigned int idx); /** * \brief Sets the mode of this filter. * * See OperationMode for the behavior in the different modes - * \warn A call to this method will change the number of outputs of the filter. + * \warning A call to this method will change the number of outputs of the filter. * After calling this method, all previously acquired pointers to outputs are invalid * Always set the operation mode first, then get the outputs with GetOutput() */ virtual void SetOperationMode(OperationMode mode); /** * \brief returns the mode of this filter. * * See OperationMode for the behavior in the different modes */ itkGetConstMacro(OperationMode, OperationMode); void GenerateOutputInformation() override {}; ///< empty implementation to prevent calling of the superclass method that would try to copy information from the input NavigationData to the output PointSet, which makes no sense! protected: NavigationDataToPointSetFilter(); ~NavigationDataToPointSetFilter() override; /** * \brief Generates the output for Mode3D * */ virtual void GenerateDataMode3D(); /** * \brief Generates the output for Mode3DMean * */ virtual void GenerateDataMode3DMean(); /** * \brief Generates the output for Mode4D */ virtual void GenerateDataMode4D(); /** * \brief create output objects according to OperationMode for all inputs */ virtual void CreateOutputsForAllInputs(); OperationMode m_OperationMode; ///< Stores the mode. See enum OperationMode unsigned int m_RingBufferSize; ///< Stores the ringbuffer size unsigned int m_CurrentTimeStep; ///< Indicates the current timestamp unsigned int m_NumberForMean; ///< Number of Navigation Data, which should be averaged }; } // namespace mitk #endif // _MITKNAVIGATIONDATATOPOINTSETFILTER_H__ diff --git a/Modules/IGT/Rendering/mitkNavigationDataObjectVisualizationFilter.h b/Modules/IGT/Rendering/mitkNavigationDataObjectVisualizationFilter.h index 42871e0337..d19771f2fc 100644 --- a/Modules/IGT/Rendering/mitkNavigationDataObjectVisualizationFilter.h +++ b/Modules/IGT/Rendering/mitkNavigationDataObjectVisualizationFilter.h @@ -1,176 +1,177 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKNAVIGATIONDATAOBJECTVISUALIZATIONFILTER_H_HEADER_INCLUDED_ #define MITKNAVIGATIONDATAOBJECTVISUALIZATIONFILTER_H_HEADER_INCLUDED_ #include "mitkNavigationDataToNavigationDataFilter.h" #include "mitkNavigationData.h" #include "mitkBaseData.h" namespace mitk { /** * \brief Class that reads NavigationData from input and transfers the information to the geometry of the associated BaseData * * Derived from NavigationDataToNavigationDataFilter * * \ingroup IGT */ class MITKIGT_EXPORT NavigationDataObjectVisualizationFilter : public NavigationDataToNavigationDataFilter { public: mitkClassMacro(NavigationDataObjectVisualizationFilter, NavigationDataToNavigationDataFilter); itkFactorylessNewMacro(Self); itkCloneMacro(Self); /** Defines the rotation modes of this tracking device which results in different representations * of quaternions. * * - Standard: normal representation, rawdata from the device is not changed (DEFAULT) * * - Transposed: the rotation is stored transposed, which is (by mistake!) expected by some older MITK classes due * to an ambigious method naming in VNL. * * CAUTION: The rotation mode can only be changed for backward compatibility of old WRONG code. * PLEASE DO NOT CHANGE THE ROTATION MODE UNLESS YOU ARE KNOWING EXACTLY WHAT YOU ARE DOING! * * use SetRotationMode to change the mode. */ enum RotationMode {RotationStandard, RotationTransposed}; /** * \brief Smart Pointer type to a BaseData. */ typedef BaseData::Pointer RepresentationPointer; /** * \brief STL map of index to BaseData . Using map to be able to set non continuous indices */ typedef std::map RepresentationPointerMap; /** * \brief STL vector map of index to BaseData . Using map to be able to set non continuous indices */ typedef std::map> RepresentationVectorPointerMap; /** * \brief Size type of an std::vector */ typedef RepresentationVectorPointerMap::size_type RepresentationPointerMapSizeType; /** * \brief Set the representation object of the input * * \param data The BaseData to be associated to the index * \param index the index with which data will be associated */ void SetRepresentationObject(unsigned int index, BaseData::Pointer data); /** * \brief Set the representation objects vector of the input * * \param data The BaseData vector to be associated to the index * \param index the index with which data will be associated */ void SetRepresentationObjects(unsigned int index, const std::vector &data); /** * \brief Get the representation object associated with the index idx * * \param idx the corresponding input number with which the BaseData is associated * \return Returns the desired BaseData if it exists for the given input; Returns nullptr * if no BaseData was found. */ BaseData::Pointer GetRepresentationObject(unsigned int idx) const; /** * \brief Get all the representation objects associated with the index idx * * \param idx the corresponding input number with which the BaseData is associated * \return Returns the desired BaseData if it exists for the given input; Returns nullptr * if no BaseData was found. */ std::vector GetAllRepresentationObjects(unsigned int idx) const; virtual void SetTransformPosition(unsigned int index, bool applyTransform); ///< if set to true, the filter will use the position part of the input navigation data at the given index to transform the representation object. If set to false, it will not. If no value is set, it defaults to true. virtual bool GetTransformPosition(unsigned int index) const; ///< returns whether position part of the input navigation data at the given index is used for the transformation of the representation object. virtual void TransformPositionOn(unsigned int index); ///< sets the TransformPosition flag to true for the given index virtual void TransformPositionOff(unsigned int index); ///< sets the TransformPosition flag to false for the given index virtual void SetTransformOrientation(unsigned int index, bool applyTransform); ///< if set to true, the filter will use the orientation part of the input navigation data at the given index to transform the representation object. If set to false, it will not. If no value is set, it defaults to true. virtual bool GetTransformOrientation(unsigned int index) const; ///< returns whether orientation part of the input navigation data at the given index is used for the transformation of the representation object. virtual void TransformOrientationOn(unsigned int index); ///< sets the TransformOrientation flag to true for the given index virtual void TransformOrientationOff(unsigned int index); ///< sets the TransformOrientation flag to false for the given index /** @brief Defines an offset for a representation object. This offset is applied before the object is visualized. * If no offset is given, no offset will be used. To deactivate the offset just set it to nullptr. The offset is deactivated by default. + * @param index * @param offset The new offset which will be set. Set to nullptr to deactivate the offset. */ void SetOffset(int index, mitk::AffineTransform3D::Pointer offset); /** Sets the rotation mode of this class. See documentation of enum RotationMode for details * on the different modes. * CAUTION: The rotation mode can only be changed for backward compatibility of old WRONG code. * PLEASE DO NOT CHANGE THE ROTATION MODE UNLESS YOU ARE KNOWING EXACTLY WHAT YOU ARE DOING! */ virtual void SetRotationMode(RotationMode r); /** @return Returns the offset of a represenation object. Returns nullptr if there is no offset. */ mitk::AffineTransform3D::Pointer GetOffset(int index); /** *\brief Get the number of added BaseData associated to NavigationData * \return Returns the size of the internal map */ RepresentationPointerMapSizeType GetNumberOfToolRepresentations() const { return m_RepresentationVectorMap.size(); } /* * \brief Transfer the information from the input to the associated BaseData */ void GenerateData() override; protected: typedef std::map BooleanInputMap; typedef std::map OffsetPointerMap; /** * \brief Constructor **/ NavigationDataObjectVisualizationFilter(); /** * \brief Destructor **/ ~NavigationDataObjectVisualizationFilter() override; /** * \brief An array of the BaseData which represent the tools. */ RepresentationVectorPointerMap m_RepresentationVectorMap; BooleanInputMap m_TransformPosition; ///< if set to true, the filter will use the position part of the input navigation data at the given index for the calculation of the transform. If no entry for the index exists, it defaults to true. BooleanInputMap m_TransformOrientation; ///< if set to true, the filter will use the orientation part of the input navigation data at the given index for the calculation of the transform. If no entry for the index exists, it defaults to true. OffsetPointerMap m_OffsetList; private: RotationMode m_RotationMode; ///< defines the rotation mode Standard or Transposed, Standard is default }; } // namespace mitk #endif /* MITKNAVIGATIONDATAOBJECTVISUALIZATIONFILTER_H_HEADER_INCLUDED_ */ diff --git a/Modules/IGTBase/include/mitkNavigationData.h b/Modules/IGTBase/include/mitkNavigationData.h index ad041dfd64..ef6571a6ae 100644 --- a/Modules/IGTBase/include/mitkNavigationData.h +++ b/Modules/IGTBase/include/mitkNavigationData.h @@ -1,294 +1,295 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKNAVIGATIONDATA_H_HEADER_INCLUDED_ #define MITKNAVIGATIONDATA_H_HEADER_INCLUDED_ #include #include #include #include namespace mitk { /**Documentation * \brief Navigation Data * * This class represents the data object that is passed through the MITK-IGT navigation filter * pipeline. It encapsulates position and orientation of a tracked tool/sensor. Additionally, * it contains a data structure that contains error/plausibility information * * It provides methods to work with the affine transformation represented by its orientation and position. * Additionally, it provides a constructor to construct a NavigationData object from an AffineTransform3D and * a getter to create an AffineTransform3D from a NavigationData object. * * \ingroup IGT */ class MITKIGTBASE_EXPORT NavigationData : public itk::DataObject { public: mitkClassMacroItkParent(NavigationData, itk::DataObject); itkFactorylessNewMacro(Self); itkCloneMacro(Self); mitkNewMacro2Param(Self, mitk::AffineTransform3D::Pointer, const bool); mitkNewMacro1Param(Self, mitk::AffineTransform3D::Pointer); /** * \brief Type that holds the position part of the tracking data */ typedef mitk::Point3D PositionType; /** * \brief Type that holds the orientation part of the tracking data */ typedef mitk::Quaternion OrientationType; /** * \brief type that holds the error characterization of the position and orientation measurements */ typedef itk::Matrix CovarianceMatrixType; /** * \brief type that holds the time at which the data was recorded in milliseconds */ typedef double TimeStampType; /** * \brief sets the position of the NavigationData object */ itkSetMacro(Position, PositionType); /** * \brief returns position of the NavigationData object */ itkGetConstMacro(Position, PositionType); /** * \brief sets the orientation of the NavigationData object */ itkSetMacro(Orientation, OrientationType); /** * \brief returns the orientation of the NavigationData object */ itkGetConstMacro(Orientation, OrientationType); /** * \brief returns true if the object contains valid data */ virtual bool IsDataValid() const; /** * \brief sets the dataValid flag of the NavigationData object indicating if the object contains valid data */ itkSetMacro(DataValid, bool); /** * \brief sets the IGT timestamp of the NavigationData object in milliseconds */ itkSetMacro(IGTTimeStamp, TimeStampType); /** * \brief gets the IGT timestamp of the NavigationData object in milliseconds * Please note, that there is also the GetTimeStamp method provided by the ITK object. Within IGT you should always use GetIGTTimeStamp ! */ itkGetConstMacro(IGTTimeStamp, TimeStampType); /** * \brief sets the HasPosition flag of the NavigationData object */ itkSetMacro(HasPosition, bool); /** * \brief gets the HasPosition flag of the NavigationData object */ itkGetConstMacro(HasPosition, bool); /** * \brief sets the HasOrientation flag of the NavigationData object */ itkSetMacro(HasOrientation, bool); /** * \brief gets the HasOrientation flag of the NavigationData object */ itkGetConstMacro(HasOrientation, bool); /** * \brief sets the 6x6 Error Covariance Matrix of the NavigationData object */ itkSetMacro(CovErrorMatrix, CovarianceMatrixType); /** * \brief gets the 6x6 Error Covariance Matrix of the NavigationData object */ itkGetConstMacro(CovErrorMatrix, CovarianceMatrixType); /** * \brief set the name of the NavigationData object */ itkSetStringMacro(Name); /** * \brief returns the name of the NavigationData object */ itkGetStringMacro(Name); /** * \brief Graft the data and information from one NavigationData to another. * * Copies the content of data into this object. * This is a convenience method to setup a second NavigationData object with all the meta * information of another NavigationData object. * Note that this method is different than just using two * SmartPointers to the same NavigationData object since separate DataObjects are * still maintained. */ void Graft(const DataObject *data) override; /** * \brief copy meta data of a NavigationData object * * copies all meta data from NavigationData data to this object */ void CopyInformation(const DataObject* data) override; /** * \brief Prints the object information to the given stream os. * \param os The stream which is used to print the output. * \param indent Defines the indentation of the output. */ void PrintSelf(std::ostream& os, itk::Indent indent) const override; /** * Set the position part of m_CovErrorMatrix to I*error^2 * This means that all position variables are assumed to be independent */ void SetPositionAccuracy(mitk::ScalarType error); /** * Set the orientation part of m_CovErrorMatrix to I*error^2 * This means that all orientation variables are assumed to be independent */ void SetOrientationAccuracy(mitk::ScalarType error); /** * \brief Calculate AffineTransform3D from the transformation held by this NavigationData. * TODO: should throw an error if transformation is invalid. */ mitk::AffineTransform3D::Pointer GetAffineTransform3D() const; /** * \brief Calculate the RotationMatrix of this transformation. */ mitk::Matrix3D GetRotationMatrix() const; /** * \brief Transform by an affine transformation * * This method applies the affine transform given by self to a * given point, returning the transformed point. */ mitk::Point3D TransformPoint(const mitk::Point3D point) const; /** * Get inverse of the Transformation represented by this NavigationData. * @throws mitk::Exception in case the transformation is invalid (only case: quaternion is zero) */ mitk::NavigationData::Pointer GetInverse() const; /** Compose with another NavigationData * * This method composes self with another NavigationData of the * same dimension, modifying self to be the composition of self * and other. If the argument pre is true, then other is * precomposed with self; that is, the resulting transformation * consists of first applying other to the source, followed by * self. If pre is false or omitted, then other is post-composed * with self; that is the resulting transformation consists of * first applying self to the source, followed by other. */ void Compose(const mitk::NavigationData::Pointer n, const bool pre = false); protected: mitkCloneMacro(Self); NavigationData(); /* * Copy constructor internally used. */ NavigationData(const mitk::NavigationData& toCopy); /** * Creates a NavigationData object from an affineTransform3D. * Caution: NavigationData doesn't support spacing, only translation and rotation. If the affine * transform includes spacing it cannot be converted to a NavigationData and an exception is thrown. + * @param affineTransform3D * @param checkForRotationMatrix if this is true, the rotation matrix coming from the affineTransform is checked * for being a rotation matrix. If it isn't, an exception is thrown. Disable this check by * setting checkForRotationMatrix to false. * * @throws mitkException if checkForRotationMatrix is true and a non rotation matrix was introduced by * AffineTransform. */ NavigationData(mitk::AffineTransform3D::Pointer affineTransform3D, const bool checkForRotationMatrix = true); ~NavigationData() override; /** * \brief holds the position part of the tracking data */ PositionType m_Position; /** * \brief holds the orientation part of the tracking data */ OrientationType m_Orientation; /** * \brief A 6x6 covariance matrix parameterizing the Gaussian error * distribution of the measured position and orientation. * * The hasPosition/hasOrientation fields define which entries * are valid. */ CovarianceMatrixType m_CovErrorMatrix; ///< holds the error characterization of the position and orientation /** * \brief defines if position part of m_CovErrorMatrix is valid */ bool m_HasPosition; /** * \brief defines if orientation part of m_CovErrorMatrix is valid */ bool m_HasOrientation; /** * \brief defines if the object contains valid values */ bool m_DataValid; /** * \brief contains the time at which the tracking data was recorded */ TimeStampType m_IGTTimeStamp; /** * \brief name of the navigation data */ std::string m_Name; private: void ResetCovarianceValidity(); // pre = false static mitk::NavigationData::Pointer getComposition(const mitk::NavigationData::Pointer nd1, const mitk::NavigationData::Pointer nd2); }; /** * @brief Equal A function comparing two navigation data objects for beeing equal in meta- and imagedata * * @ingroup MITKTestingAPI * * Following aspects are tested for equality: * - position * - orientation * - other members and flags of the class * * @param rightHandSide An NavigationData to be compared * @param leftHandSide An NavigationData to be compared * @param eps Tolarence for comparison. You can use mitk::eps in most cases. * @param verbose Flag indicating if the user wants detailed console output or not. * @return true, if all subsequent comparisons are true, false otherwise */ MITKIGTBASE_EXPORT bool Equal( const mitk::NavigationData& leftHandSide, const mitk::NavigationData& rightHandSide, ScalarType eps = mitk::eps, bool verbose = false ); } // namespace mitk #endif /* MITKNAVIGATIONDATA_H_HEADER_INCLUDED_ */ diff --git a/Modules/LegacyIO/mitkImageWriter.h b/Modules/LegacyIO/mitkImageWriter.h index e9f67d016d..67033cd7c9 100644 --- a/Modules/LegacyIO/mitkImageWriter.h +++ b/Modules/LegacyIO/mitkImageWriter.h @@ -1,171 +1,171 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef _MITK_IMAGE_WRITER__H_ #define _MITK_IMAGE_WRITER__H_ #include #include namespace mitk { class Image; /** * @brief Writer for mitk::Image * * Uses the given extension (SetExtension) to decide the format to write * (.mhd is default, .pic, .tif, .png, .jpg supported yet). * @ingroup MitkLegacyIOModule * @deprecatedSince{2014_10} Use mitk::IOUtils or mitk::FileWriterRegistry instead. */ class MITKLEGACYIO_EXPORT ImageWriter : public mitk::FileWriterWithInformation { public: mitkClassMacro(ImageWriter, mitk::FileWriter); itkFactorylessNewMacro(Self); itkCloneMacro(Self); mitkWriterMacro; /** * Sets the filename of the file to write. - * @param _arg the name of the file to write. + * @param fileName the name of the file to write. */ void SetFileName(const char *fileName) override; virtual void SetFileName(const std::string &fileName); /** * @returns the name of the file to be written to disk. */ itkGetStringMacro(FileName); /** * \brief Explicitly set the extension to be added to the filename. - * @param _arg to be added to the filename, including a "." + * @param extension Extension to be added to the filename, including a "." * (e.g., ".mhd"). */ virtual void SetExtension(const char *extension); virtual void SetExtension(const std::string &extension); /** * \brief Get the extension to be added to the filename. * @returns the extension to be added to the filename (e.g., * ".mhd"). */ itkGetStringMacro(Extension); /** * \brief Set the extension to be added to the filename to the default */ void SetDefaultExtension(); /** * @warning multiple write not (yet) supported */ itkSetStringMacro(FilePrefix); /** * @warning multiple write not (yet) supported */ itkGetStringMacro(FilePrefix); /** * @warning multiple write not (yet) supported */ itkSetStringMacro(FilePattern); /** * @warning multiple write not (yet) supported */ itkGetStringMacro(FilePattern); /** * Sets the 0'th input object for the filter. * @param input the first input for the filter. */ void SetInput(mitk::Image *input); //##Documentation //## @brief Return the possible file extensions for the data type associated with the writer std::vector GetPossibleFileExtensions() override; std::string GetSupportedBaseData() const override; /** * @brief Return the extension to be added to the filename. */ std::string GetFileExtension() override; /** * @brief Check if the Writer can write the Content of the */ bool CanWriteDataType(DataNode *) override; /** * @brief Return the MimeType of the saved File. */ std::string GetWritenMIMEType() override; using Superclass::SetInput; /** * @brief Set the DataTreenode as Input. Important: The Writer always have a SetInput-Function. */ virtual void SetInput(DataNode *); /** * @returns the 0'th input object of the filter. */ const mitk::Image *GetInput(); // FileWriterWithInformation methods const char *GetDefaultFilename() override; const char *GetFileDialogPattern() override; const char *GetDefaultExtension() override; bool CanWriteBaseDataType(BaseData::Pointer data) override; void DoWrite(BaseData::Pointer data) override; void SetUseCompression(bool useCompression); protected: /** * Constructor. */ ImageWriter(); /** * Virtual destructor. */ ~ImageWriter() override; void GenerateData() override; virtual void WriteByITK(mitk::Image *image, const std::string &fileName); std::string m_FileName; std::string m_FileNameWithoutExtension; std::string m_FilePrefix; std::string m_FilePattern; std::string m_Extension; std::string m_MimeType; bool m_UseCompression; }; } #endif //_MITK_IMAGE_WRITER__H_ diff --git a/Modules/LegacyIO/mitkPointSetWriter.h b/Modules/LegacyIO/mitkPointSetWriter.h index 0789e8c685..f848cbd98c 100644 --- a/Modules/LegacyIO/mitkPointSetWriter.h +++ b/Modules/LegacyIO/mitkPointSetWriter.h @@ -1,254 +1,254 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef _MITK_POINT_SET_WRITER__H_ #define _MITK_POINT_SET_WRITER__H_ #include #include #include #include namespace mitk { /** * @brief XML-based writer for mitk::PointSets * * XML-based writer for mitk::PointSets. Multiple PointSets can be written in * a single XML file by simply setting multiple inputs to the filter. * Writing of multiple XML files according to a given filename pattern is not * yet supported. * * @ingroup MitkLegacyIOModule * * @deprecatedSince{2014_10} Use mitk::IOUtils or mitk::FileReaderRegistry instead. */ class MITKLEGACYIO_EXPORT PointSetWriter : public mitk::FileWriter { public: mitkClassMacro(PointSetWriter, mitk::FileWriter); mitkWriterMacro; itkFactorylessNewMacro(Self); itkCloneMacro(Self); typedef mitk::PointSet InputType; typedef InputType::Pointer InputTypePointer; /** * Sets the filename of the file to write. - * @param FileName the name of the file to write. */ itkSetStringMacro(FileName); /** * @returns the name of the file to be written to disk. */ itkGetStringMacro(FileName); /** * @warning multiple write not (yet) supported */ itkSetStringMacro(FilePrefix); /** * @warning multiple write not (yet) supported */ itkGetStringMacro(FilePrefix); /** * @warning multiple write not (yet) supported */ itkSetStringMacro(FilePattern); /** * @warning multiple write not (yet) supported */ itkGetStringMacro(FilePattern); /** * Sets the 0'th input object for the filter. * @param input the first input for the filter. */ void SetInput(InputType *input); /** * Sets the n'th input object for the filter. If num is * larger than GetNumberOfInputs() the number of inputs is * resized appropriately. + * @param num * @param input the n'th input for the filter. */ void SetInput(const unsigned int &num, InputType *input); /** * @returns the 0'th input object of the filter. */ PointSet *GetInput(); /** * @param num the index of the desired output object. * @returns the n'th input object of the filter. */ PointSet *GetInput(const unsigned int &num); /** * @brief Return the possible file extensions for the data type associated with the writer */ std::vector GetPossibleFileExtensions() override; std::string GetSupportedBaseData() const override; /** * @brief Return the extension to be added to the filename. */ std::string GetFileExtension() override; /** * @brief Check if the Writer can write the Content of the */ bool CanWriteDataType(DataNode *) override; /** * @brief Return the MimeType of the saved File. */ std::string GetWritenMIMEType() override; using mitk::FileWriter::SetInput; /** * @brief Set the DataTreenode as Input. Important: The Writer always have a SetInput-Function. */ virtual void SetInput(DataNode *); /** * @returns whether the last write attempt was successful or not. */ bool GetSuccess() const; protected: /** * Constructor. */ PointSetWriter(); /** * Virtual destructor. */ ~PointSetWriter() override; /** * Writes the XML file */ void GenerateData() override; /** * Resizes the number of inputs of the writer. * The inputs are initialized by empty PointSets * @param num the new number of inputs */ virtual void ResizeInputs(const unsigned int &num); /** * Converts an arbitrary type to a string. The type has to * support the << operator. This works fine at least for integral * data types as float, int, long etc. * @param value the value to convert * @returns the string representation of value */ template std::string ConvertToString(T value); /** * Writes an XML representation of the given point set to * an outstream. The XML-Header an root node is not included! * @param pointSet the point set to be converted to xml * @param out the stream to write to. */ void WriteXML(mitk::PointSet *pointSet, std::ofstream &out); /** * Writes an standard xml header to the given stream. * @param file the stream in which the header is written. */ void WriteXMLHeader(std::ofstream &file); /** Write a start element tag */ void WriteStartElement(const char *const tag, std::ofstream &file); /** * Write an end element tag * End-Elements following character data should pass indent = false. */ void WriteEndElement(const char *const tag, std::ofstream &file, const bool &indent = true); /** Write character data inside a tag. */ void WriteCharacterData(const char *const data, std::ofstream &file); /** Write a start element tag */ void WriteStartElement(std::string &tag, std::ofstream &file); /** Write an end element tag */ void WriteEndElement(std::string &tag, std::ofstream &file, const bool &indent = true); /** Write character data inside a tag. */ void WriteCharacterData(std::string &data, std::ofstream &file); /** Writes empty spaces to the stream according to m_IndentDepth and m_Indent */ void WriteIndent(std::ofstream &file); std::string m_FileName; std::string m_FilePrefix; std::string m_FilePattern; std::string m_Extension; std::string m_MimeType; unsigned int m_IndentDepth; unsigned int m_Indent; bool m_Success; public: static const char *XML_POINT_SET; static const char *XML_TIME_SERIES; static const char *XML_TIME_SERIES_ID; static const char *XML_POINT_SET_FILE; static const char *XML_FILE_VERSION; static const char *XML_POINT; static const char *XML_SPEC; static const char *XML_ID; static const char *XML_X; static const char *XML_Y; static const char *XML_Z; static const char *VERSION_STRING; }; } #endif diff --git a/Modules/MatchPointRegistration/include/mitkRegEvaluationMapper2D.h b/Modules/MatchPointRegistration/include/mitkRegEvaluationMapper2D.h index 934346fb63..54e35034e9 100644 --- a/Modules/MatchPointRegistration/include/mitkRegEvaluationMapper2D.h +++ b/Modules/MatchPointRegistration/include/mitkRegEvaluationMapper2D.h @@ -1,245 +1,248 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITK_REG_EVALUATION_MAPPER_2D_H #define MITK_REG_EVALUATION_MAPPER_2D_H //MatchPoint #include #include "mitkRegEvaluationObject.h" //MITK #include //MITK Rendering #include "mitkBaseRenderer.h" #include "mitkVtkMapper.h" #include "mitkExtractSliceFilter.h" //VTK #include #include //MITK #include "MitkMatchPointRegistrationExports.h" class vtkActor; class vtkPolyDataMapper; class vtkPlaneSource; class vtkImageData; class vtkLookupTable; class vtkImageExtractComponents; class vtkImageReslice; class vtkImageChangeInformation; class vtkPoints; class vtkMitkThickSlicesFilter; class vtkPolyData; class vtkMitkApplyLevelWindowToRGBFilter; class vtkMitkLevelWindowFilter; namespace mitk { /** \brief Mapper to resample and display 2D slices of registration evaluation visualization. * \ingroup Mapper */ class MITKMATCHPOINTREGISTRATION_EXPORT RegEvaluationMapper2D : public VtkMapper { public: /** Standard class typedefs. */ mitkClassMacro( RegEvaluationMapper2D,VtkMapper ); /** Method for creation through the object factory. */ itkFactorylessNewMacro(Self); itkCloneMacro(Self); const mitk::DataNode* GetTargetNode(void); const mitk::DataNode* GetMovingNode(void); /** \brief Get the target image to map */ const mitk::Image *GetTargetImage(void); /** \brief Get the moving image to map */ const mitk::Image *GetMovingImage(void); /** \brief Get the target image to map */ const mitk::MAPRegistrationWrapper *GetRegistration(void); /** \brief Checks whether this mapper needs to update itself and generate * data. */ void Update(mitk::BaseRenderer * renderer) override; //### methods of MITK-VTK rendering pipeline vtkProp* GetVtkProp(mitk::BaseRenderer* renderer) override; //### end of methods of MITK-VTK rendering pipeline /** \brief Internal class holding the mapper, actor, etc. for each of the 3 2D render windows */ /** * To render transveral, coronal, and sagittal, the mapper is called three times. * For performance reasons, the corresponding data for each view is saved in the * internal helper class LocalStorage. This allows rendering n views with just * 1 mitkMapper using n vtkMapper. * */ class MITKMATCHPOINTREGISTRATION_EXPORT LocalStorage : public mitk::Mapper::BaseLocalStorage { public: /** \brief Actor of a 2D render window. */ vtkSmartPointer m_Actor; vtkSmartPointer m_Actors; /** \brief Mapper of a 2D render window. */ vtkSmartPointer m_Mapper; /** \brief Current slice of a 2D render window.*/ vtkSmartPointer m_EvaluationImage; /** \brief Empty vtkPolyData that is set when rendering geometry does not * intersect the image geometry. * \warning This member variable is set to nullptr, * if no image geometry is inside the plane geometry * of the respective render window. Any user of this * slice has to check whether it is set to nullptr! */ vtkSmartPointer m_EmptyPolyData; /** \brief Plane on which the slice is rendered as texture. */ vtkSmartPointer m_Plane; /** \brief The texture which is used to render the current slice. */ vtkSmartPointer m_Texture; /** \brief The lookuptables for colors and level window */ vtkSmartPointer m_ColorLookupTable; vtkSmartPointer m_DefaultLookupTable; /** \brief The actual reslicer (one per renderer) */ mitk::ExtractSliceFilter::Pointer m_Reslicer; /** part of the target image that is relevant for the rendering*/ mitk::Image::Pointer m_slicedTargetImage; /** part of the moving image mapped into the slicedTargetImage geometry*/ mitk::Image::Pointer m_slicedMappedImage; /** \brief Timestamp of last update of stored data. */ itk::TimeStamp m_LastUpdateTime; /** \brief mmPerPixel relation between pixel and mm. (World spacing).*/ mitk::ScalarType* m_mmPerPixel; /** \brief This filter is used to apply the level window to target image. */ vtkSmartPointer m_TargetLevelWindowFilter; /** \brief This filter is used to apply the level window to moving image. */ vtkSmartPointer m_MappedLevelWindowFilter; vtkSmartPointer m_TargetExtractFilter; vtkSmartPointer m_MappedExtractFilter; /** \brief Default constructor of the local storage. */ LocalStorage(); /** \brief Default deconstructor of the local storage. */ ~LocalStorage() override; }; /** \brief The LocalStorageHandler holds all (three) LocalStorages for the three 2D render windows. */ mitk::LocalStorageHandler m_LSH; /** \brief Get the LocalStorage corresponding to the current renderer. */ LocalStorage* GetLocalStorage(mitk::BaseRenderer* renderer); /** \brief Set the default properties for general image rendering. */ static void SetDefaultProperties(mitk::DataNode* node, mitk::BaseRenderer* renderer = nullptr, bool overwrite = false); protected: /** \brief Transforms the actor to the actual position in 3D. * \param renderer The current renderer corresponding to the render window. */ void TransformActor(mitk::BaseRenderer* renderer); /** \brief Generates a plane according to the size of the resliced image in milimeters. - * - * \image html texturedPlane.png * * In VTK a vtkPlaneSource is defined through three points. The origin and two * points defining the axes of the plane (see VTK documentation). The origin is * set to (xMin; yMin; Z), where xMin and yMin are the minimal bounds of the * resliced image in space. Z is relevant for blending and the layer property. * The center of the plane (C) is also the center of the view plane (cf. the image above). * * \note For the standard MITK view with three 2D render windows showing three * different slices, three such planes are generated. All these planes are generated * in the XY-plane (even if they depict a YZ-slice of the volume). * */ void GeneratePlane(mitk::BaseRenderer* renderer, double planeBounds[6]); /** Default constructor */ RegEvaluationMapper2D(); /** Default deconstructor */ ~RegEvaluationMapper2D() override; /** \brief Does the actual resampling, without rendering the image yet. * All the data is generated inside this method. The vtkProp (or Actor) * is filled with content (i.e. the resliced image). * * After generation, a 4x4 transformation matrix(t) of the current slice is obtained * from the vtkResliceImage object via GetReslicesAxis(). This matrix is * applied to each textured plane (actor->SetUserTransform(t)) to transform everything * to the actual 3D position (cf. the following image). * * \image html cameraPositioning3D.png * */ void GenerateDataForRenderer(mitk::BaseRenderer *renderer) override; void PrepareContour( mitk::DataNode* datanode, LocalStorage * localStorage ); void PrepareDifference( LocalStorage * localStorage ); void PrepareWipe(mitk::DataNode* datanode, LocalStorage * localStorage, const Point2D& currentIndex2D); void PrepareCheckerBoard( mitk::DataNode* datanode, LocalStorage * localStorage ); void PrepareColorBlend( LocalStorage * localStorage ); void PrepareBlend( mitk::DataNode* datanode, LocalStorage * localStorage ); /** \brief This method uses the vtkCamera clipping range and the layer property * to calcualte the depth of the object (e.g. image or contour). The depth is used * to keep the correct order for the final VTK rendering.*/ float CalculateLayerDepth(mitk::BaseRenderer* renderer); /** \brief This method applies (or modifies) the lookuptable for all types of images. * \warning To use the lookup table, the property 'Lookup Table' must be set and a 'Image Rendering.Mode' * which uses the lookup table must be set. */ void ApplyLookuptable(mitk::BaseRenderer* renderer, const mitk::DataNode* dataNode, vtkMitkLevelWindowFilter* levelFilter); /** * @brief ApplyLevelWindow Apply the level window for the given renderer. * \warning To use the level window, the property 'LevelWindow' must be set and a 'Image Rendering.Mode' which uses the level window must be set. * @param renderer Level window for which renderer? + * @param dataNode + * @param levelFilter */ void ApplyLevelWindow(mitk::BaseRenderer *renderer, const mitk::DataNode* dataNode, vtkMitkLevelWindowFilter* levelFilter); /** \brief Set the opacity of the actor. */ void ApplyOpacity( mitk::BaseRenderer* renderer ); /** * \brief Calculates whether the given rendering geometry intersects the * given SlicedGeometry3D. * * This method checks if the given PlaneGeometry intersects the given * SlicedGeometry3D. It calculates the distance of the PlaneGeometry to all * 8 cornerpoints of the SlicedGeometry3D. If all distances have the same * sign (all positive or all negative) there is no intersection. * If the distances have different sign, there is an intersection. + * + * \param renderingGeometry + * \param imageGeometry **/ bool RenderingGeometryIntersectsImage( const PlaneGeometry* renderingGeometry, SlicedGeometry3D* imageGeometry ); }; } // namespace mitk #endif /* MITKRegEvaluationMapper2D_H_HEADER_INCLUDED_C10E906E */ diff --git a/Modules/MatchPointRegistration/include/mitkRegistrationHelper.h b/Modules/MatchPointRegistration/include/mitkRegistrationHelper.h index ff3f1c4c5d..1eba8b2551 100644 --- a/Modules/MatchPointRegistration/include/mitkRegistrationHelper.h +++ b/Modules/MatchPointRegistration/include/mitkRegistrationHelper.h @@ -1,91 +1,91 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef _mitkRegistrationHelper_h #define _mitkRegistrationHelper_h //ITK #include "itkScalableAffineTransform.h" //MatchPoint #include "mapRegistrationAlgorithmBase.h" #include "mapRegistration.h" //MITK #include #include #include //MITK #include "MitkMatchPointRegistrationExports.h" #include "mitkMAPRegistrationWrapper.h" namespace mitk { /*! \brief MITKRegistrationHelper \warning This class is not yet documented. Use "git blame" and ask the author to provide basic documentation. */ class MITKMATCHPOINTREGISTRATION_EXPORT MITKRegistrationHelper { public: typedef ::itk::ScalableAffineTransform< ::mitk::ScalarType,3 > Affine3DTransformType; typedef ::map::core::Registration<3,3> Registration3DType; typedef ::map::core::RegistrationBase RegistrationBaseType; /** Extracts the affine transformation, if possible, of the selected kernel. @param wrapper Pointer to the registration that is target of the extraction @param inverseKernel Indicates from which kernel the matrix should be extract. True: inverse kernel, False: direct kernel. @return Pointer to the extracted transform. If it is not possible to convert the kernel into an affine transform a null pointer is returned. @pre wrapper must point to a valid instance. @pre wrapper must be a 3D-3D registration.*/ static Affine3DTransformType::Pointer getAffineMatrix(const mitk::MAPRegistrationWrapper* wrapper, bool inverseKernel); static Affine3DTransformType::Pointer getAffineMatrix(const RegistrationBaseType* registration, bool inverseKernel); static bool is3D(const mitk::MAPRegistrationWrapper* wrapper); static bool is3D(const RegistrationBaseType* regBase); /** Checks if the passed Node contains a MatchPoint registration - @param Pointer to the node to be checked.* + @param node Pointer to the node to be checked.* @return true: node contains a MAPRegistrationWrapper. false: "node" does not point to a valid instance or does not contain a registration wrapper.*/; static bool IsRegNode(const mitk::DataNode* node); /** Returns a node predicate that identifies registration nodes.*/ static NodePredicateBase::ConstPointer RegNodePredicate(); /** Returns a node predicate that identifies image nodes.*/ static NodePredicateBase::ConstPointer ImageNodePredicate(); /** Returns a node predicate that identifies segmentation/mask nodes.*/ static NodePredicateBase::ConstPointer MaskNodePredicate(); /** Returns a node predicate that identifies point set nodes.*/ static NodePredicateBase::ConstPointer PointSetNodePredicate(); private: typedef ::map::core::Registration<3,3>::DirectMappingType RegistrationKernel3DBase; static Affine3DTransformType::Pointer getAffineMatrix(const RegistrationKernel3DBase& kernel); MITKRegistrationHelper(); ~MITKRegistrationHelper(); MITKRegistrationHelper& operator = (const MITKRegistrationHelper&); MITKRegistrationHelper(const MITKRegistrationHelper&); }; } #endif diff --git a/Modules/Multilabel/mitkLabelSetImageVtkMapper2D.h b/Modules/Multilabel/mitkLabelSetImageVtkMapper2D.h index 676305caf2..884388bfa9 100644 --- a/Modules/Multilabel/mitkLabelSetImageVtkMapper2D.h +++ b/Modules/Multilabel/mitkLabelSetImageVtkMapper2D.h @@ -1,241 +1,241 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef __mitkLabelSetImageVtkMapper2D_H_ #define __mitkLabelSetImageVtkMapper2D_H_ // MITK #include "MitkMultilabelExports.h" #include "mitkCommon.h" // MITK Rendering #include "mitkBaseRenderer.h" #include "mitkExtractSliceFilter.h" #include "mitkLabelSetImage.h" #include "mitkVtkMapper.h" // VTK #include class vtkActor; class vtkPolyDataMapper; class vtkPlaneSource; class vtkImageData; class vtkLookupTable; class vtkImageReslice; class vtkPoints; class vtkMitkThickSlicesFilter; class vtkPolyData; class vtkMitkLevelWindowFilter; class vtkNeverTranslucentTexture; namespace mitk { /** \brief Mapper to resample and display 2D slices of a 3D labelset image. * * Properties that can be set for labelset images and influence this mapper are: * * - \b "labelset.contour.active": (BoolProperty) whether to show only the active label as a contour or not * - \b "labelset.contour.width": (FloatProperty) line width of the contour * The default properties are: * - \b "labelset.contour.active", mitk::BoolProperty::New( true ), renderer, overwrite ) * - \b "labelset.contour.width", mitk::FloatProperty::New( 2.0 ), renderer, overwrite ) * \ingroup Mapper */ class MITKMULTILABEL_EXPORT LabelSetImageVtkMapper2D : public VtkMapper { public: /** Standard class typedefs. */ mitkClassMacro(LabelSetImageVtkMapper2D, VtkMapper); /** Method for creation through the object factory. */ itkNewMacro(Self); /** \brief Get the Image to map */ const mitk::Image *GetInput(void); /** \brief Checks whether this mapper needs to update itself and generate * data. */ void Update(mitk::BaseRenderer *renderer) override; //### methods of MITK-VTK rendering pipeline vtkProp *GetVtkProp(mitk::BaseRenderer *renderer) override; //### end of methods of MITK-VTK rendering pipeline /** \brief Internal class holding the mapper, actor, etc. for each of the 3 2D render windows */ /** * To render transversal, coronal, and sagittal, the mapper is called three times. * For performance reasons, the corresponding data for each view is saved in the * internal helper class LocalStorage. This allows rendering n views with just * 1 mitkMapper using n vtkMapper. * */ class MITKMULTILABEL_EXPORT LocalStorage : public mitk::Mapper::BaseLocalStorage { public: vtkSmartPointer m_Actors; std::vector> m_LayerActorVector; std::vector> m_LayerMapperVector; std::vector> m_ReslicedImageVector; std::vector> m_LayerTextureVector; vtkSmartPointer m_EmptyPolyData; vtkSmartPointer m_Plane; std::vector m_ReslicerVector; vtkSmartPointer m_OutlinePolyData; /** \brief An actor for the outline */ vtkSmartPointer m_OutlineActor; /** \brief An actor for the outline shadow*/ vtkSmartPointer m_OutlineShadowActor; /** \brief A mapper for the outline */ vtkSmartPointer m_OutlineMapper; /** \brief Timestamp of last update of stored data. */ itk::TimeStamp m_LastDataUpdateTime; /** \brief Timestamp of last update of a property. */ itk::TimeStamp m_LastPropertyUpdateTime; /** \brief mmPerPixel relation between pixel and mm. (World spacing).*/ mitk::ScalarType *m_mmPerPixel; int m_NumberOfLayers; /** \brief This filter is used to apply the level window to Grayvalue and RBG(A) images. */ // vtkSmartPointer m_LevelWindowFilter; std::vector> m_LevelWindowFilterVector; /** \brief Default constructor of the local storage. */ LocalStorage(); /** \brief Default deconstructor of the local storage. */ ~LocalStorage() override; }; /** \brief The LocalStorageHandler holds all (three) LocalStorages for the three 2D render windows. */ mitk::LocalStorageHandler m_LSH; /** \brief Get the LocalStorage corresponding to the current renderer. */ LocalStorage *GetLocalStorage(mitk::BaseRenderer *renderer); /** \brief Set the default properties for general image rendering. */ static void SetDefaultProperties(mitk::DataNode *node, mitk::BaseRenderer *renderer = nullptr, bool overwrite = false); /** \brief This method switches between different rendering modes (e.g. use a lookup table or a transfer function). * Detailed documentation about the modes can be found here: \link mitk::RenderingModeProperty \endlink */ void ApplyRenderingMode(mitk::BaseRenderer *renderer); protected: /** \brief Transforms the actor to the actual position in 3D. * \param renderer The current renderer corresponding to the render window. */ void TransformActor(mitk::BaseRenderer *renderer); /** \brief Generates a plane according to the size of the resliced image in milimeters. - * - * \image html texturedPlane.png * * In VTK a vtkPlaneSource is defined through three points. The origin and two * points defining the axes of the plane (see VTK documentation). The origin is * set to (xMin; yMin; Z), where xMin and yMin are the minimal bounds of the * resliced image in space. Z is relevant for blending and the layer property. * The center of the plane (C) is also the center of the view plane (cf. the image above). * * \note For the standard MITK view with three 2D render windows showing three * different slices, three such planes are generated. All these planes are generated * in the XY-plane (even if they depict a YZ-slice of the volume). * */ void GeneratePlane(mitk::BaseRenderer *renderer, double planeBounds[6]); /** \brief Generates a vtkPolyData object containing the outline of a given binary slice. - \param renderer: Pointer to the renderer containing the needed information + \param renderer Pointer to the renderer containing the needed information + \param image + \param pixelValue \note This code is based on code from the iil library. */ vtkSmartPointer CreateOutlinePolyData(mitk::BaseRenderer *renderer, vtkImageData *image, int pixelValue = 1); /** Default constructor */ LabelSetImageVtkMapper2D(); /** Default deconstructor */ ~LabelSetImageVtkMapper2D() override; /** \brief Does the actual resampling, without rendering the image yet. * All the data is generated inside this method. The vtkProp (or Actor) * is filled with content (i.e. the resliced image). * * After generation, a 4x4 transformation matrix(t) of the current slice is obtained * from the vtkResliceImage object via GetReslicesAxis(). This matrix is * applied to each textured plane (actor->SetUserTransform(t)) to transform everything * to the actual 3D position (cf. the following image). * * \image html cameraPositioning3D.png * */ void GenerateDataForRenderer(mitk::BaseRenderer *renderer) override; /** \brief This method uses the vtkCamera clipping range and the layer property * to calcualte the depth of the object (e.g. image or contour). The depth is used * to keep the correct order for the final VTK rendering.*/ float CalculateLayerDepth(mitk::BaseRenderer *renderer); /** \brief This method applies (or modifies) the lookuptable for all types of images. * \warning To use the lookup table, the property 'Lookup Table' must be set and a 'Image Rendering.Mode' * which uses the lookup table must be set. */ void ApplyLookuptable(mitk::BaseRenderer *renderer, int layer); /** \brief This method applies a color transfer function. * Internally, a vtkColorTransferFunction is used. This is usefull for coloring continous * images (e.g. float) * \warning To use the color transfer function, the property 'Image Rendering.Transfer Function' must be set and a * 'Image Rendering.Mode' which uses the color transfer function must be set. */ void ApplyColorTransferFunction(mitk::BaseRenderer *renderer); /** * @brief ApplyLevelWindow Apply the level window for the given renderer. * \warning To use the level window, the property 'LevelWindow' must be set and a 'Image Rendering.Mode' which uses * the level window must be set. * @param renderer Level window for which renderer? */ void ApplyLevelWindow(mitk::BaseRenderer *renderer); /** \brief Set the color of the image/polydata */ void ApplyColor(mitk::BaseRenderer *renderer, const mitk::Color &color); /** \brief Set the opacity of the actor. */ void ApplyOpacity(mitk::BaseRenderer *renderer, int layer); /** * \brief Calculates whether the given rendering geometry intersects the * given SlicedGeometry3D. * * This method checks if the given Geometry2D intersects the given * SlicedGeometry3D. It calculates the distance of the Geometry2D to all * 8 cornerpoints of the SlicedGeometry3D. If all distances have the same * sign (all positive or all negative) there is no intersection. * If the distances have different sign, there is an intersection. **/ bool RenderingGeometryIntersectsImage(const PlaneGeometry *renderingGeometry, SlicedGeometry3D *imageGeometry); }; } // namespace mitk #endif // __mitkLabelSetImageVtkMapper2D_H_ diff --git a/Modules/OpenCL/mitkOclBinaryThresholdImageFilter.h b/Modules/OpenCL/mitkOclBinaryThresholdImageFilter.h index 9070125f86..dada1676d0 100644 --- a/Modules/OpenCL/mitkOclBinaryThresholdImageFilter.h +++ b/Modules/OpenCL/mitkOclBinaryThresholdImageFilter.h @@ -1,121 +1,121 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef _MITKOCLBINARYTHRESHOLDIMAGEFILTER_H_ #define _MITKOCLBINARYTHRESHOLDIMAGEFILTER_H_ #include "mitkOclImageToImageFilter.h" #include namespace mitk { class OclImageToImageFilter; /** Documentation * * \brief The OclBinaryThresholdImageFilter computes a binary segmentation based on given threshold values. * * The filter requires two threshold values ( the upper and the lower threshold ) and two image values ( inside and outside ). The resulting voxel of the segmentation image is assigned the inside value 1 if the image value is between the given thresholds and the outside value otherwise. */ class MITKOPENCL_EXPORT OclBinaryThresholdImageFilter : public OclImageToImageFilter, public itk::Object { public: mitkClassMacroItkParent(OclBinaryThresholdImageFilter, itk::Object); itkNewMacro(Self); /** * @brief SetInput Set the input image. Only 3D images are supported for now. * @param image a 3D image. * @throw mitk::Exception if the dimesion is not 3. */ void SetInput(Image::Pointer image); /** Update the filter */ void Update(); /** Set the lower threshold - @param thr Threshold value + @param lowerThreshold Threshold value */ void SetLowerThreshold( int lowerThreshold ) { this->m_LowerThreshold = lowerThreshold; } /** Set the upper threshold - @param thr Threshold value + @param upperThreshold Threshold value */ void SetUpperThreshold( int upperThreshold ) { this->m_UpperThreshold = upperThreshold; } /** Set the outside value - @param val The outside value + @param outsideValue The outside value */ void SetOutsideValue( int outsideValue ) { this->m_OutsideValue = outsideValue; } /** Set the inside value - @param val The inside value + @param insideValue The inside value */ void SetInsideValue( int insideValue ) { this->m_InsideValue = insideValue; } protected: /** Constructor */ OclBinaryThresholdImageFilter(); /** Destructor */ virtual ~OclBinaryThresholdImageFilter(); /** Initialize the filter */ bool Initialize(); void Execute(); mitk::PixelType GetOutputType() { return mitk::MakeScalarPixelType(); } int GetBytesPerElem() { return sizeof(unsigned char); } virtual us::Module* GetModule(); private: /** The OpenCL kernel for the filter */ cl_kernel m_ckBinaryThreshold; int m_LowerThreshold; int m_UpperThreshold; int m_InsideValue; int m_OutsideValue; }; } #endif diff --git a/Modules/OpenCL/mitkOclDataSetFilter.h b/Modules/OpenCL/mitkOclDataSetFilter.h index b4e660c4bb..7bda3d545a 100644 --- a/Modules/OpenCL/mitkOclDataSetFilter.h +++ b/Modules/OpenCL/mitkOclDataSetFilter.h @@ -1,65 +1,67 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef __mitkOclDataSetFilter_h #define __mitkOclDataSetFilter_h #include "mitkOclFilter.h" #include "mitkOclDataSet.h" #define FILTER_UCHAR 0 #define FILTER_SHORT 1 namespace mitk { class OclFilter; class OclDataSetFilter; /** * \brief The OclDataSetFilter is the topmost class for all filter which take DataSets as input. * * The input DataSet can be intialized via an oclDataSet or a pointer to the data * This makes it possible to create a filter pipeline of GPU-based filters * and to bind this part into the CPU (ITK) filter pipeline. */ class MITKOPENCL_EXPORT OclDataSetFilter: public OclFilter { public: /** * @brief SetInput SetInput Set the input DataSet (as mitk::OclDataSet). * @param DataSet The DataSet in mitk::OclDataSet. */ void SetInput(mitk::OclDataSet::Pointer DataSet); /** * @brief SetInput Set the input DataSet (as a pointer to the data). * @param DataSet The DataSet in mitk::OclDataSet. + * @param size + * @param BpE */ void SetInput(void* DataSet, unsigned int size, unsigned int BpE); /** * @brief SetInput Set the input DataSet (as mitk::Image). - * @param DataSet The DataSet in mitk::OclDataSet. + * @param image The DataSet in mitk::OclDataSet. */ void SetInput(mitk::Image::Pointer image); protected: OclDataSetFilter(); virtual ~OclDataSetFilter(); /** The input DataSet */ mitk::OclDataSet::Pointer m_Input; unsigned int m_CurrentSize; }; } #endif // __mitkOclDataSetFilter_h diff --git a/Modules/OpenCL/mitkOclDataSetToDataSetFilter.h b/Modules/OpenCL/mitkOclDataSetToDataSetFilter.h index d1ca3fa76e..842bc0df47 100644 --- a/Modules/OpenCL/mitkOclDataSetToDataSetFilter.h +++ b/Modules/OpenCL/mitkOclDataSetToDataSetFilter.h @@ -1,77 +1,80 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef __mitkOclDataSetToDataSetFilter_h #define __mitkOclDataSetToDataSetFilter_h #include "mitkOclDataSetFilter.h" namespace mitk { class OclDataSetFilter; class OclDataSetToDataSetFilter; /** @class OclDataSetToDataSetFilter * @brief The OclDataSetToDataSetFilter is the base class for all OpenCL DataSet filter generating DataSets. */ class MITKOPENCL_EXPORT OclDataSetToDataSetFilter: public OclDataSetFilter { public: /*! * \brief Returns an pointer to the filtered data. */ void* GetOutput(); /*! * \brief Returns a pointer to the graphics memory. * * Use this method when executing two and more filters on the GPU for fast access. * This method does not copy the data to RAM. It returns only a pointer. */ mitk::OclDataSet::Pointer GetGPUOutput(); protected: /** * @brief OclDataSetToDataSetFilter Default constructor. */ OclDataSetToDataSetFilter(); /** @brief Destructor */ virtual ~OclDataSetToDataSetFilter(); /** Output DataSet */ mitk::OclDataSet::Pointer m_Output; /** @brief (Virtual) method Update() to be implemented in derived classes. */ virtual void Update() = 0; /** * @brief InitExec Initialize the execution * @param ckKernel The GPU kernel. + * @param dimensions + * @param outputDataSize + * @param outputBpE * @throws mitk::Exception if something goes wrong. * @return True for success. */ bool InitExec(cl_kernel ckKernel, unsigned int* dimensions, size_t outputDataSize, unsigned int outputBpE); bool InitExecNoInput(cl_kernel ckKernel, unsigned int* dimensions, size_t outputDataSize, unsigned int outputBpE); /** @brief Get the memory size needed for each element */ virtual int GetBytesPerElem(); unsigned int m_CurrentSizeOutput; private: /** Block dimensions */ unsigned int m_BlockDims[3]; }; } #endif // __mitkOclDataSetToDataSetFilter_h diff --git a/Modules/OpenCL/mitkOclFilter.h b/Modules/OpenCL/mitkOclFilter.h index 29aed74597..4de5217d7a 100644 --- a/Modules/OpenCL/mitkOclFilter.h +++ b/Modules/OpenCL/mitkOclFilter.h @@ -1,158 +1,159 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef __mitkOclFilter_h #define __mitkOclFilter_h #include "mitkOclUtils.h" #include "mitkCommon.h" #include #include #include namespace mitk { /** @class OclFilter @brief Superclass for all OpenCL based filter. This class takes care of loading and compiling the external GPU program code. */ class MITKOPENCL_EXPORT OclFilter { public: /** * @brief Add a source file from the resource files to the * OpenCL shader file list. Multiple files can be added to the list. * - * @param name of the file in the resource system + * @param filename of the file in the resource system */ void AddSourceFile(const char* filename); /** * @brief Set specific compilerflags to compile the CL source. Default is set to nullptr; * example: "-cl-fast-relaxed-math -cl-mad-enable -cl-strict-aliasing" * * @param flags to the modulefolder that contains the gpuSource */ void SetCompilerFlags(const char* flags); /** * @brief Returns true if the initialization was successfull */ virtual bool IsInitialized(); /** * @brief Returns the amount of global memory of the used device in bytes */ virtual unsigned long GetDeviceMemory(); /** @brief Destructor */ virtual ~OclFilter(); protected: typedef std::vector CStringList; typedef std::vector ClSizeList; /** @brief Constructor */ OclFilter(); /** @brief Constructor ( overloaded ) */ OclFilter(const char* filename); /** @brief String that contains the compiler flags */ const char* m_ClCompilerFlags; /** @brief The compiled OpenCL program */ cl_program m_ClProgram; /** @brief Command queue for the filter */ cl_command_queue m_CommandQue; /** @brief Unique ID of the filter, needs to be specified in the constructor of the derived class */ std::string m_FilterID; /*! @brief source preambel for e.g. \c \#define commands to be inserted into the OpenCL source */ const char* m_Preambel; /** @brief List of sourcefiles that will be compiled for this filter.*/ CStringList m_ClFiles; /** @brief status of the filter */ bool m_Initialized; /** @brief The local work size fo the filter */ size_t m_LocalWorkSize[3]; /** @brief The global work size of the filter */ size_t m_GlobalWorkSize[3]; /** @brief Set the working size for the following OpenCL kernel call */ void SetWorkingSize(unsigned int locx, unsigned int dimx, unsigned int locy = 1, unsigned int dimy = 1, unsigned int locz = 1, unsigned int dimz = 1); /** @brief Execute the given kernel on the OpenCL Index-Space defined by the local and global work sizes */ bool ExecuteKernel( cl_kernel kernel, unsigned int workSizeDim ); /** @brief Execute the given kernel on the OpenCL Index-Space defined by the local and global work sizes, but divide it into chunks of dimension chunksDim */ bool ExecuteKernelChunks( cl_kernel kernel, unsigned int workSizeDim, size_t* chunksDim ); /** @brief Execute the given kernel on the OpenCL Index-Space defined by the local and global work sizes, but divide it into chunks of dimension chunksDim and wait between * batches of batchSize chunks a time of waitTimems milliseconds */ bool ExecuteKernelChunksInBatches(cl_kernel kernel, unsigned int workSizeDim, size_t* chunksDim, size_t batchSize, int waitTimems); /** * \brief Initialize all necessary parts of the filter * * The Initialize() method creates the command queue and the m_clProgram. * The program is either compiled from the given source or taken from the * OclResourceManager if the program was compiled already. */ bool Initialize(); /** * @brief Compile the program source * * @param preambel e.g. defines for the shader code */ void CompileSource(); /** * @brief Add some source code on the beginning of the loaded source * * In this way, some preprocessor flags for the CL compiler can at the beginning of the filter - * @param preambel Source preambel for e.g. #define commands to be inserted into the OpenCL source + * @param preambel Source preambel for e.g. \c \#define commands to be inserted into the OpenCL source */ void SetSourcePreambel(const char* preambel); /** * @brief Get the Module of the filter. Needs to be implemented by every subclass. * The filter will load the OpenCL sourcefiles from this module context. */ virtual us::Module* GetModule() = 0; /** * @brief Helper functions that load sourcefiles from the module context in the Initialize function. * @param SourceCodeList holds the sourcecode for every file as string, the SourceCodeSizeList holst the * size of every file in bytes. + * @param SourceCodeSizeList */ void LoadSourceFiles(CStringList &SourceCodeList, ClSizeList &SourceCodeSizeList); }; } #endif // __mitkOclFilter_h diff --git a/Modules/PhotoacousticsAlgorithms/include/mitkPhotoacousticFilterService.h b/Modules/PhotoacousticsAlgorithms/include/mitkPhotoacousticFilterService.h index 5a59fd5746..4bc3447162 100644 --- a/Modules/PhotoacousticsAlgorithms/include/mitkPhotoacousticFilterService.h +++ b/Modules/PhotoacousticsAlgorithms/include/mitkPhotoacousticFilterService.h @@ -1,126 +1,129 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkPhotoacousticFilterService_H_HEADER_INCLUDED #define mitkPhotoacousticFilterService_H_HEADER_INCLUDED #include "itkObject.h" #include "mitkCommon.h" #include "mitkImage.h" #include #include "mitkBeamformingSettings.h" #include "mitkBeamformingFilter.h" #include "MitkPhotoacousticsAlgorithmsExports.h" namespace mitk { /*! * \brief Class holding methods to apply all Filters within the Photoacoustics Algorithms Module * * Implemented are: * - A B-Mode Filter * - A Resampling Filter * - Beamforming on GPU and CPU * - A Bandpass Filter */ class MITKPHOTOACOUSTICSALGORITHMS_EXPORT PhotoacousticFilterService : public itk::Object { public: mitkClassMacroItkParent(mitk::PhotoacousticFilterService, itk::Object); itkFactorylessNewMacro(Self); /** \brief Defines the methods for the B-Mode filter * Currently implemented are an Envelope Detection filter and a simple Absolute filter. */ enum BModeMethod { EnvelopeDetection, Abs }; /** \brief Applies a B-Mode Filter * * Applies a B-Mode filter using the given parameters. * @param inputImage The image to be processed. * @param method The kind of B-Mode Filter to be used. * @param UseLogFilter Setting this to true will apply a simple logarithm to the image after the B-Mode Filter has been applied. - * @param resampleSpacing If this is set to 0, nothing will be done; otherwise, the image is resampled to a spacing of resampleSpacing mm per pixel. * @return The processed image is returned after the filter has finished. */ mitk::Image::Pointer ApplyBmodeFilter(mitk::Image::Pointer inputImage, BModeMethod method = BModeMethod::Abs, bool UseLogFilter = false); /** \brief Resamples the given image * * Resamples an image using the given parameters. * @param inputImage The image to be processed. - * @param outputSize An array of dimensions the image should be resampled to. + * @param outputSpacing An array of dimensions the image should be resampled to. * @return The processed image is returned after the filter has finished. */ mitk::Image::Pointer ApplyResampling(mitk::Image::Pointer inputImage, double* outputSpacing); mitk::Image::Pointer ApplyResamplingToDim(mitk::Image::Pointer inputImage, double* outputDimension); /** \brief Beamforms the given image * * Resamples an image using the given parameters. * @param inputImage The image to be processed. * @param config The configuration set to be used for beamforming. * @param progressHandle An std::function, through which progress of the currently updating filter is reported. * The integer argument is a number between 0 an 100 to indicate how far completion has been achieved, the std::string argument indicates what the filter is currently doing. * @return The processed image is returned after the filter has finished. */ mitk::Image::Pointer ApplyBeamforming(mitk::Image::Pointer inputImage, BeamformingSettings::Pointer config, std::function progressHandle = [](int, std::string) {}); /** \brief Crops the given image * * Crops an image in 3 dimension using the given parameters. * @param inputImage The image to be processed. * @param above How many voxels will be cut from the top of the image. * @param below How many voxels will be cut from the bottom of the image. * @param right How many voxels will be cut from the right side of the image. * @param left How many voxels will be cut from the left side of the image. * @param minSlice The first slice to be present in the resulting volume. * @param maxSlice How many slices are cut off from the end of the volume. + * @param errCode * @return The processed image is returned after the filter has finished. For the purposes of this module, the returned image is always of type float. */ mitk::Image::Pointer ApplyCropping(mitk::Image::Pointer inputImage, int above, int below, int right, int left, int minSlice, int maxSlice, int* errCode); mitk::Image::Pointer ExtendImage(mitk::Image::Pointer inputImage, float pixelColor, unsigned int outputDimensionY); /** \brief Applies a Bandpass filter to the given image * * Applies a bandpass filter to the given image using the given parameters. * @param data The image to be processed. * @param BPHighPass The position at which Lower frequencies are completely cut off in Hz. * @param BPLowPass The position at which Higher frequencies are completely cut off in Hz. * @param alphaHighPass The high pass tukey window parameter to control the shape of the bandpass filter: 0 will make it a Box function, 1 a Hann function. alpha can be set between those two bounds. * @param alphaLowPass The low passtukey window parameter to control the shape of the bandpass filter: 0 will make it a Box function, 1 a Hann function. alpha can be set between those two bounds. + * @param timeSpacing + * @param SpeedOfSound + * @param IsBFImage * @return The processed image is returned after the filter has finished. */ mitk::Image::Pointer ApplyBandpassFilter(mitk::Image::Pointer data, float BPHighPass, float BPLowPass, float alphaHighPass, float alphaLowPass, float timeSpacing, float SpeedOfSound, bool IsBFImage); protected: PhotoacousticFilterService(); ~PhotoacousticFilterService() override; /** \brief For performance reasons, an instance of the Beamforming filter is initialized as soon as possible and kept for all further uses. */ mitk::BeamformingFilter::Pointer m_BeamformingFilter; mitk::Image::Pointer ConvertToFloat(mitk::Image::Pointer); }; } // namespace mitk #endif /* mitkPhotoacousticFilterService_H_HEADER_INCLUDED */ diff --git a/Modules/PhotoacousticsAlgorithms/include/mitkPhotoacousticMotionCorrectionFilter.h b/Modules/PhotoacousticsAlgorithms/include/mitkPhotoacousticMotionCorrectionFilter.h index 8e8dcb3bfa..de4d9124dc 100644 --- a/Modules/PhotoacousticsAlgorithms/include/mitkPhotoacousticMotionCorrectionFilter.h +++ b/Modules/PhotoacousticsAlgorithms/include/mitkPhotoacousticMotionCorrectionFilter.h @@ -1,307 +1,307 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef _MITKPHOTOACOUSTICSMOTIONCORRECTIONFILTER_H_ #define _MITKPHOTOACOUSTICSMOTIONCORRECTIONFILTER_H_ #include "mitkImageToImageFilter.h" #include #include "opencv2/imgproc.hpp" // TODO: Find out why build fails with this option or replace with something // else /* #include "opencv2/opencv.hpp" */ #include "opencv2/video/tracking.hpp" #include "itkOpenCVImageBridge.h" #include #include "mitkImageCast.h" #include #include #include #define IMAGE_DIMENSION 3 /*!< All images need to have dimension 3*/ #define MAX_MATRIX 255.0 /*!< Rescaling constant to maximum character*/ namespace mitk { /*! * \brief Class implementing a mitk::ImageToImageFilter for PAUS motion * correction. * * The filter takes a stack of PA and US images. It then computes the optical * flow * within the US image and compensates the PA and US images for the flow. * Afterwards it * returns the stack of PA and US images. * * @see * https://docs.opencv.org/3.0-beta/modules/video/doc/motion_analysis_and_object_tracking.html#calcopticalflowfarneback */ class MITKPHOTOACOUSTICSALGORITHMS_EXPORT PhotoacousticMotionCorrectionFilter : public ImageToImageFilter { public: mitkClassMacro(PhotoacousticMotionCorrectionFilter, ImageToImageFilter); itkFactorylessNewMacro(Self); // Setters and Getters for the class variables itkSetMacro(BatchSize, unsigned int); itkSetMacro(PyrScale, double); itkSetMacro(Levels, unsigned int); itkSetMacro(WinSize, unsigned int); itkSetMacro(Iterations, unsigned int); itkSetMacro(PolyN, unsigned int); itkSetMacro(PolySigma, double); itkSetMacro(Flags, unsigned int); itkGetConstMacro(BatchSize, unsigned int); itkGetConstMacro(PyrScale, double); itkGetConstMacro(Levels, unsigned int); itkGetConstMacro(WinSize, unsigned int); itkGetConstMacro(Iterations, unsigned int); itkGetConstMacro(PolyN, unsigned int); itkGetConstMacro(PolySigma, double); itkGetConstMacro(Flags, unsigned int); // Wrapper for SetInput, GetInput and GetOutput /*! * \brief Wrapper which sets the photoacoustic image as the correct input * * This method is a wrapper around the @c SetInput method. It is implemented * for convenience such that you do not have to remember which input is for * which image. * * @param input The photoacoustic image */ - void SetPaInput(mitk::Image::Pointer); + void SetPaInput(mitk::Image::Pointer input); /*! * \brief Wrapper which gets the photoacoustic image out of the correct input * * This method is a wrapper around the @c GetInput method. It is implemented * for convenience such that you do not have to remember which input is for * which image. * * @return The photoacoustic image */ mitk::Image::Pointer GetPaInput(); /*! * \brief Wrapper which sets the ultrasonic image as the correct input * * This method is a wrapper around the @c SetInput method. It is implemented * for convenience such that you do not have to remember which input is for * which image. * * @param input The ultrasonic image */ - void SetUsInput(mitk::Image::Pointer); + void SetUsInput(mitk::Image::Pointer input); /*! * \brief Wrapper which gets the ultrasonic image out of the correct input * * This method is a wrapper around the @c GetInput method. It is implemented * for convenience such that you do not have to remember which input is for * which image. * * @return The ultrasonic image */ mitk::Image::Pointer GetUsInput(); /*! * \brief Wrapper which gets the photoacoustic image out of the correct output * * This method is a wrapper around the @c GetOutput method. It is implemented * for convenience such that you do not have to remember which output is for * which image. * * @return The photoacoustic image */ mitk::Image::Pointer GetPaOutput(); /*! * \brief Wrapper which gets the ultrasonic image out of the correct output * * This method is a wrapper around the @c GetOutput method. It is implemented * for convenience such that you do not have to remember which output is for * which image. * * @return The ultrasonic image */ mitk::Image::Pointer GetUsOutput(); protected: PhotoacousticMotionCorrectionFilter(); ~PhotoacousticMotionCorrectionFilter() override; /*! * \brief Apply OpenCV algorithm to compensate motion in a 2d image time * series * * This method uses two 3d mitk images. Both will be interpreted as time * series of 2d images. @c GetInput(0) should be a photoacoustic image whereas * @c GetInput(1) should be an ultrasound image. The input will be validated * and then converted to OpenCV matrices. In the end the Farneback algorithm * will be used to compute the optical flow in consecutive images and * compensate for this flow. The Output will be two 3d mitk images of the same * dimensions as the input containing the compensated data. * * @warning The input images need to be 3-dimensional (with the same size in * each dimension). Otherwise, an @c invalid_argument exception will be * thrown. * @throws invalid_argument */ void GenerateData() override; /*! * \brief Validate the input images * * The input images have to be non-empty, 3d and have to coincide in the * length in each dimension. If any of these conditions are violated, the * method will throw an @c invalid_argument exception. * * @param paImage A mitk image * @param usImage A mitk image * @warning If the two images are not 3d and do not coincide in the length in * each dimension, this method will throw an @c invalid_argument exception. * @throws invalid_argument */ void CheckInput(mitk::Image::Pointer paImage, mitk::Image::Pointer usImage); /*! * \brief Assure that the output images have the same dimensions as the input * images. * * The output images need to have the same dimensions as the input images. * This will be checked here. If the dimensions do not match, the output will * be reinitialized and the image data from the input images will be copied to * the output images (in order to make sure that they have a valid data * pointer). * * @param paInput Pointer to the photoacoustic input image * @param usInput Pointer to the ultrasonic input image * @param paOutput Pointer to the photoacoustic output image * @param usOutput Pointer to the ultrasonic output image */ void InitializeOutputIfNecessary(mitk::Image::Pointer paInput, mitk::Image::Pointer usInput, mitk::Image::Pointer paOutput, mitk::Image::Pointer usOutput); /*! * \brief Copy the image data from the input image to the output image * * This method copys the image data from @p input to @p output. This method * assumes that the dimensions of the two images match and will not test this. * * @param input A mitk image * @param output A mitk image */ void InitializeOutput(mitk::Image::Pointer input, mitk::Image::Pointer output); /*! * \brief This method performs the actual motion compensation. * * This method uses the ultrasonic input image @p usInput to compute the * optical flow in the time series of 2d images. Then it compensates both the * @p usInput and @p paInput for it and saves the result in @p usOutput and @p * paOutput respectively. In the background the OpenCV Farneback algorithm is * used for the flow determination. * * @param paInput The photoacoustic input image * @param usInput The ultrasonic input image * @param paOutput The photoacoustic output image * @param usOutput The ultrasonic output image */ void PerformCorrection(mitk::Image::Pointer paInput, mitk::Image::Pointer usInput, mitk::Image::Pointer paOutput, mitk::Image::Pointer usOutput); /*! * \brief Extract a 2d slice as OpenCV matrix. * * This method extracts slice @p i from the 3-dimensional image @p input and * converts it to a OpenCV matrix. Internally, the * mitkImageToOpenCVImageFilter is used. * * @param input A 3d image from which a slice is extracted as a 2d OpenCV * matrix. * @param i Determines the slice to be extracted. * @return returns a OpenCV matrix containing the 2d slice. */ cv::Mat GetMatrix(const mitk::Image::Pointer input, unsigned int i); /*! * \brief Rescale matrix such that the values lie between 0 and 255 * * This method rescales the matrix such that its values lie between 0 and 255. In order to do that it uses the maximum and the minimum of the input ultrasonic image. * * @warning This is a specialized method which does not perform the operation in general, but only if the matrix stems from the right ultrasonic image. Therefore, the method should only be called internally. * * @param mat The OpenCV matrix to be rescaled * @return The rescaled OpenCV matrix */ cv::Mat FitMatrixToChar(cv::Mat mat); /*! * \brief Insert a OpenCV matrix as a slice into an image * * This method converts the 2d OpenCV matrix @p mat into an mitk image using * the mitkOpenCVToMitkImageFilter. Afterwards it inserts the image as slice * @p i into the 3d mitk image @p output. * * @param mat The matrix to be inserted as a slice * @param output The 3d image the matrix is inserted into * @param i The index of the slice to be replaced. */ void InsertMatrixAsSlice(cv::Mat mat, mitk::Image::Pointer output, unsigned int i); /*! * \brief Compute the remapping map from an optical flow * * The optical flow cannot be used directly to compensate an image. Instead we have to generate an appropriate map. * * @param flow The optical flow which is the base for the remapping. * @return The remapping map. */ - cv::Mat ComputeFlowMap(cv::Mat); + cv::Mat ComputeFlowMap(cv::Mat flow); private: // Parameters double m_PyrScale; /*!< See @c pyr_scale in @c cv::calcOpticalFlowFarneback */ double m_PolySigma; /*!< See @c poly_sigma in @c cv::calcOpticalFlowFarneback */ unsigned int m_Levels; /*!< See @c levels in @c cv::calcOpticalFlowFarneback */ unsigned int m_WinSize; /*!< See @c winsize in @c cv::calcOpticalFlowFarneback */ unsigned int m_Iterations; /*!< See @c iterations in @c cv::calcOpticalFlowFarneback */ unsigned int m_PolyN; /*!< See @c poly_n in @c cv::calcOpticalFlowFarneback */ unsigned int m_Flags; /*!< See @c flags in @c cv::calcOpticalFlowFarneback */ unsigned int m_BatchSize; /*!< Determines how many slices belong together and will be motion compensated with regard to the first image in the batch. If the variable is set to 0, the whole time series will be processed as one batch. */ float m_MaxValue; /*!< The maximum of the ultrasonic image*/ float m_MinValue; /*!< The minimum of the ultrasonic image*/ // Stuff that OpenCV needs cv::Mat m_UsRef; /*!< Contains the reference ultrasonic image to which the motion compensation is compared to.*/ cv::Mat m_Flow; /*!< Contains the optical flow between @c m_UsRef and @c m_UsMat*/ cv::Mat m_PaRes; /*!< Contains the motion compensated photoacoustic image*/ cv::Mat m_UsRes; /*!< Contains the motion compensated ultrasonic image*/ cv::Mat m_PaMat; /*!< Contains the latest photoacoustic image to be motion compensated*/ cv::Mat m_UsMat; /*!< Contains the latest ultrasonic image on which the optical flow is to be computed */ cv::Mat m_Map; /*!< Contains the remapping map */ mitk::OpenCVToMitkImageFilter::Pointer m_OpenCVToImageFilter = mitk::OpenCVToMitkImageFilter::New(); /*!< Filter which converts an OpenCV matrix to a mitk image */ mitk::ImageToOpenCVImageFilter::Pointer m_ImageToOpenCVFilter = mitk::ImageToOpenCVImageFilter::New(); /*!< Filter which converts a mitk image to an OpenCV matrix */ }; } #endif diff --git a/Modules/REST/include/mitkIRESTObserver.h b/Modules/REST/include/mitkIRESTObserver.h index 099483fc58..db3330d055 100644 --- a/Modules/REST/include/mitkIRESTObserver.h +++ b/Modules/REST/include/mitkIRESTObserver.h @@ -1,51 +1,53 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkIRESTObserver_h #define mitkIRESTObserver_h #include #include #include #include #include namespace mitk { class MITKREST_EXPORT IRESTObserver { public: /** * @brief Deletes an observer and calls HandleDeleteObserver() in RESTManager class * * @see HandleDeleteObserver() */ virtual ~IRESTObserver(); /** * @brief Called if there's an incoming request for the observer, observer implements how to handle request * + * @param uri * @param data the data of the incoming request - * @param method the http method of the incoming request + * @param method the http method of the incoming request + * @param headers * @return the modified data */ virtual web::http::http_response Notify(const web::uri &uri, const web::json::value &data, const web::http::method &method, const mitk::RESTUtil::ParamMap &headers) = 0; private: }; } #endif diff --git a/Modules/REST/include/mitkRESTClient.h b/Modules/REST/include/mitkRESTClient.h index 5cf46e094a..075e826924 100644 --- a/Modules/REST/include/mitkRESTClient.h +++ b/Modules/REST/include/mitkRESTClient.h @@ -1,104 +1,105 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkRESTClient_h #define mitkRESTClient_h #include #include namespace mitk { class MITKREST_EXPORT RESTClient { public: using http_request = web::http::http_request; RESTClient(); ~RESTClient(); /** * @brief Executes a HTTP GET request with the given uri and returns a task waiting for a json object * * @throw mitk::Exception if request went wrong * @param uri the URI resulting the target of the HTTP request - * @param the additional headers to be set to the HTTP request + * @param headers the additional headers to be set to the HTTP request * @return task to wait for with resulting json object */ pplx::task Get(const web::uri &uri, const std::map headers); /** * @brief Executes a HTTP GET request with the given uri and and stores the byte stream in a file given by the * filePath * * @throw mitk::Exception if request went wrong * @param uri the URI resulting the target of the HTTP request - * @param the additional headers to be set to the HTTP request + * @param filePath + * @param headers the additional headers to be set to the HTTP request * @return task to wait for returning an empty json object */ pplx::task Get(const web::uri &uri, const utility::string_t &filePath, const std::map headers); /** * @brief Executes a HTTP PUT request with given uri and the content given as json * * @throw mitk::Exception if request went wrong * @param uri defines the URI resulting the target of the HTTP request * @param content the content as json value which should be the body of the request and thus the content of the * created resources * @return task to wait for with resulting json object */ pplx::task Put(const web::uri &uri, const web::json::value *content); /** * @brief Executes a HTTP POST request with given uri and the content given as json * * @throw mitk::Exception if request went wrong * @param uri defines the URI resulting the target of the HTTP request * @param content the content as json value which should be the body of the request and thus the content of the * created resource * @param headers the additional headers to be set to the HTTP request * @return task to wait for with resulting json object */ pplx::task Post(const web::uri &uri, const web::json::value *content, const std::map headers); /** * @brief Executes a HTTP POST request with given uri and the content given as json * * @throw mitk::Exception if request went wrong * @param uri defines the URI resulting the target of the HTTP request * @param content the content as json value which should be the body of the request and thus the content of the * created resource * @param headers the additional headers to be set to the HTTP request * @return task to wait for with resulting json object */ pplx::task Post(const web::uri &uri, const std::vector *content, const std::map headers); private: /** * @brief Use this to create and init a new request with the given headers. If needed, set the body on the resulting * request object to avoid an automatic change of the content type header when setting the body first. */ http_request InitRequest(const std::map headers); void CheckResponseContentType(web::http::http_response &response); pplx::task ExecutePost(const web::uri &uri, http_request request); web::http::client::http_client_config m_ClientConfig; }; } // namespace mitk #endif diff --git a/Modules/RESTService/include/mitkRESTManager.h b/Modules/RESTService/include/mitkRESTManager.h index f1ad8e00c5..5ea1b5e457 100644 --- a/Modules/RESTService/include/mitkRESTManager.h +++ b/Modules/RESTService/include/mitkRESTManager.h @@ -1,153 +1,153 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef mitkRESTManager_h #define mitkRESTManager_h #include #include #include namespace mitk { /** * @class RESTManager * @brief this is a microservice for managing REST-requests, used for non-qt applications. * * RESTManagerQt in the CppRestSdkQt module inherits from this class and is the equivalent microservice * used for Qt applications. */ class MITKRESTSERVICE_EXPORT RESTManager : public IRESTManager { public: RESTManager(); ~RESTManager() override; /** * @brief Executes a HTTP request in the mitkRESTClient class * * @throw mitk::Exception if RequestType is not suported * @param uri defines the URI the request is send to * @param type the RequestType of the HTTP request (optional) * @param headers the headers for the request (optional) * @return task to wait for */ pplx::task SendRequest( const web::uri &uri, const RequestType &type = RequestType::Get, const std::map headers = {}) override; /** * @brief Executes a HTTP request in the mitkRESTClient class * * @throw mitk::Exception if RequestType is not suported * @param uri defines the URI the request is send to * @param type the RequestType of the HTTP request (optional) * @param body the body for the request (optional) * @param headers the headers for the request (optional) * @param filePath the file path to store the request to (optional) * @return task to wait for */ pplx::task SendJSONRequest(const web::uri &uri, const RequestType &type = RequestType::Get, const web::json::value *body = nullptr, const std::map headers = {}, const utility::string_t &filePath = {}) override; /** * @brief Executes a HTTP request in the mitkRESTClient class * * @throw mitk::Exception if RequestType is not suported * @param uri defines the URI the request is send to * @param type the RequestType of the HTTP request (optional) * @param body the body for the request (optional) * @param headers the headers for the request (optional) * @return task to wait for */ pplx::task SendBinaryRequest( const web::uri &uri, const RequestType &type = RequestType::Get, - const std::vector * = {}, + const std::vector *body = {}, const std::map headers = {}) override; /** * @brief starts listening for requests if there isn't another observer listening and the port is free * * @param uri defines the URI for which incoming requests should be send to the observer * @param observer the observer which handles the incoming requests */ void ReceiveRequest(const web::uri &uri, IRESTObserver *observer) override; /** * @brief Handles incoming requests by notifying the observer which should receive it * * @param uri defines the URI of the request * @param body the body of the request * @param method the http method of the request * @param headers the http headers of the request * @return the response */ web::http::http_response Handle(const web::uri &uri, const web::json::value &body, const web::http::method &method, const mitk::RESTUtil::ParamMap &headers) override; /** * @brief Handles the deletion of an observer for all or a specific uri * * @param observer the observer which shouldn't receive requests anymore * @param uri the uri for which the observer doesn't handle requests anymore (optional) */ void HandleDeleteObserver(IRESTObserver *observer, const web::uri &uri = {}) override; /** * @brief internal use only */ const std::map &GetServerMap() override; std::map, IRESTObserver *> &GetObservers() override; private: /** * @brief adds an observer if a port is free, called by ReceiveRequest method * * @param uri the uri which builds the key for the observer map * @param observer the observer which is added */ void AddObserver(const web::uri &uri, IRESTObserver *observer); /** * @brief handles server management if there is already a server under a port, called by ReceiveRequest method * * @param uri the uri which which is requested to be added * @param observer the observer which proceeds the request */ void RequestForATakenPort(const web::uri &uri, IRESTObserver *observer); /** * @brief deletes an observer, called by HandleDeleteObserver method * * @param it the iterator comparing the observers in HandleDeleteObserver method * @return bool if there is another observer under the port */ bool DeleteObserver(std::map, IRESTObserver *>::iterator &it); void SetServerMap(const int port, RESTServer *server); void DeleteFromServerMap(const int port); void SetObservers(const std::pair key, IRESTObserver *observer); std::map m_ServerMap; // Map with port server pairs std::map, IRESTObserver *> m_Observers; // Map with all observers }; } // namespace mitk #endif diff --git a/Modules/RenderWindowManager/include/mitkRenderWindowLayerController.h b/Modules/RenderWindowManager/include/mitkRenderWindowLayerController.h index d4e14f8fa3..d8fffebf2d 100644 --- a/Modules/RenderWindowManager/include/mitkRenderWindowLayerController.h +++ b/Modules/RenderWindowManager/include/mitkRenderWindowLayerController.h @@ -1,173 +1,174 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKRENDERWINDOWLAYERCONTROLLER_H #define MITKRENDERWINDOWLAYERCONTROLLER_H // render window manager module #include "MitkRenderWindowManagerExports.h" #include "mitkRenderWindowLayerUtilities.h" // mitk core #include #include #include namespace mitk { /** * The RenderWindowLayerController is used to manipulate the 'layer', 'fixedLayer' and 'visible' property of a given data node. * The 'layer' property is used to denote the layer level of a data node. Data from nodes on higher layer level are rendered * on top of data from nodes on lower layer level. It can be changed using the 'MoveNode*'-functions. * * To view the data of a data node only in a specific renderer, the "InsertLayerNode'-function should be used. It inserts the * given node into the specified renderer and sets the corresponding properties. * To hide the data in the common renderer view (all renderer), the 'HideDataNodeInAllRenderer'-function can be used. * Inserting and showing a data node in a specific renderer / render window, will overwrite the properties of the common renderer view. * * For more information about the data node properties for specific renderer, see mitk::DataNode- and mitk::PropertyList-classes. * * Functions with 'mitk::BaseRenderer* renderer' have 'nullptr' as their default argument. Using the nullptr * these functions operate on all base renderer. Giving a specific base renderer will modify the node only for the given renderer. */ class MITKRENDERWINDOWMANAGER_EXPORT RenderWindowLayerController { public: RenderWindowLayerController(); /** * @brief Set the data storage on which to work. */ void SetDataStorage(DataStorage::Pointer dataStorage); /** * @brief Set the controlled base renderer. */ void SetControlledRenderer(RenderWindowLayerUtilities::RendererVector controlledRenderer); // wrapper functions to modify the layer order / visibility of render window data /** * @brief Set the given node as the base node of the given renderer. * * @param dataNode The data node whose layer is to be modified. * @param renderer Pointer to the renderer instance for which the data node property should be modified. * If it is a nullptr (default) all controlled renderer will be affected. */ void SetBaseDataNode(DataNode* dataNode, const BaseRenderer* renderer = nullptr); /** * @brief Insert the given data node at the specified layer for the given renderer. * * @param dataNode The data node that should be inserted. * @param layer The layer value for the "layer" property of the data node (insertion level). "layer = RenderWindowLayerUtilities::TOP_LAYER_INDEX" (default) inserts the given data node at the top of the node stack (topmost layer). * @param renderer Pointer to the renderer instance for which the data node should be inserted. * If it is a nullptr (default) all controlled renderer will be affected. * * @post After a successful call, the "fixedLayer" and "visibility" property will be true and the "layer" property will be set correctly. */ void InsertLayerNode(DataNode* dataNode, int layer = RenderWindowLayerUtilities::TOP_LAYER_INDEX, const BaseRenderer* renderer = nullptr); /** * @brief Remove the given data node for the given renderer. * * @param dataNode The data node that should be removed. * @param renderer Pointer to the renderer instance for which the data node should be removed. * If it is a nullptr (default) all controlled renderer will be affected. * * @post After a successful call, the "fixedLayer" and "visibility" property will be false and the "layer" property will be deleted. */ void RemoveLayerNode(DataNode* dataNode, const BaseRenderer* renderer = nullptr); /** * @brief Move the data node to the given layer. This will change only the "layer" property. * * @param dataNode The data node that should be moved. + * @param newLayer * @param renderer Pointer to the renderer instance for which the data node should be moved. * If it is a nullptr (default) all controlled renderer will be affected. */ bool MoveNodeToPosition(DataNode* dataNode, int newLayer, const BaseRenderer* renderer = nullptr); /** * @brief Set the node in the given renderer as the topmost layer. This will change only the "layer" property. * * @param dataNode The data node that should be moved. * @param renderer Pointer to the renderer instance for which the data node should be moved. * If it is a nullptr (default) all controlled renderer will be affected. */ bool MoveNodeToFront(DataNode* dataNode, const BaseRenderer* renderer = nullptr); /** * @brief Set the node in the given renderer as the lowermost layer. This will change only the "layer" property. * * @param dataNode The data node that should be moved. * @param renderer Pointer to the renderer instance for which the data node should be moved. * If it is a nullptr (default) all controlled renderer will be affected. */ bool MoveNodeToBack(DataNode* dataNode, const BaseRenderer* renderer = nullptr); /** * @brief Move the node in the given renderer one layer down. This will change only the "layer" property. * * @param dataNode The data node that should be moved. * @param renderer Pointer to the renderer instance for which the data node should be moved. * If it is a nullptr (default) all controlled renderer will be affected. */ bool MoveNodeUp(DataNode* dataNode, const BaseRenderer* renderer = nullptr); /** * @brief Move the node in the given renderer one layer up. This will change only the "layer" property. * * @param dataNode The data node that should be moved. * @param renderer Pointer to the renderer instance for which the data node should be moved. * If it is a nullptr (default) all controlled renderer will be affected. */ bool MoveNodeDown(DataNode* dataNode, const BaseRenderer* renderer = nullptr); /** * @brief Set the visibility of the given data node for the given renderer. * * @param visibility Boolean to set the "visible" property of the given data node. * @param dataNode The data node that should be moved. * @param renderer Pointer to the renderer instance for which the data node should be modified. * If it is a nullptr (default) all controlled renderer will be affected. * * @post After a successful call , the "visibility" property will be set to the "visibility" value. */ - void SetVisibilityOfDataNode(bool visiblity, DataNode* dataNode, const BaseRenderer* renderer = nullptr); + void SetVisibilityOfDataNode(bool visibility, DataNode* dataNode, const BaseRenderer* renderer = nullptr); /** * @brief Hide the given data node by setting the "visible" property of the data node for * all controlled renderer to false. * Later setting the "visible" property of the data node for a certain renderer will overwrite * the same property of the common renderer. * * @param dataNode The data node that should be hid. * * @post After a successful call , the "visibility" property will be set to the false. */ void HideDataNodeInAllRenderer(const DataNode* dataNode); /** * @brief Reset the given render window: * If "onlyVisibility = true": set all data nodes for the given render window to invisible, except for the base node. * If "onlyVisibility = false": remove all data nodes from the render window, except for the base node. * - * @param visibility Boolean to define the reset mode. + * @param onlyVisibility Boolean to define the reset mode. * @param renderer Pointer to the renderer instance for which the data node should be reset. * If it is a nullptr (default) all controlled renderer will be affected. * * @post After a successful call , the "visibility" property will be set to the "false" value (except for the base node). * If "onlyVisibility = false": additionally the "fixedLayer" property will be false and the "layer" property will be deleted. */ void ResetRenderer(bool onlyVisibility = true, const BaseRenderer* renderer = nullptr); private: void InsertLayerNodeInternal(DataNode* dataNode, int layer, const BaseRenderer* renderer = nullptr); DataStorage::Pointer m_DataStorage; RenderWindowLayerUtilities::RendererVector m_ControlledRenderer; }; } // namespace mitk #endif // MITKRENDERWINDOWLAYERCONTROLLER_H diff --git a/Modules/SemanticRelations/include/mitkSemanticRelationsDataStorageAccess.h b/Modules/SemanticRelations/include/mitkSemanticRelationsDataStorageAccess.h index 2e05221e5a..12fdd6be2d 100644 --- a/Modules/SemanticRelations/include/mitkSemanticRelationsDataStorageAccess.h +++ b/Modules/SemanticRelations/include/mitkSemanticRelationsDataStorageAccess.h @@ -1,183 +1,184 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKSEMANTICRELATIONSDATASTORAGEACCESS_H #define MITKSEMANTICRELATIONSDATASTORAGEACCESS_H #include // semantic relations module #include "mitkSemanticTypes.h" // mitk core #include #include namespace mitk { /** * @brief The API provides functions to query and manipulate image relations and instances, * that are helpful during follow-up examination, like control-points (time period), * types of the images or lesions that may be visible on multiple images. * * The class is able to generate IDs from given data nodes using DICOM information. * These IDs are used to identify the corresponding instances of a specific case. * The case can also be directly identified by the given case ID. * * In order for most functions to work the case ID has to be used as a parameter. * If not, these functions do nothing. */ class MITKSEMANTICRELATIONS_EXPORT SemanticRelationsDataStorageAccess { public: using DataNodeVector = std::vector; SemanticRelationsDataStorageAccess(DataStorage* dataStorage); /************************************************************************/ /* functions to get instances / attributes */ /************************************************************************/ /** * @brief Return a vector of all segmentations that are currently available for the given case. * The segmentations may be connected / not connected to a lesion of the case. * If no segmentations are stored for the current case, an empty vector is returned. * * @pre The data storage member has to be valid (!nullptr). * @throw SemanticRelationException, if the data storage member is invalid (==nullptr). * * @param caseID The current case identifier is defined by the given string. * * @return A vector of data nodes representing segmentations. */ DataNodeVector GetAllSegmentationsOfCase(const SemanticTypes::CaseID& caseID) const; /** * @brief Return a vector of all segmentations that define the given lesion. These segmentations don't have to be linked to the same image. * If the lesion is not referred to by any segmentation, an empty vector is returned. * * @pre The data storage member has to be valid (!nullptr). * @throw SemanticRelationException, if the data storage member is invalid (==nullptr). * @pre The UID of the lesion has to exist for a lesion instance. * @throw SemanticRelationException, if UID of the lesion does not exist for a lesion instance (this can be checked via 'InstanceExists'). * * @param caseID The current case identifier is defined by the given string. * @param lesion A lesion with a UID that identifies the corresponding lesion instance. * * @return A vector of data nodes representing segmentations that define the given lesion. */ DataNodeVector GetAllSegmentationsOfLesion(const SemanticTypes::CaseID& caseID, const SemanticTypes::Lesion& lesion) const; /** * @brief Return a vector of all images that are currently available for the given case. * * @pre The data storage member has to be valid (!nullptr). * @throw SemanticRelationException, if the data storage member is invalid (==nullptr). * * @param caseID The current case identifier is defined by the given string. * * @return A vector of data nodes representing images. */ DataNodeVector GetAllImagesOfCase(const SemanticTypes::CaseID& caseID) const; /** * @brief Return a vector of all images that are specified by the given vector of image IDs. * * @pre The data storage member has to be valid (!nullptr). * @throw SemanticRelationException, if the data storage member is invalid (==nullptr). * * @param imageIDs A vector of image IDs that represent the images in the data storage. * * @return A vector of data nodes representing images. */ DataNodeVector GetAllImagesByID(const SemanticTypes::IDVector& imageIDs) const; /** * @brief Return a vector of all images that are connected to those segmentations that are linked to the given lesion. * If the lesion is not referred to by any segmentation, an empty vector is returned. * * @pre The UID of the lesion has to exist for a lesion instance. * @throw SemanticRelationException, if UID of the lesion does not exist for a lesion instance (this can be checked via 'InstanceExists'). * * @param caseID The current case identifier is defined by the given string. * @param lesion A lesion with a UID that identifies the corresponding lesion instance. * * @return A vector of data nodes representing images on which the lesions are visible. */ DataNodeVector GetAllImagesOfLesion(const SemanticTypes::CaseID& caseID, const SemanticTypes::Lesion& lesion) const; /** * @brief Return a vector of all image nodes that are defined with the given control point and the given information type. * * @pre The UID of the control point has to exist for a control point instance. * The information type has to exist for the given case (and is therefore used by at least one data node). * @throw SemanticRelationException, if the UID of the control point does not exist for a control point instance (this can be checked via 'InstanceExists') or * if the information type is not used by any data node (this can be checked via 'InstanceExists'). * * @param caseID The current case identifier is defined by the given string. * @param controlPoint A control point with a UID that identifies the corresponding control point instance. * @param informationType An information type that identifies the corresponding information type instance. * * @return A vector of image nodes that are defined with the given control point and the given information type. */ DataNodeVector GetAllSpecificImages(const SemanticTypes::CaseID& caseID, const SemanticTypes::ControlPoint& controlPoint, const SemanticTypes::InformationType& informationType) const; /** * @brief Return a vector of all image nodes that are defined with the given information type and the given examination period. * The function uses the 'SemanticRelationsInference::GetAllImageIDsOfExaminationPeriod'-function to retrieve the imageIDs of the examination period and * then compares the information type of all these images against the given information type. * + * @param caseID * @param informationType An information type that identifies the corresponding information type instance. * @param examinationPeriod An examination period that identifies the corresponding examination period instance. * * @return A vector of image nodes that are defined with the given information type with the given control point. */ DataNodeVector GetAllSpecificImages(const SemanticTypes::CaseID& caseID, const SemanticTypes::InformationType& informationType, const SemanticTypes::ExaminationPeriod& examinationPeriod) const; /** * @brief Return a vector of all segmentation nodes that are defined with the given control point and the given information type. * The function uses the 'GetAllSpecificImages'-function to retrieve the specific images and then searches for the derived nodes (segmentation child nodes). * * @pre The UID of the control point has to exist for a control point instance. * The information type has to exist for the given case (and is therefore used by at least one data node). * @throw SemanticRelationException, if the UID of the control point does not exist for a control point instance (this can be checked via 'InstanceExists') or * if the information type is not used by any data node (this can be checked via 'InstanceExists'). * * @param caseID The current case identifier is defined by the given string. * @param controlPoint A control point with a UID that identifies the corresponding control point instance. * @param informationType An information type that identifies the corresponding information type instance. * * @return A vector of segmentation nodes that are defined with the given control point and the given information type. */ DataNodeVector GetAllSpecificSegmentations(const SemanticTypes::CaseID& caseID, const SemanticTypes::ControlPoint& controlPoint, const SemanticTypes::InformationType& informationType) const; /** * @brief Return the single segmentation node that is defined with the given information type, the given control point and is representing the given lesion. * The function uses the 'GetAllSpecificSegmentations'-function to retrieve the specific segmentations and then checks for the represented lesion. * * @pre The UID of the control point has to exist for a control point instance. * The information type has to exist for the given case (and is therefore used by at least one data node). * The lesion has to exist for the given case. * @throw SemanticRelationException, if the UID of the control point does not exist for a control point instance (this can be checked via 'InstanceExists') or * if the information type is not used by any data node (this can be checked via 'InstanceExists') or * if the lesion does not exist for the given case (this can be checked via 'InstanceExists'). * * @param caseID The current case identifier is defined by the given string. * @param controlPoint A control point with a UID that identifies the corresponding control point instance. * @param informationType An information type that identifies the corresponding information type instance. * @param lesion A lesion with a UID that identifies the corresponding lesion instance. * * @return A single segmentation node that is defined with the given information type, the given control point and is representing the given lesion. */ DataNode::Pointer GetSpecificSegmentation(const SemanticTypes::CaseID& caseID, const SemanticTypes::ControlPoint& controlPoint, const SemanticTypes::InformationType& informationType, const SemanticTypes::Lesion& lesion) const; private: WeakPointer m_DataStorage; }; } // namespace mitk #endif // MITKSEMANTICRELATIONSDATASTORAGEACCESS_H diff --git a/Modules/SemanticRelations/include/mitkSemanticRelationsIntegration.h b/Modules/SemanticRelations/include/mitkSemanticRelationsIntegration.h index 7d798c3d1e..4584c31fb3 100644 --- a/Modules/SemanticRelations/include/mitkSemanticRelationsIntegration.h +++ b/Modules/SemanticRelations/include/mitkSemanticRelationsIntegration.h @@ -1,322 +1,322 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKSEMANTICRELATIONSINTEGRATION_H #define MITKSEMANTICRELATIONSINTEGRATION_H #include // semantic relations module #include "mitkISemanticRelationsObservable.h" #include "mitkISemanticRelationsObserver.h" #include "mitkSemanticTypes.h" // mitk core #include namespace mitk { /** * @brief The API provides functions to manipulate image relations and instances * that are helpful during follow-up examination, like control-points (time period), * types of the images or lesions that may be visible on multiple images. * * The class is able to generate IDs from given data nodes using DICOM information. * These IDs are used to identify the corresponding instances of a specific case. * The case can also be directly identified by the given case ID. * * In order for most functions to work the case ID has to be used as a parameter. * If not, these functions do nothing. * * The class implements the ISemanticRelationsObservable interface to allow observers to * be informed about changes in the semantic relation storage. */ class MITKSEMANTICRELATIONS_EXPORT SemanticRelationsIntegration : public ISemanticRelationsObservable { public: /************************************************************************/ /* functions to implement the observer pattern */ /************************************************************************/ /** * @brief Adds the given concrete observer to the vector that holds all currently registered observer. * If the observer is already registered, it will not be added to the observer vector. * * @param observer The concrete observer to register. */ void AddObserver(ISemanticRelationsObserver* observer) override; /** * @brief Removes the given concrete observer from the vector that holds all currently registered observer. * * @param observer The concrete observer to unregister. */ void RemoveObserver(ISemanticRelationsObserver* observer) override; virtual ~SemanticRelationsIntegration() {} /************************************************************************/ /* functions to add / remove instances / attributes */ /************************************************************************/ /** * @brief Add the given image to the set of already existing images. * The date is extracted from the DICOM data of the image node and is compared to already existing control points in the semantic relations model. * The function tries to find a fitting control point or to extend an already existing control point, if the extracted control point is close to * any other, already existing control point. * Finally, the image is linked to the correct control point. * * @pre The given image data node has to be valid (!nullptr). * @throw SemanticRelationException, if the given image data node is invalid (==nullptr). * * @param imageNode The current case identifier and node identifier is extracted from the given image data node, which contains DICOM information about the case and the node. */ void AddImage(const DataNode* imageNode); /** * @brief Remove the given image from the set of already existing images. * * @pre The given image data node has to be valid (!nullptr). * @throw SemanticRelationException, if the given image data node is invalid (==nullptr). * * @param imageNode The current case identifier and node identifier is extracted from the given image data node, which contains DICOM information about the case and the node. */ void RemoveImage(const DataNode* imageNode); /** * @brief Add a newly created lesion to the set of already existing lesions - with no connection to a specific image / segmentation of the case data. * * @pre The UID of the lesion must not already exist for a lesion instance. * @throw SemanticRelationException, it the UID of the lesion already exists for a lesion instance (this can be checked via 'InstanceExists'). * * @param caseID The current case identifier is defined by the given string. * @param lesion The lesion instance to add. */ void AddLesion(const SemanticTypes::CaseID& caseID, const SemanticTypes::Lesion& lesion); /** * @brief Overwrite an already existing lesion instance (this may be useful to overwrite the lesion with a different lesion class). * * @pre The UID of the lesion has to exist for a lesion instance. * @throw SemanticRelationException, if the UID of the lesion does not exist for a lesion instance (this can be checked via 'InstanceExists'). * * @param caseID The current case identifier is defined by the given string. * @param lesion The lesion instance that overwrites an existing lesion. */ void OverwriteLesion(const SemanticTypes::CaseID& caseID, const SemanticTypes::Lesion& lesion); /** * @brief Add a newly created lesion to the set of already existing lesions. The lesion is added and a reference to * the lesion is added to the segmentation. If the segmentation is already linked to a lesion, the * old linkage is overwritten (this can be checked via 'IsRepresentingALesion'). * * @pre The given segmentation data node has to be valid (!nullptr). * @throw SemanticRelationException, if the given segmentation data node is invalid (==nullptr). * @pre The UID of the lesion must not already exist for a lesion instance. * @throw SemanticRelationException, if the UID of the lesion already exists for a lesion instance (this can be checked via 'InstanceExists'). * * @param segmentationNode The segmentation identifier is extracted from the given segmentation data node. The segmentation node has DICOM information from its parent node. * @param lesion The lesion instance to add and link. */ void AddLesionAndLinkSegmentation(const DataNode* segmentationNode, const SemanticTypes::Lesion& lesion); /** * @brief Remove the given lesion from the set of already existing lesions. * * @pre The UID of the lesion has to exist for a lesion instance. * @throw SemanticRelationException, if the UID of the lesion does not exist for a lesion instance (this can be checked via 'InstanceExists'). * @pre The function needs to assure that no segmentation is still representing (linked to) this lesion. * @throw SemanticRelationException, if the lesion instance to remove is still linked to by any segmentation (this can be checked via 'GetAllSegmentationsOfLesion'). * * @param caseID The current case identifier is defined by the given string. * @param lesion The lesion instance to remove. */ void RemoveLesion(const SemanticTypes::CaseID& caseID, const SemanticTypes::Lesion& lesion); /** * @brief Add a segmentation instance to the set of already existing segmentations - with no connection to a specific lesion. * * @param segmentationNode The segmentation identifier is extracted from the given segmentation data node. The segmentation node has DICOM information from its parent node. * @param parentNode The node identifier of the parent node is extracted from the given parent data node. */ void AddSegmentation(const DataNode* segmentationNode, const DataNode* parentNode); /** * @brief Link the given segmentation instance to an an already existing lesion instance. If the segmentation is already linked to a lesion instance, the * old linkage is overwritten (this can be checked via 'IsRepresentingALesion'). * * @pre The given segmentation data node has to be valid (!nullptr). * @throw SemanticRelationException, if the given segmentation data node is invalid (==nullptr). * @pre The UID of the lesion has to exist for a lesion instance. * @throw SemanticRelationException, if the UID of the lesion does not exist for a lesion instance (this can be checked via 'InstanceExists'). * * @param segmentationNode The segmentation identifier is extracted from the given segmentation data node. The segmentation node has DICOM information from its parent node. * @param lesion The lesion instance to link. */ void LinkSegmentationToLesion(const DataNode* segmentationNode, const SemanticTypes::Lesion& lesion); /** * @brief Unlink the given segmentation instance from the linked lesion instance. * The lesion may stay unlinked to any segmentation. * * @pre The given segmentation data node has to be valid (!nullptr). * @throw SemanticRelationException, if the given segmentation data node is invalid (==nullptr). * * @param segmentationNode The segmentation identifier is extracted from the given segmentation data node. The segmentation node has DICOM information from its parent node. */ void UnlinkSegmentationFromLesion(const DataNode* segmentationNode); /** * @brief Remove the given segmentation from the set of already existing segmentations. * * @pre The given segmentation data node has to be valid (!nullptr). * @throw SemanticRelationException, if the given segmentation data node is invalid (==nullptr). * * @param segmentationNode The segmentation identifier is extracted from the given segmentation data node. The segmentation node has DICOM information from its parent node. */ void RemoveSegmentation(const DataNode* segmentationNode); /** * @brief Set the control point for the given image. * * @pre The given image data node has to be valid (!nullptr). * @throw SemanticRelationException, if the given image data node is invalid (==nullptr). * * @param imageNode The current case identifier and node identifier is extracted from the given image data node, which contains DICOM information about the case and the node. * @param controlPoint The control point instance which is used for the given image. */ void SetControlPointOfImage(const DataNode* imageNode, const SemanticTypes::ControlPoint& controlPoint); /** * @brief Add a newly created control point to the set of already existing control points. A reference to the control point is added to the given image. * This function combines adding a control point and linking it, since a control point with no associated data is not allowed. * * @pre The given image data node has to be valid (!nullptr). * @throw SemanticRelationException, if the given image data node is invalid (==nullptr). * @pre The UID of the control point must not already exist for a control point instance. * @throw SemanticRelationException, if the UID of the control point already exists for a control point instance (this can be checked via 'InstanceExists'). * @pre The given control point must not already be contained in an existing control point interval. * @throw SemanticRelationException, if the given control point is already contained in an existing control point interval (this can be checked via 'CheckContainingControlPoint'). * @pre The given control point must contain the date of the given image data node (if parameter 'checkConsistence = true'). * @throw SemanticRelationException, if the given control point does not contain the date of the given image data node and 'checkConsistence = true' (this can be checked via 'ControlPointManager::InsideControlPoint'). * * @param imageNode The current case identifier and node identifier is extracted from the given image data node, which contains DICOM information about the case and the node. * @param controlPoint The control point instance to add. For a newly added control point always has "startDate = endDate". * @param checkConsistence If true, the function checks, whether the date of the image data node actually lies inside the control point to link. */ void AddControlPointAndLinkImage(const DataNode* imageNode, const SemanticTypes::ControlPoint& controlPoint, bool checkConsistence = true); /** * @brief Link the given image to an already existing control point. * * @pre The given image data node has to be valid (!nullptr). * @throw SemanticRelationException, if the given image data node is invalid (==nullptr). * @pre The UID of the control point has to exist for a control point instance. * @throw SemanticRelationException, if the UID of the control point does not exists for a control point instance (this can be checked via 'InstanceExists'). * @pre The given control point must contain the date of the given image data node (if parameter 'checkConsistence = true'). * @throw SemanticRelationException, if the given control point does not contain the date of the given image data node and 'checkConsistence = true' (this can be checked via 'ControlPointManager::InsideControlPoint'). * * @param imageNode The current case identifier and node identifier is extracted from the given image data node, which contains DICOM information about the case and the node. * @param controlPoint The control point instance to link. * @param checkConsistence If true, the function checks, whether the date of the image data node actually lies inside the control point to link. */ void LinkImageToControlPoint(const DataNode* imageNode, const SemanticTypes::ControlPoint& controlPoint, bool checkConsistence = true); /** * @brief Unlink the given image from the linked control point. * If an image is unlinked from a control point, the function needs to check whether the control point is still linked to any other image: * - if not, the control point instance will be removed (has to be removed since a control point with no associated image is not allowed). * - if so, the function has to make sure that the control point instance is shortened to its minimum time period (e.g. moving the end point to an earlier date). * * @param imageNode The current case identifier and node identifier is extracted from the given image data node, which contains DICOM information about the case and the node. */ void UnlinkImageFromControlPoint(const DataNode* imageNode); /** * @brief Add an examination period instance to the set of already existing examination periods - with no connection to a specific control point. * * @pre The UID of the examination period must not already exist for an examination period instance. * @throw SemanticRelationException, if the UID of the examination period already exists for a examination period instance (this can be checked via 'InstanceExists'). * * @param caseID The current case identifier is defined by the given string. * @param examinationPeriod The examination period to add. */ void AddExaminationPeriod(const SemanticTypes::CaseID& caseID, const SemanticTypes::ExaminationPeriod& examinationPeriod); /** * @brief Rename an already existing examination period instance. * * @pre The UID of the examination period has to exist for an examination period instance. * @throw SemanticRelationException, if the UID of the examination period does not exist for an examination period instance (this can be checked via 'InstanceExists'). * - * @param caseID The current case identifier is defined by the given string. - * @param lesion The examination period instance that renames an existing examination period. + * @param caseID The current case identifier is defined by the given string. + * @param examinationPeriod The examination period instance that renames an existing examination period. */ void RenameExaminationPeriod(const SemanticTypes::CaseID& caseID, const SemanticTypes::ExaminationPeriod& examinationPeriod); /** * @brief Add a control point to the vector of control point UIDs of an existing examination period. * * @pre The UID of the control point has to exist for a control point instance. * @throw SemanticRelationException, if the UID of the control point does not exists for a control point instance (this can be checked via 'InstanceExists'). * @pre The UID of the examination period must not already exist for an examination period instance. * @throw SemanticRelationException, if the UID of the examination period already exists for a examination period instance (this can be checked via 'InstanceExists'). * * @param caseID The current case identifier is defined by the given string. * @param controlPoint The control point instance to add to the examination period. * @param examinationPeriod The examination period to which the control point should be added. */ void AddControlPointToExaminationPeriod(const SemanticTypes::CaseID& caseID, const SemanticTypes::ControlPoint& controlPoint, const SemanticTypes::ExaminationPeriod& examinationPeriod); /** * @brief Set (and possibly overwrite) the information type of the given image. * An already associated information type might be removed if is not referenced by any other image: * * @pre The given image data node has to be valid (!nullptr). * @throw SemanticRelationException, if the given image data node is invalid (==nullptr). * @post If the information type instance did not exist before, it is now added. * * @param imageNode The current case identifier is extracted from the given image data node, which contains DICOM information about the case. * @param informationType An information type that identifies the corresponding information type instance. */ void SetInformationType(const DataNode* imageNode, const SemanticTypes::InformationType& informationType); /** * @brief Set the information type of the given image. * * @pre The given image data node has to be valid (!nullptr). * @throw SemanticRelationException, if the given image data node is invalid (==nullptr). * @post If the information type instance did not exist before, it is now added. * * @param imageNode The current case identifier is extracted from the given image data node, which contains DICOM information about the case. * @param informationType An information type that identifies the corresponding information type instance. */ void AddInformationTypeToImage(const DataNode* imageNode, const SemanticTypes::InformationType& informationType); /** * @brief Remove the information type of the given image. * If the information type is removed, the function needs to check whether the information type is referenced by any other image: * - if not, the information type instance can be removed (has to be removed since an information type with no associated image is not allowed). * - if so, the information type is just removed from the given image. * * @pre The given image data node has to be valid (!nullptr). * @throw SemanticRelationException, if the given image data node is invalid (==nullptr). * * @param imageNode The current case identifier is extracted from the given image data node, which contains DICOM information about the case. */ void RemoveInformationTypeFromImage(const DataNode* imageNode); private: /** * @brief A vector that stores the currently registered observer of this observable subject. */ static std::vector m_ObserverVector; /** * @brief The class notifies (updates) the observer with a given case ID. * The view's caseID was set before in the GUI. The parts of the view that observe changes in the semantic relations are only updated, * if the given case ID is equal to the observer's current caseID and thus the observer currently shows the semantic information of the given case. * * @param caseID The caseID that identifies the currently active patient / case. */ void NotifyObserver(const mitk::SemanticTypes::CaseID& caseID) const override; /** * @brief Remove all control points from the storage that are not referenced by any image anymore. * This might happen if an image has been removed (and unlinked from the corresponding control point) * or if the user sets a new control point for an image manually in the GUI. * * @param caseID The current case identifier is defined by the given string. */ void ClearControlPoints(const SemanticTypes::CaseID& caseID); }; } // namespace mitk #endif // MITKSEMANTICRELATIONSINTEGRATION_H diff --git a/Modules/ToFHardware/Kinect/mitkKinectController.h b/Modules/ToFHardware/Kinect/mitkKinectController.h index 81b1db888c..75cf216002 100644 --- a/Modules/ToFHardware/Kinect/mitkKinectController.h +++ b/Modules/ToFHardware/Kinect/mitkKinectController.h @@ -1,91 +1,92 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef __mitkKinectController_h #define __mitkKinectController_h #include #include "mitkCommon.h" #include "mitkToFConfig.h" #include "itkObject.h" #include "itkObjectFactory.h" namespace mitk { /** * @brief Interface to the Kinect camera * * * @ingroup ToFHardware */ class MITKKINECT_EXPORT KinectController : public itk::Object { public: mitkClassMacroItkParent( KinectController , itk::Object ); itkFactorylessNewMacro(Self); itkCloneMacro(Self); unsigned int GetCaptureWidth() const; unsigned int GetCaptureHeight() const; bool GetUseIR() const; void SetUseIR(bool useIR); /*! \brief opens a connection to the Kinect camera. \throws mitkException In case of no connection, an exception is thrown! */ virtual bool OpenCameraConnection(); /*! \brief closes the connection to the camera */ virtual bool CloseCameraConnection(); /*! \brief updates the camera. The update function of the hardware interface is called only when new data is available \throws mitkException In case of no connection, an exception is thrown! */ virtual bool UpdateCamera(); /*! \brief acquire new distance data from the Kinect camera \param distances pointer to memory location where distances should be stored */ void GetDistances(float* distances); void GetAmplitudes(float* amplitudes); void GetIntensities(float* intensities); /*! \brief acquire new rgb data from the Kinect camera \param rgb pointer to memory location where rgb information should be stored */ void GetRgb(unsigned char* rgb); /*! \brief convenience method for faster access to distance and rgb data \param distances pointer to memory location where distances should be stored + \param amplitudes \param rgb pointer to memory location where rgb information should be stored */ void GetAllData(float* distances, float* amplitudes, unsigned char* rgb); protected: KinectController(); ~KinectController(); private: class KinectControllerPrivate; KinectControllerPrivate *d; }; } //END mitk namespace #endif diff --git a/Modules/ToFHardware/Kinect/mitkKinectDevice.h b/Modules/ToFHardware/Kinect/mitkKinectDevice.h index 1bf4c113ff..29f607047d 100644 --- a/Modules/ToFHardware/Kinect/mitkKinectDevice.h +++ b/Modules/ToFHardware/Kinect/mitkKinectDevice.h @@ -1,145 +1,149 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef __mitkKinectDevice_h #define __mitkKinectDevice_h #include #include "mitkCommon.h" #include "mitkToFCameraDevice.h" #include "mitkKinectController.h" #include "itkObject.h" #include "itkObjectFactory.h" #include "itkMultiThreader.h" #include "itkFastMutexLock.h" namespace mitk { /** * @brief Interface for all representations of Kinect devices. * KinectDevice internally holds an instance of KinectController and starts a thread * that continuously grabs images from the controller. A buffer structure buffers the last acquired images * to provide the image data loss-less. * * \throws mitkException In case of no connection, an exception is thrown! * * @ingroup ToFHardware */ class MITKKINECT_EXPORT KinectDevice : public ToFCameraDevice { public: mitkClassMacro( KinectDevice , ToFCameraDevice ); itkFactorylessNewMacro(Self); itkCloneMacro(Self); /*! \brief opens a connection to the ToF camera \throws mitkException In case of no connection, an exception is thrown! */ virtual bool OnConnectCamera(); /*! \brief closes the connection to the camera */ virtual bool DisconnectCamera(); /*! \brief starts the continuous updating of the camera. A separate thread updates the source data, the main thread processes the source data and creates images and coordinates \throws mitkException In case of no connection, an exception is thrown! */ virtual void StartCamera(); /*! \brief stops the continuous updating of the camera */ virtual void StopCamera(); /*! \brief updates the camera for image acquisition \throws mitkException In case of no connection, an exception is thrown! */ virtual void UpdateCamera(); /*! \brief returns whether the camera is currently active or not */ virtual bool IsCameraActive(); /*! \brief gets the amplitude data from the ToF camera as the strength of the active illumination of every pixel. Caution! The user is responsible for allocating and deleting the images. These values can be used to determine the quality of the distance values. The higher the amplitude value, the higher the accuracy of the according distance value \param imageSequence the actually captured image sequence number \param amplitudeArray contains the returned amplitude data as an array. */ virtual void GetAmplitudes(float* amplitudeArray, int& imageSequence); /*! \brief gets the intensity data from the ToF camera as a greyscale image. Caution! The user is responsible for allocating and deleting the images. \param intensityArray contains the returned intensities data as an array. \param imageSequence the actually captured image sequence number */ virtual void GetIntensities(float* intensityArray, int& imageSequence); /*! \brief gets the distance data from the ToF camera measuring the distance between the camera and the different object points in millimeters. Caution! The user is responsible for allocating and deleting the images. \param distanceArray contains the returned distances data as an array. \param imageSequence the actually captured image sequence number */ virtual void GetDistances(float* distanceArray, int& imageSequence); /*! \brief gets the 3 images (distance, amplitude, intensity) from the ToF camera. Caution! The user is responsible for allocating and deleting the images. \param distanceArray contains the returned distance data as an array. \param amplitudeArray contains the returned amplitude data as an array. + \param intensityArray + \param sourceDataArray + \param requiredImageSequence \param capturedImageSequence the actually captured image sequence number. + \param rgbDataArray */ virtual void GetAllImages(float* distanceArray, float* amplitudeArray, float* intensityArray, char* sourceDataArray, int requiredImageSequence, int& capturedImageSequence, unsigned char* rgbDataArray=nullptr); /*! \brief returns the corresponding camera controller */ KinectController::Pointer GetController(); /*! \brief set a BaseProperty */ virtual void SetProperty( const char *propertyKey, BaseProperty* propertyValue ); /*! \brief returns the width of the RGB image */ int GetRGBCaptureWidth(); /*! \brief returns the height of the RGB image */ int GetRGBCaptureHeight(); protected: KinectDevice(); ~KinectDevice(); /*! \brief Thread method continuously acquiring images from the ToF hardware */ static ITK_THREAD_RETURN_TYPE Acquire(void* pInfoStruct); /*! \brief moves the position pointer m_CurrentPos to the next position in the buffer if that's not the next free position to prevent reading from an empty buffer */ void GetNextPos(); KinectController::Pointer m_Controller; ///< corresponding CameraController float** m_DistanceDataBuffer; ///< buffer holding the last distance images float** m_AmplitudeDataBuffer; ///< buffer holding the last infra-red (IR) images unsigned char** m_RGBDataBuffer; ///< buffer holding the last RGB image private: }; } //END mitk namespace #endif diff --git a/Modules/ToFHardware/KinectV2/mitkKinectV2Controller.h b/Modules/ToFHardware/KinectV2/mitkKinectV2Controller.h index c958676176..33ae229d8e 100644 --- a/Modules/ToFHardware/KinectV2/mitkKinectV2Controller.h +++ b/Modules/ToFHardware/KinectV2/mitkKinectV2Controller.h @@ -1,104 +1,105 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef __mitkKinectV2Controller_h #define __mitkKinectV2Controller_h #include #include #include "mitkToFConfig.h" #include #include #include #include namespace mitk { /** * @brief Interface to the Kinect 2 camera. Currently, the Microsoft SDK is used. * * @ingroup ToFHardware */ class MITKKINECTV2_EXPORT KinectV2Controller : public itk::Object { public: mitkClassMacroItkParent( KinectV2Controller , itk::Object ); itkFactorylessNewMacro(Self); itkCloneMacro(Self) int GetRGBCaptureWidth() const; int GetRGBCaptureHeight() const; int GetDepthCaptureWidth() const; int GetDepthCaptureHeight() const; /** \brief Setup MultiFrameReader of Kinect V2. * This reader can acquire different types of data. Here it is used * to acquire depth, RGB and infrared images. */ bool InitializeMultiFrameReader(); /*! \brief opens a connection to the Kinect V2 camera. \throws mitkException In case of no connection, an exception is thrown! */ virtual bool OpenCameraConnection(); /*! \brief closes the connection to the camera */ virtual bool CloseCameraConnection(); /*! \brief updates the camera. The update function of the hardware interface is called only when new data is available \throws mitkException In case of no connection, an exception is thrown! */ virtual bool UpdateCamera(); /*! \brief acquire new distance data from the Kinect camera \param distances pointer to memory location where distances should be stored */ void GetDistances(float* distances); void GetAmplitudes(float* amplitudes); void GetIntensities(float* intensities); vtkSmartPointer GetVtkPolyData(); void SetGenerateTriangularMesh(bool flag); void SetTriangulationThreshold(double triangulationThreshold); /*! \brief acquire new rgb data from the Kinect camera \param rgb pointer to memory location where rgb information should be stored */ void GetRgb(unsigned char* rgb); /*! \brief convenience method for faster access to distance and rgb data \param distances pointer to memory location where distances should be stored + \param amplitudes \param rgb pointer to memory location where rgb information should be stored */ void GetAllData(float* distances, float* amplitudes, unsigned char* rgb); protected: KinectV2Controller(); ~KinectV2Controller(); private: class KinectV2ControllerPrivate; KinectV2ControllerPrivate *d; }; } //END mitk namespace #endif diff --git a/Modules/ToFHardware/KinectV2/mitkKinectV2Device.h b/Modules/ToFHardware/KinectV2/mitkKinectV2Device.h index 5e32555080..b77ab252b2 100644 --- a/Modules/ToFHardware/KinectV2/mitkKinectV2Device.h +++ b/Modules/ToFHardware/KinectV2/mitkKinectV2Device.h @@ -1,153 +1,154 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef __mitkKinectV2Device_h #define __mitkKinectV2Device_h #include #include #include "mitkToFCameraDevice.h" #include "mitkKinectV2Controller.h" #include #include #include #include #include #include namespace mitk { /** * @brief Interface for all representations of Microsoft Kinect V2 devices. * Kinect2Device internally holds an instance of Kinect2Controller and starts a thread * that continuously grabs images from the controller. A buffer structure buffers the last acquired images * to provide the image data loss-less. * * \throws mitkException In case of no connection, an exception is thrown! * * @ingroup ToFHardware */ class MITKKINECTV2_EXPORT KinectV2Device : public ToFCameraDevice { public: mitkClassMacro( KinectV2Device , ToFCameraDevice ); itkFactorylessNewMacro(Self); itkCloneMacro(Self) /** Prints the framerate to the console every 100 frames. * Mainly for debugging, deactivated by default. * Refers to a static variable, means it is acivated/deactivated * for all instances. */ itkSetMacro(PrintFrameRate, bool); /*! \brief opens a connection to the ToF camera \throws mitkException In case of no connection, an exception is thrown! */ virtual bool OnConnectCamera(); /*! \brief closes the connection to the camera */ virtual bool DisconnectCamera(); /*! \brief starts the continuous updating of the camera. A separate thread updates the source data, the main thread processes the source data and creates images and coordinates \throws mitkException In case of no connection, an exception is thrown! */ virtual void StartCamera(); /*! \brief stops the continuous updating of the camera */ virtual void StopCamera(); /*! \brief updates the camera for image acquisition \throws mitkException In case of no connection, an exception is thrown! */ virtual void UpdateCamera(); /*! \brief returns whether the camera is currently active or not */ virtual bool IsCameraActive(); /*! \brief gets the amplitude data from the ToF camera as the strength of the active illumination of every pixel. Caution! The user is responsible for allocating and deleting the images. These values can be used to determine the quality of the distance values. The higher the amplitude value, the higher the accuracy of the according distance value \param imageSequence the actually captured image sequence number \param amplitudeArray contains the returned amplitude data as an array. */ virtual void GetAmplitudes(float* amplitudeArray, int& imageSequence); /*! \brief Does nothing for Kinect V2 as there is no intensity data provided by the device. * * The method is an empty implementation, because the interface (ToFCameraDevice) requires it. */ virtual void GetIntensities(float* intensityArray, int& imageSequence); /*! \brief gets the distance data from the ToF camera measuring the distance between the camera and the different object points in millimeters. Caution! The user is responsible for allocating and deleting the images. \param distanceArray contains the returned distances data as an array. \param imageSequence the actually captured image sequence number */ virtual void GetDistances(float* distanceArray, int& imageSequence); /*! \brief gets the 3 images (distance, amplitude, intensity) from the ToF camera. Caution! The user is responsible for allocating and deleting the images. \param distanceArray Contains the distance data as an array. \param amplitudeArray Contains the infrared image. \param intensityArray Does nothing for Kinect V2. \param sourceDataArray Does nothing for Kinect V2. \param requiredImageSequence The required image sequence number. \param capturedImageSequence Does nothing for Kinect V2. + \param rgbDataArray */ virtual void GetAllImages(float* distanceArray, float* amplitudeArray, float* intensityArray, char* sourceDataArray, int requiredImageSequence, int& capturedImageSequence, unsigned char* rgbDataArray=nullptr); /*! \brief returns the corresponding camera controller */ KinectV2Controller::Pointer GetController(); /*! \brief returns the width of the RGB image */ int GetRGBCaptureWidth(); /*! \brief returns the height of the RGB image */ int GetRGBCaptureHeight(); protected: KinectV2Device(); ~KinectV2Device(); /*! \brief Thread method continuously acquiring images from the ToF hardware */ static ITK_THREAD_RETURN_TYPE Acquire(void* pInfoStruct); static bool m_PrintFrameRate; ///< prints the framerate to the console every 100 frames, deactivated by default KinectV2Controller::Pointer m_Controller; ///< corresponding CameraController float** m_DistanceDataBuffer; ///< buffer holding the last distance images float** m_AmplitudeDataBuffer; ///< buffer holding the last amplitude images unsigned char** m_RGBDataBuffer; ///< buffer holding the last RGB image size_t m_DepthBufferSize; ///< Size of depth buffer (i.e. memory size of depth and infrared image) size_t m_RGBBufferSize; ///< Size of RGB buffer (i.e. memory size of RGB image) vtkSmartPointer m_PolyData; ///< Surface generated via the Kinect V2 SDK with default/unknown calibration. }; } //END mitk namespace #endif diff --git a/Plugins/org.mitk.gui.common/src/mitkIRenderWindowPartListener.h b/Plugins/org.mitk.gui.common/src/mitkIRenderWindowPartListener.h index 5539d50766..3e0e9a2f5f 100644 --- a/Plugins/org.mitk.gui.common/src/mitkIRenderWindowPartListener.h +++ b/Plugins/org.mitk.gui.common/src/mitkIRenderWindowPartListener.h @@ -1,61 +1,61 @@ /*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef MITKIRENDERWINDOWPARTLISTENER_H #define MITKIRENDERWINDOWPARTLISTENER_H #include namespace mitk { struct IRenderWindowPart; /** * \ingroup org_mitk_gui_common * * \brief Interface for berry::IViewPart implementations to be notified about mitk::IRenderWindowPart lifecycle changes. * * This interface is intended to be implemented by subclasses of berry::IWorkbenchPart. If implemented, * the interface methods are called automatically if a Workbench part which implementes mitk::IRenderWindowPart * is activated or deactivated. * * The notion of activated and deactivated is slightly different from the usual Workbench part lifecycle. */ struct MITK_GUI_COMMON_PLUGIN IRenderWindowPartListener { virtual ~IRenderWindowPartListener(); /** * Called when an IRenderWindowPart is activated or if it becomes visible and no * other IRenderWindowPart was activated before. * * \param renderWindowPart The newly activated IRenderWindowPart. */ virtual void RenderWindowPartActivated(mitk::IRenderWindowPart* renderWindowPart) = 0; /** * Called when an IRenderWindowPart becomes invisible and if it was active before. * * \param renderWindowPart The deactivated IRenderWindowPart. */ virtual void RenderWindowPartDeactivated(mitk::IRenderWindowPart* renderWindowPart) = 0; /** * Called when an IRenderWindowPart changes and if it was active before. * * \param renderWindowPart The modified IRenderWindowPart. */ - virtual void RenderWindowPartInputChanged(mitk::IRenderWindowPart* /*renderWindowPart*/) {}; + virtual void RenderWindowPartInputChanged(mitk::IRenderWindowPart* renderWindowPart) {}; }; } #endif // MITKIRENDERWINDOWPARTLISTENER_H