diff --git a/CMake/BuildConfigurations/All.cmake b/CMake/BuildConfigurations/All.cmake index 4db45f564d..f9bc2d76be 100644 --- a/CMake/BuildConfigurations/All.cmake +++ b/CMake/BuildConfigurations/All.cmake @@ -1,55 +1,56 @@ set(MITK_CONFIG_PACKAGES ) set(_apple_package_excludes) if(APPLE) set(_apple_package_excludes SOFA ) endif() set(_package_excludes ${_apple_package_excludes} Python + Numpy OpenCL SYSTEM_Boost Boost_LIBRARIES SYSTEM_PYTHON SOFA_PLUGINS SOFA_PLUGINS_DIR SUPERBUILD KWSTYLE MICROBIRD_TRACKER MICROBIRD_TRACKER_INCLUDE_DIR MICROBIRD_TRACKER_LIB MICRON_TRACKER OPTITRACK_TRACKER SPACENAVIGATOR TOF_KINECT TOF_KINECTV2 TOF_MESASR4000 TOF_PMDCAMBOARD TOF_PMDCAMCUBE TOF_PMDO3 US_TELEMED_SDK videoInput WIIMOTE ) get_cmake_property(_cache_vars CACHE_VARIABLES) foreach(_cache_var ${_cache_vars}) string(REGEX REPLACE "MITK_USE_(.+)" "\\1" _package "${_cache_var}") if(_package AND NOT _package STREQUAL _cache_var) list(FIND _package_excludes ${_package} _index) if(_index EQUAL -1) list(APPEND MITK_CONFIG_PACKAGES ${_package}) endif() endif() endforeach() set(MITK_BUILD_ALL_APPS ON CACHE BOOL "Build all MITK applications" FORCE) set(MITK_BUILD_ALL_PLUGINS ON CACHE BOOL "Build all MITK plugins" FORCE) set(MITK_BUILD_EXAMPLES ON CACHE BOOL "Build the MITK examples" FORCE) set(BLUEBERRY_BUILD_ALL_PLUGINS ON CACHE BOOL "Build all BlueBerry plugins" FORCE) set(BUILD_DiffusionMiniApps ON CACHE BOOL "Build MITK Diffusion MiniApps" FORCE) diff --git a/CMake/MITKDashboardDriverScript.cmake b/CMake/MITKDashboardDriverScript.cmake index 4385481bba..05b2bab27f 100644 --- a/CMake/MITKDashboardDriverScript.cmake +++ b/CMake/MITKDashboardDriverScript.cmake @@ -1,486 +1,521 @@ # # Included from a dashboard script, this cmake file will drive the configure and build # steps of MITK # #----------------------------------------------------------------------------- # The following variable are expected to be define in the top-level script: set(expected_variables CTEST_NOTES_FILES CTEST_SITE CTEST_DASHBOARD_ROOT CTEST_CMAKE_COMMAND CTEST_CMAKE_GENERATOR WITH_MEMCHECK WITH_COVERAGE WITH_DOCUMENTATION CTEST_BUILD_CONFIGURATION CTEST_TEST_TIMEOUT CTEST_BUILD_FLAGS TEST_TO_EXCLUDE_REGEX CTEST_SOURCE_DIRECTORY CTEST_BINARY_DIRECTORY CTEST_BUILD_NAME SCRIPT_MODE CTEST_COVERAGE_COMMAND CTEST_MEMORYCHECK_COMMAND CTEST_GIT_COMMAND PROJECT_BUILD_DIR - SUPERBUILD_TARGETS ) foreach(var ${expected_variables}) if(NOT DEFINED ${var}) message(FATAL_ERROR "Variable ${var} should be defined in top-level script !") endif() endforeach() string(REPLACE " " "%20" _build_name_escaped "${CTEST_BUILD_NAME}") # Check if "mbits" is reachable file(DOWNLOAD "http://mbits" "${CTEST_SCRIPT_DIRECTORY}/mbits.html" TIMEOUT 2 STATUS _status) list(GET _status 0 _status_code) if(_status_code EQUAL 6) # couldn't resovle host name set(MBITS_AVAILABLE 0) else() set(MBITS_AVAILABLE 1) endif() # # Site specific options # if(NOT CDASH_ADMIN_URL_PREFIX AND MBITS_AVAILABLE) set(CDASH_ADMIN_URL_PREFIX "http://mbits") endif() if(NOT MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL AND MBITS_AVAILABLE) set(MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL "http://mbits/dl-cache") endif() if(NOT DEFINED GIT_BRANCH OR GIT_BRANCH STREQUAL "") set(GIT_BRANCH "") else() set(GIT_BRANCH "-b ${GIT_BRANCH}") endif() # Should binary directory be cleaned? set(empty_binary_directory FALSE) # Attempt to build and test also if 'ctest_update' returned an error set(initial_force_build FALSE) # Set model options set(model "") if(SCRIPT_MODE STREQUAL "experimental") set(empty_binary_directory FALSE) set(initial_force_build TRUE) set(model Experimental) elseif(SCRIPT_MODE STREQUAL "continuous") set(empty_binary_directory FALSE) set(initial_force_build FALSE) set(model Continuous) elseif(SCRIPT_MODE STREQUAL "nightly") set(empty_binary_directory TRUE) set(initial_force_build TRUE) set(model Nightly) else() message(FATAL_ERROR "Unknown script mode: '${SCRIPT_MODE}'. Script mode should be either 'experimental', 'continuous' or 'nightly'") endif() #message("script_mode:${SCRIPT_MODE}") #message("model:${model}") #message("empty_binary_directory:${empty_binary_directory}") #message("force_build:${initial_force_build}") set(CTEST_CONFIGURATION_TYPE ${CTEST_BUILD_CONFIGURATION}) if(empty_binary_directory) message("Directory ${CTEST_BINARY_DIRECTORY} cleaned !") ctest_empty_binary_directory(${CTEST_BINARY_DIRECTORY}) endif() if(NOT DEFINED CTEST_CHECKOUT_DIR) set(CTEST_CHECKOUT_DIR ${CTEST_SOURCE_DIRECTORY}) endif() if(NOT EXISTS "${CTEST_CHECKOUT_DIR}") set(CTEST_CHECKOUT_COMMAND "\"${CTEST_GIT_COMMAND}\" clone ${GIT_BRANCH} ${GIT_REPOSITORY} \"${CTEST_CHECKOUT_DIR}\"") endif() set(CTEST_UPDATE_TYPE "git") set(CTEST_UPDATE_COMMAND "${CTEST_GIT_COMMAND}") #---------------------------------------------------------------------- # Utility macros #---------------------------------------------------------------------- function(func_build_target target build_dir) set(CTEST_BUILD_TARGET ${target}) ctest_build(BUILD "${build_dir}" APPEND RETURN_VALUE res NUMBER_ERRORS num_errors NUMBER_WARNINGS num_warnings) ctest_submit(PARTS Build RETRY_DELAY 3 RETRY_COUNT 3) if(num_errors) math(EXPR build_errors "${build_errors} + ${num_errors}") set(build_errors ${build_errors} PARENT_SCOPE) endif() if(num_warnings) math(EXPR build_warnings "${build_warnings} + ${num_warnings}") set(build_warnings ${build_warnings} PARENT_SCOPE) endif() endfunction() function(func_test label build_dir) if(NOT TESTING_PARALLEL_LEVEL) set(TESTING_PARALLEL_LEVEL 8) endif() if(label MATCHES "Unlabeled") set(_include_label EXCLUDE_LABEL .*) else() set(_include_label INCLUDE_LABEL ${label}) endif() ctest_test(BUILD "${build_dir}" ${_include_label} PARALLEL_LEVEL ${TESTING_PARALLEL_LEVEL} EXCLUDE ${TEST_TO_EXCLUDE_REGEX} RETURN_VALUE res ) ctest_submit(PARTS Test RETRY_DELAY 3 RETRY_COUNT 3) if(res) math(EXPR test_errors "${test_errors} + 1") set(test_errors ${test_errors} PARENT_SCOPE) endif() if(ARG3) set(WITH_COVERAGE ${ARG3}) endif() if(ARG4) set(WITH_MEMCHECK ${ARG4}) endif() if(WITH_COVERAGE AND CTEST_COVERAGE_COMMAND) message("----------- [ Coverage ${label} ] -----------") ctest_coverage(BUILD "${build_dir}" LABELS ${label}) ctest_submit(PARTS Coverage RETRY_DELAY 3 RETRY_COUNT 3) endif() if(WITH_MEMCHECK AND CTEST_MEMORYCHECK_COMMAND) if(NOT CTEST_MEMORYCHECK_SUPPRESSIONS_FILE) if(EXISTS "${CTEST_SOURCE_DIRECTORY}/CMake/valgrind.supp") set(CTEST_MEMORYCHECK_SUPPRESSIONS_FILE "${CTEST_SOURCE_DIRECTORY}/CMake/valgrind.supp") endif() endif() if(NOT CTEST_MEMORYCHECK_COMMAND_OPTIONS) set(CTEST_MEMORYCHECK_COMMAND_OPTIONS "-q --tool=memcheck --leak-check=yes --show-reachable=no --show-possibly-lost=no --workaround-gcc296-bugs=yes --num-callers=50") endif() ctest_memcheck(BUILD "${build_dir}" INCLUDE_LABEL ${label}) ctest_submit(PARTS MemCheck RETRY_DELAY 3 RETRY_COUNT 3) endif() endfunction() +macro(finalize_submission) + + # Note should be at the end + ctest_submit(PARTS Notes RETRY_DELAY 3 RETRY_COUNT 3) + + # Send status to the "CDash Web Admin" + if(CDASH_ADMIN_URL_PREFIX) + set(cdash_admin_url "${CDASH_ADMIN_URL_PREFIX}/cdashadmin-web/index.php?pw=4da12ca9c06d46d3171d7f73974c900f") + string(REGEX REPLACE ".*\\?project=(.*)&?" "\\1" _ctest_project "${CTEST_DROP_LOCATION}") + file(DOWNLOAD + "${cdash_admin_url}&action=submit&name=${_build_name_escaped}&hasTestErrors=${test_errors}&hasBuildErrors=${build_errors}&hasBuildWarnings=${build_warnings}&ctestDropSite=${CTEST_DROP_SITE}&ctestProject=${_ctest_project}" + "${CTEST_BINARY_DIRECTORY}/cdashadmin.txt" + STATUS status + ) + list(GET status 0 error_code) + list(GET status 1 error_msg) + if(error_code) + message(FATAL_ERROR "error: Failed to communicate with cdashadmin-web - ${error_msg}") + endif() + endif() + +endmacro() + +macro(check_for_errors) + + set(_curr_target ${ARGV0}) + if(build_errors AND _curr_target) + # try to remove the stamp file for external projects + set(_stamp_file "${CTEST_BINARY_DIRECTORY}/ep/src/${_curr_target}-stamp/${_curr_target}-configure") + if(EXISTS "${_stamp_file}") + file(REMOVE "${_stamp_file}") + endif() + endif() + + if(build_errors OR test_errors) + finalize_submission() + # this should return from run_ctest() + return() + endif() + +endmacro() + #--------------------------------------------------------------------- # run_ctest macro #--------------------------------------------------------------------- -macro(run_ctest) +function(run_ctest) set(build_warnings 0) set(build_errors 0) set(test_errors 0) ctest_start(${model}) ctest_update(SOURCE "${CTEST_CHECKOUT_DIR}" RETURN_VALUE res) if(res LESS 0) # update error math(EXPR build_errors "${build_errors} + 1") endif() set(force_build ${initial_force_build}) # Check if a forced run was requested set(cdash_remove_rerun_url ) if(CDASH_ADMIN_URL_PREFIX) set(cdash_rerun_url "${CDASH_ADMIN_URL_PREFIX}/rerun/${_build_name_escaped}") set(cdash_remove_rerun_url "${CDASH_ADMIN_URL_PREFIX}/rerun/rerun.php?name=${_build_name_escaped}&remove=1") file(DOWNLOAD "${cdash_rerun_url}" "${CTEST_BINARY_DIRECTORY}/tmp.txt" STATUS status ) list(GET status 0 error_code) file(READ "${CTEST_BINARY_DIRECTORY}/tmp.txt" rerun_content LIMIT 1) if(NOT error_code AND NOT rerun_content) set(force_build 1) endif() endif() if(COMMAND MITK_OVERRIDE_FORCE_BUILD) MITK_OVERRIDE_FORCE_BUILD(force_build) endif() # force a build if this is the first run and the build dir is empty if(NOT EXISTS "${CTEST_BINARY_DIRECTORY}/CMakeCache.txt") message("First time build - Initialize CMakeCache.txt") set(res 1) # Write initial cache. if(NOT DEFINED BUILD_TESTING) set(BUILD_TESTING ON) endif() # Write initial cache. file(WRITE "${CTEST_BINARY_DIRECTORY}/CMakeCache.txt" " CTEST_USE_LAUNCHERS:BOOL=${CTEST_USE_LAUNCHERS} CTEST_PROJECT_ADDITIONAL_TARGETS:INTERNAL=${CTEST_PROJECT_ADDITIONAL_TARGETS} BUILD_TESTING:BOOL=${BUILD_TESTING} MITK_CTEST_SCRIPT_MODE:STRING=${SCRIPT_MODE} CMAKE_BUILD_TYPE:STRING=${CTEST_BUILD_CONFIGURATION} WITH_COVERAGE:BOOL=${WITH_COVERAGE} MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL:STRING=${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL} ${INITIAL_CMAKECACHE_OPTIONS} ") endif() if(res GREATER 0 OR force_build) # Clear the forced rerun request if(CDASH_ADMIN_URL_PREFIX AND cdash_remove_rerun_url) file(DOWNLOAD "${cdash_remove_rerun_url}" "${CTEST_BINARY_DIRECTORY}/tmp.txt") file(REMOVE "${CTEST_BINARY_DIRECTORY}/tmp.txt") endif() if(CTEST_PROJECT_NAME_SUPERBUILD) set(ctest_project_name_orig ${CTEST_PROJECT_NAME}) set(CTEST_PROJECT_NAME ${CTEST_PROJECT_NAME_SUPERBUILD}) endif() message("----------- [ Configure SuperBuild ] -----------") set_property(GLOBAL PROPERTY SubProject SuperBuild) set_property(GLOBAL PROPERTY Label SuperBuild) ctest_configure(BUILD "${CTEST_BINARY_DIRECTORY}" RETURN_VALUE res OPTIONS "${SUPERBUILD_CONFIG_OPTIONS}") if(res) math(EXPR build_errors "${build_errors} + 1") endif() # Project.xml is generated during the superbuild configure step ctest_submit(FILES "${CTEST_BINARY_DIRECTORY}/Project.xml" RETRY_DELAY 3 RETRY_COUNT 3) ctest_read_custom_files("${CTEST_BINARY_DIRECTORY}") ctest_submit(PARTS Configure RETRY_DELAY 3 RETRY_COUNT 3) # submit the update results *after* the submitting the Configure info, # otherwise CDash is somehow confused and cannot add the update info # to the superbuild project ctest_submit(PARTS Update RETRY_DELAY 3 RETRY_COUNT 3) + check_for_errors() + # To get CTEST_PROJECT_SUBPROJECTS and CTEST_PROJECT_EXTERNALS definition include("${CTEST_BINARY_DIRECTORY}/CTestConfigSubProject.cmake") + # Read in a list of super-build targets (SUPERBUILD_TARGETS). If an error + # occurs in one of the listed projects, the ctest superbuild make step stops + # and the error is reported in the dashboard. If this variable would be empty + # the errors are still reported but make would keep building external + # projects which leads to potentially more errors because of dependencies. + set(MITK_SUPERBUILD_TARGETS_FILE "${CTEST_BINARY_DIRECTORY}/SuperBuildTargets.cmake") + if(EXISTS "${MITK_SUPERBUILD_TARGETS_FILE}") + include("${MITK_SUPERBUILD_TARGETS_FILE}") + endif() + # Build top level (either all or the supplied targets at # superbuild level - if(SUPERBUILD_TARGETS AND NOT build_errors) + if(SUPERBUILD_TARGETS) foreach(superbuild_target ${SUPERBUILD_TARGETS}) message("----------- [ Build ${superbuild_target} - SuperBuild ] -----------") func_build_target(${superbuild_target} "${CTEST_BINARY_DIRECTORY}") + check_for_errors(${superbuild_target}) # runs only tests that have a LABELS property matching "SuperBuild" func_test("SuperBuild" "${CTEST_BINARY_DIRECTORY}") + check_for_errors() endforeach() # HACK Unfortunately ctest_coverage ignores the build argument, back-up the original dirs file(READ "${CTEST_BINARY_DIRECTORY}/CMakeFiles/TargetDirectories.txt" old_coverage_dirs) # explicitly build requested external projects as subprojects foreach(external_project_with_build_dir ${CTEST_PROJECT_EXTERNALS}) string(REPLACE "^^" ";" external_project_with_build_dir_list "${external_project_with_build_dir}") list(GET external_project_with_build_dir_list 0 external_project_name) list(GET external_project_with_build_dir_list 1 external_project_builddir) set_property(GLOBAL PROPERTY SubProject ${external_project_name}) set_property(GLOBAL PROPERTY Label ${external_project_name}) message("----------- [ Build ${external_project_name} ] -----------") func_build_target("${external_project_name}" "${CTEST_BINARY_DIRECTORY}") + check_for_errors() - if(NOT build_errors) - # HACK Unfortunately ctest_coverage ignores the build argument, try to force it... - file(READ "${CTEST_BINARY_DIRECTORY}/${external_project_builddir}/CMakeFiles/TargetDirectories.txt" mitk_build_coverage_dirs) - file(APPEND "${CTEST_BINARY_DIRECTORY}/CMakeFiles/TargetDirectories.txt" "${mitk_build_coverage_dirs}") + # HACK Unfortunately ctest_coverage ignores the build argument, try to force it... + file(READ "${CTEST_BINARY_DIRECTORY}/${external_project_builddir}/CMakeFiles/TargetDirectories.txt" mitk_build_coverage_dirs) + file(APPEND "${CTEST_BINARY_DIRECTORY}/CMakeFiles/TargetDirectories.txt" "${mitk_build_coverage_dirs}") - message("----------- [ Test ${external_project_name} ] -----------") + message("----------- [ Test ${external_project_name} ] -----------") - # runs only tests that have a LABELS property matching "${external_project_name}" - func_test(${external_project_name} "${CTEST_BINARY_DIRECTORY}/${external_project_builddir}") + # runs only tests that have a LABELS property matching "${external_project_name}" + func_test(${external_project_name} "${CTEST_BINARY_DIRECTORY}/${external_project_builddir}") - # restore old coverage dirs - file(WRITE "${CTEST_BINARY_DIRECTORY}/CMakeFiles/TargetDirectories.txt" "${old_coverage_dirs}") - endif() + # restore old coverage dirs + file(WRITE "${CTEST_BINARY_DIRECTORY}/CMakeFiles/TargetDirectories.txt" "${old_coverage_dirs}") endforeach() # switch back to SuperBuild label set_property(GLOBAL PROPERTY SubProject SuperBuild) set_property(GLOBAL PROPERTY Label SuperBuild) message("----------- [ Finish SuperBuild ] -----------") else() message("----------- [ Build SuperBuild ] -----------") endif() - if(NOT build_errors) - # build everything at superbuild level which has not yet been built - func_build_target("" "${CTEST_BINARY_DIRECTORY}") - endif() + # build everything at superbuild level which has not yet been built + func_build_target("" "${CTEST_BINARY_DIRECTORY}") + check_for_errors() # runs only tests that have a LABELS property matching "SuperBuild" #func_test("SuperBuild" "${CTEST_BINARY_DIRECTORY}") set(build_dir "${CTEST_BINARY_DIRECTORY}/${PROJECT_BUILD_DIR}") if(CTEST_PROJECT_NAME_SUPERBUILD) set(CTEST_PROJECT_NAME ${ctest_project_name_orig}) endif() message("----------- [ Configure ${build_dir} ] -----------") # Configure target ctest_configure(BUILD "${build_dir}" OPTIONS "-DCTEST_USE_LAUNCHERS=${CTEST_USE_LAUNCHERS}" RETURN_VALUE res ) ctest_read_custom_files("${CTEST_BINARY_DIRECTORY}") ctest_submit(PARTS Configure RETRY_DELAY 3 RETRY_COUNT 3) if(res) math(EXPR build_errors "${build_errors} + 1") endif() - + check_for_errors() foreach(subproject ${CTEST_PROJECT_SUBPROJECTS}) - if(NOT build_errors) - set_property(GLOBAL PROPERTY SubProject ${subproject}) - set_property(GLOBAL PROPERTY Label ${subproject}) - - if(subproject MATCHES "Unlabeled") - message("----------- [ Build All (Unlabeled) ] -----------") - # Build target - func_build_target("" "${build_dir}") - else() - message("----------- [ Build ${subproject} ] -----------") - # Build target - func_build_target(${subproject} "${build_dir}") - endif() + set_property(GLOBAL PROPERTY SubProject ${subproject}) + set_property(GLOBAL PROPERTY Label ${subproject}) + + if(subproject MATCHES "Unlabeled") + message("----------- [ Build All (Unlabeled) ] -----------") + # Build target + func_build_target("" "${build_dir}") + else() + message("----------- [ Build ${subproject} ] -----------") + # Build target + func_build_target(${subproject} "${build_dir}") endif() + check_for_errors() endforeach() - if(NOT build_errors) - # HACK Unfortunately ctest_coverage ignores the build argument, try to force it... - file(READ ${build_dir}/CMakeFiles/TargetDirectories.txt mitk_build_coverage_dirs) - file(APPEND "${CTEST_BINARY_DIRECTORY}/CMakeFiles/TargetDirectories.txt" "${mitk_build_coverage_dirs}") + # HACK Unfortunately ctest_coverage ignores the build argument, try to force it... + file(READ ${build_dir}/CMakeFiles/TargetDirectories.txt mitk_build_coverage_dirs) + file(APPEND "${CTEST_BINARY_DIRECTORY}/CMakeFiles/TargetDirectories.txt" "${mitk_build_coverage_dirs}") - foreach(subproject ${CTEST_PROJECT_SUBPROJECTS}) - set_property(GLOBAL PROPERTY SubProject ${subproject}) - set_property(GLOBAL PROPERTY Label ${subproject}) - message("----------- [ Test ${subproject} ] -----------") + foreach(subproject ${CTEST_PROJECT_SUBPROJECTS}) + set_property(GLOBAL PROPERTY SubProject ${subproject}) + set_property(GLOBAL PROPERTY Label ${subproject}) + message("----------- [ Test ${subproject} ] -----------") - # runs only tests that have a LABELS property matching "${subproject}" - func_test(${subproject} "${build_dir}") - endforeach() - endif() + # runs only tests that have a LABELS property matching "${subproject}" + func_test(${subproject} "${build_dir}") + endforeach() # Build any additional target which is not build by "all" # i.e. the "package" target - if(CTEST_PROJECT_ADDITIONAL_TARGETS AND NOT build_errors) + if(CTEST_PROJECT_ADDITIONAL_TARGETS) foreach(additional_target ${CTEST_PROJECT_ADDITIONAL_TARGETS}) set_property(GLOBAL PROPERTY SubProject ${additional_target}) set_property(GLOBAL PROPERTY Label ${additional_target}) message("----------- [ Build ${additional_target} ] -----------") func_build_target(${additional_target} "${build_dir}") + check_for_errors() message("----------- [ Test ${additional_target} ] -----------") # runs only tests that have a LABELS property matching "${subproject}" func_test(${additional_target} "${build_dir}") endforeach() endif() if(WITH_DOCUMENTATION) message("----------- [ Build Documentation ] -----------") set(ctest_use_launchers_orig ${CTEST_USE_LAUNCHERS}) set(CTEST_USE_LAUNCHERS 0) # Build Documentation target set_property(GLOBAL PROPERTY SubProject Documentation) set_property(GLOBAL PROPERTY Label Documentation) func_build_target("doc" "${build_dir}") set(CTEST_USE_LAUNCHERS ${ctest_use_launchers_orig}) endif() set_property(GLOBAL PROPERTY SubProject SuperBuild) set_property(GLOBAL PROPERTY Label SuperBuild) # Global coverage ... if(WITH_COVERAGE AND CTEST_COVERAGE_COMMAND) message("----------- [ Global coverage ] -----------") ctest_coverage(BUILD "${build_dir}" APPEND) ctest_submit(PARTS Coverage RETRY_DELAY 3 RETRY_COUNT 3) endif() # Global dynamic analysis ... if(WITH_MEMCHECK AND CTEST_MEMORYCHECK_COMMAND) message("----------- [ Global memcheck ] -----------") ctest_memcheck(BUILD "${build_dir}") ctest_submit(PARTS MemCheck RETRY_DELAY 3 RETRY_COUNT 3) endif() - # Note should be at the end - ctest_submit(PARTS Notes RETRY_DELAY 3 RETRY_COUNT 3) - - # Send status to the "CDash Web Admin" - if(CDASH_ADMIN_URL_PREFIX) - set(cdash_admin_url "${CDASH_ADMIN_URL_PREFIX}/cdashadmin-web/index.php?pw=4da12ca9c06d46d3171d7f73974c900f") - string(REGEX REPLACE ".*\\?project=(.*)&?" "\\1" _ctest_project "${CTEST_DROP_LOCATION}") - file(DOWNLOAD - "${cdash_admin_url}&action=submit&name=${_build_name_escaped}&hasTestErrors=${test_errors}&hasBuildErrors=${build_errors}&hasBuildWarnings=${build_warnings}&ctestDropSite=${CTEST_DROP_SITE}&ctestProject=${_ctest_project}" - "${CTEST_BINARY_DIRECTORY}/cdashadmin.txt" - STATUS status - ) - list(GET status 0 error_code) - list(GET status 1 error_msg) - if(error_code) - message(FATAL_ERROR "error: Failed to communicate with cdashadmin-web - ${error_msg}") - endif() - endif() + check_for_errors() + finalize_submission() endif() # Clear the CTEST_CHECKOUT_COMMAND variable to prevent continuous clients # to try to checkout again set(CTEST_CHECKOUT_COMMAND "") -endmacro() +endfunction() if(SCRIPT_MODE STREQUAL "continuous") while(1) run_ctest() # Loop no faster than once every 5 minutes message("Wait for 5 minutes ...") ctest_sleep(300) endwhile() else() run_ctest() endif() diff --git a/CMake/MITKDashboardSetup.cmake b/CMake/MITKDashboardSetup.cmake index db3c968991..2a3bb37e77 100644 --- a/CMake/MITKDashboardSetup.cmake +++ b/CMake/MITKDashboardSetup.cmake @@ -1,155 +1,153 @@ # This file is intended to be included at the end of a custom MITKDashboardScript.TEMPLATE.cmake file list(APPEND CTEST_NOTES_FILES "${CTEST_SCRIPT_DIRECTORY}/${CTEST_SCRIPT_NAME}") # # Automatically determined properties # set(MY_OPERATING_SYSTEM ) if(UNIX) # Download a utility script set(url "http://mitk.org/git/?p=MITK.git;a=blob_plain;f=CMake/mitkDetectOS.sh;hb=${hb}") set(dest "${CTEST_SCRIPT_DIRECTORY}/mitkDetectOS.sh") downloadFile("${url}" "${dest}") execute_process(COMMAND sh "${dest}" RESULT_VARIABLE _result OUTPUT_VARIABLE _out OUTPUT_STRIP_TRAILING_WHITESPACE) if(NOT _result) set(MY_OPERATING_SYSTEM "${_out}") endif() endif() if(NOT MY_OPERATING_SYSTEM) set(MY_OPERATING_SYSTEM "${CMAKE_HOST_SYSTEM}") # Windows 7, Linux-2.6.32, Darwin... endif() site_name(CTEST_SITE) if(NOT DEFINED MITK_USE_QT) set(MITK_USE_QT 1) endif() if(MITK_USE_QT) if(NOT QT_QMAKE_EXECUTABLE) find_program(QT_QMAKE_EXECUTABLE NAMES qmake qmake-qt4 HINTS ${QT_BINARY_DIR}) endif() execute_process(COMMAND ${QT_QMAKE_EXECUTABLE} --version OUTPUT_VARIABLE MY_QT_VERSION RESULT_VARIABLE qmake_error) if(qmake_error) message(FATAL_ERROR "Error when executing ${QT_QMAKE_EXECUTABLE} --version\n${qmake_error}") endif() string(REGEX REPLACE ".*Qt version ([0-9.]+) .*" "\\1" MY_QT_VERSION ${MY_QT_VERSION}) endif() # # Project specific properties # if(NOT CTEST_BUILD_NAME) if(MITK_USE_QT) set(CTEST_BUILD_NAME "${MY_OPERATING_SYSTEM} ${MY_COMPILER} Qt${MY_QT_VERSION} ${CTEST_BUILD_CONFIGURATION}") else() set(CTEST_BUILD_NAME "${MY_OPERATING_SYSTEM} ${MY_COMPILER} ${CTEST_BUILD_CONFIGURATION}") endif() set(CTEST_BUILD_NAME "${CTEST_BUILD_NAME}${CTEST_BUILD_NAME_SUFFIX}") endif() set(PROJECT_BUILD_DIR "MITK-build") set(CTEST_PATH "$ENV{PATH}") if(WIN32) if(CMAKE_CL_64) set(CMAKE_LIBRARY_ARCHITECTURE x64) else() set(CMAKE_LIBRARY_ARCHITECTURE x86) endif() find_path(OPENCV_BIN_DIR opencv_core2411.dll PATHS "${CTEST_BINARY_DIRECTORY}/ep/${CMAKE_LIBRARY_ARCHITECTURE}" PATH_SUFFIXES vc10/bin vc11/bin vc12/bin vc13/bin vc14/bin NO_DEFAULT_PATH ) message("OpenCV runtime path: ${OPENCV_BIN_DIR}") set(SOFA_BINARY_DIR "${CTEST_BINARY_DIRECTORY}/ep/src/SOFA-build/bin/${CTEST_BUILD_CONFIGURATION}") set(BLUEBERRY_RUNTIME_DIR "${CTEST_BINARY_DIRECTORY}/MITK-build/bin/plugins/${CTEST_BUILD_CONFIGURATION}") set(CTEST_PATH "${CTEST_PATH};${CTEST_BINARY_DIRECTORY}/ep/bin;${QT_BINARY_DIR};${SOFA_BINARY_DIR};${BLUEBERRY_RUNTIME_DIR};${OPENCV_BIN_DIR}") endif() set(ENV{PATH} "${CTEST_PATH}") -set(SUPERBUILD_TARGETS "") - # If the dashscript doesn't define a GIT_REPOSITORY variable, let's define it here. if(NOT DEFINED GIT_REPOSITORY OR GIT_REPOSITORY STREQUAL "") set(GIT_REPOSITORY "http://git.mitk.org/MITK.git") endif() # # Display build info # message("Site name: ${CTEST_SITE}") message("Build name: ${CTEST_BUILD_NAME}") message("Script Mode: ${SCRIPT_MODE}") message("Coverage: ${WITH_COVERAGE}, MemCheck: ${WITH_MEMCHECK}") # # Set initial cache options # if(CTEST_CMAKE_GENERATOR MATCHES ".*Makefiles.*") set(CTEST_USE_LAUNCHERS 1) else() set(CTEST_USE_LAUNCHERS 0) endif() set(ENV{CTEST_USE_LAUNCHERS_DEFAULT} ${CTEST_USE_LAUNCHERS}) # Remove this if block after all dartclients work if(DEFINED ADDITIONNAL_CMAKECACHE_OPTION) message(WARNING "Rename ADDITIONNAL to ADDITIONAL in your dartlclient script: ${CTEST_SCRIPT_DIRECTORY}/${CTEST_SCRIPT_NAME}") set(ADDITIONAL_CMAKECACHE_OPTION ${ADDITIONNAL_CMAKECACHE_OPTION}) endif() if(NOT DEFINED MITK_BUILD_CONFIGURATION) set(MITK_BUILD_CONFIGURATION "All") endif() if(NOT DEFINED MITK_VTK_DEBUG_LEAKS) set(MITK_VTK_DEBUG_LEAKS 1) endif() set(INITIAL_CMAKECACHE_OPTIONS " SUPERBUILD_EXCLUDE_MITKBUILD_TARGET:BOOL=TRUE MITK_BUILD_CONFIGURATION:STRING=${MITK_BUILD_CONFIGURATION} MITK_VTK_DEBUG_LEAKS:BOOL=${MITK_VTK_DEBUG_LEAKS} ${ADDITIONAL_CMAKECACHE_OPTION} ") if(MITK_USE_QT) set(INITIAL_CMAKECACHE_OPTIONS "${INITIAL_CMAKECACHE_OPTIONS} QT_QMAKE_EXECUTABLE:FILEPATH=${QT_QMAKE_EXECUTABLE}") endif() # Write a cache file for populating the MITK initial cache (not the superbuild cache). # This can be used to provide variables which are not passed through the # superbuild process to the MITK configure step) if(MITK_INITIAL_CACHE) set(mitk_cache_file "${CTEST_SCRIPT_DIRECTORY}/mitk_initial_cache.txt") file(WRITE "${mitk_cache_file}" "${MITK_INITIAL_CACHE}") set(INITIAL_CMAKECACHE_OPTIONS "${INITIAL_CMAKECACHE_OPTIONS} MITK_INITIAL_CACHE_FILE:INTERNAL=${mitk_cache_file} ") endif() # # Download and include dashboard driver script # set(url "http://mitk.org/git/?p=MITK.git;a=blob_plain;f=CMake/MITKDashboardDriverScript.cmake;hb=${hb}") set(dest ${CTEST_SCRIPT_DIRECTORY}/${CTEST_SCRIPT_NAME}.driver) downloadFile("${url}" "${dest}") include(${dest}) diff --git a/CMakeExternals/ACVD.cmake b/CMakeExternals/ACVD.cmake index 0faebf0cf8..150d414396 100644 --- a/CMakeExternals/ACVD.cmake +++ b/CMakeExternals/ACVD.cmake @@ -1,36 +1,45 @@ #----------------------------------------------------------------------------- # ACVD #----------------------------------------------------------------------------- if(MITK_USE_ACVD) # Sanity checks if(DEFINED ACVD_DIR AND NOT EXISTS ${ACVD_DIR}) message(FATAL_ERROR "ACVD_DIR variable is defined but corresponds to non-existing directory") endif() set(proj ACVD) set(proj_DEPENDENCIES VTK) set(ACVD_DEPENDS ${proj}) if(NOT DEFINED ACVD_DIR) + + set(additional_args ) + if(CTEST_USE_LAUNCHERS) + list(APPEND additional_args + "-DCMAKE_PROJECT_${proj}_INCLUDE:FILEPATH=${CMAKE_ROOT}/Modules/CTestUseLaunchers.cmake" + ) + endif() + ExternalProject_Add(${proj} LIST_SEPARATOR ${sep} URL ${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/ACVD-vtk6_3d5ae388.tar.gz URL_MD5 5d47000a6ee3be0ec8ac7dedc04896c0 PATCH_COMMAND ${PATCH_COMMAND} -N -p1 -i ${CMAKE_CURRENT_LIST_DIR}/ACVD-vtk6_3d5ae388.patch CMAKE_GENERATOR ${gen} CMAKE_ARGS ${ep_common_args} + ${additional_args} -DUSE_MULTITHREADING:BOOL=ON -DBUILD_EXAMPLES:BOOL=OFF -DVTK_DIR:PATH=${VTK_DIR} DEPENDS ${proj_DEPENDENCIES} ) set(ACVD_DIR ${ep_prefix}) mitkFunctionInstallExternalCMakeProject(${proj}) else() mitkMacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}") endif() endif() diff --git a/CMakeExternals/ANN.cmake b/CMakeExternals/ANN.cmake index 49b0ff6666..a46fa41487 100644 --- a/CMakeExternals/ANN.cmake +++ b/CMakeExternals/ANN.cmake @@ -1,40 +1,48 @@ #----------------------------------------------------------------------------- # ANN #----------------------------------------------------------------------------- if(MITK_USE_ANN) # Sanity checks if(DEFINED ANN_DIR AND NOT EXISTS ${ANN_DIR}) message(FATAL_ERROR "ANN_DIR variable is defined but corresponds to non-existing directory") endif() set(proj ANN) set(proj_DEPENDENCIES ) set(ANN_DEPENDS ${proj}) if(NOT DEFINED ANN_DIR) + set(additional_args ) + if(CTEST_USE_LAUNCHERS) + list(APPEND additional_args + "-DCMAKE_PROJECT_${proj}_INCLUDE:FILEPATH=${CMAKE_ROOT}/Modules/CTestUseLaunchers.cmake" + ) + endif() + set(patch_cmd ${CMAKE_COMMAND} -Dproj:STRING=${proj} -Dproj_target:STRING=ann -P ${CMAKE_CURRENT_LIST_DIR}/GenerateDefaultCMakeBuildSystem.cmake) ExternalProject_Add(${proj} LIST_SEPARATOR ${sep} URL ${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/ann_1.1.2.tar.gz URL_MD5 7ffaacc7ea79ca39d4958a6378071365 PATCH_COMMAND ${patch_cmd} CMAKE_GENERATOR ${gen} CMAKE_ARGS ${ep_common_args} + ${additional_args} DEPENDS ${proj_DEPENDENCIES} ) set(ANN_DIR ${ep_prefix}/lib/cmake/ANN) mitkFunctionInstallExternalCMakeProject(${proj}) else() mitkMacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}") endif() endif() diff --git a/CMakeExternals/Boost.cmake b/CMakeExternals/Boost.cmake index be42a2b2cd..7c5aab1a24 100644 --- a/CMakeExternals/Boost.cmake +++ b/CMakeExternals/Boost.cmake @@ -1,179 +1,179 @@ #----------------------------------------------------------------------------- # Boost #----------------------------------------------------------------------------- if(MITK_USE_Boost) # Sanity checks if(DEFINED BOOST_ROOT AND NOT EXISTS ${BOOST_ROOT}) message(FATAL_ERROR "BOOST_ROOT variable is defined but corresponds to non-existing directory") endif() string(REPLACE "^^" ";" MITK_USE_Boost_LIBRARIES "${MITK_USE_Boost_LIBRARIES}") set(proj Boost) set(proj_DEPENDENCIES ) set(Boost_DEPENDS ${proj}) if(NOT DEFINED BOOST_ROOT AND NOT MITK_USE_SYSTEM_Boost) set(_boost_version 1_56) set(_boost_install_include_dir include/boost) if(WIN32) - set(_boost_install_include_dir include/boost-${_boost_version}) + set(_boost_install_include_dir include/boost-${_boost_version}/boost) endif() set(_boost_libs ) set(_with_boost_libs ) set(_install_lib_dir ) # Set the boost root to the libraries install directory set(BOOST_ROOT "${ep_prefix}") if(MITK_USE_Boost_LIBRARIES) string(REPLACE ";" "," _boost_libs "${MITK_USE_Boost_LIBRARIES}") foreach(_boost_lib ${MITK_USE_Boost_LIBRARIES}) list(APPEND _with_boost_libs ${_with_boost_libs} --with-${_boost_lib}) endforeach() endif() if(CMAKE_SIZEOF_VOID_P EQUAL 8) set(_boost_address_model "address-model=64") else() set(_boost_address_model "address-model=32") endif() if(WIN32) set(_shell_extension .bat) set(_boost_layout) if(MSVC) if(MSVC_VERSION EQUAL 1600) set(_boost_toolset "msvc-10.0") elseif(MSVC_VERSION EQUAL 1700) set(_boost_toolset "msvc-11.0") elseif(MSVC_VERSION EQUAL 1800) set(_boost_toolset "msvc-12.0") endif() endif() set(_install_lib_dir "--libdir=/bin") set(WIN32_CMAKE_SCRIPT ${ep_prefix}/src/${proj}-cmake/MoveBoostLibsToLibDirForWindows.cmake) configure_file(${CMAKE_CURRENT_SOURCE_DIR}/CMakeExternals/MoveBoostLibsToLibDirForWindows.cmake.in ${WIN32_CMAKE_SCRIPT} @ONLY) set(_windows_move_libs_cmd COMMAND ${CMAKE_COMMAND} -P ${WIN32_CMAKE_SCRIPT}) else() set(_shell_extension .sh) set(_boost_layout "--layout=tagged") endif() set (APPLE_SYSROOT_FLAG) if(APPLE) set(APPLE_CMAKE_SCRIPT ${ep_prefix}/src/${proj}-cmake/ChangeBoostLibsInstallNameForMac.cmake) configure_file(${CMAKE_CURRENT_SOURCE_DIR}/CMakeExternals/ChangeBoostLibsInstallNameForMac.cmake.in ${APPLE_CMAKE_SCRIPT} @ONLY) set(_macos_change_install_name_cmd COMMAND ${CMAKE_COMMAND} -P ${APPLE_CMAKE_SCRIPT}) # Set OSX_SYSROOT if (NOT ${CMAKE_OSX_SYSROOT} STREQUAL "") set (APPLE_SYSROOT_FLAG --sysroot=${CMAKE_OSX_SYSROOT}) endif() endif() set(_boost_variant "$<$:debug>$<$:release>") set(_boost_link shared) if(NOT BUILD_SHARED_LIBS) set(_boost_link static) endif() set(_boost_cxxflags ) if(CMAKE_CXX_FLAGS OR MITK_CXX11_FLAG) set(_boost_cxxflags "cxxflags=${MITK_CXX11_FLAG} ${CMAKE_CXX_FLAGS}") endif() set(_boost_linkflags ) if(BUILD_SHARED_LIBS AND _install_rpath_linkflag) set(_boost_linkflags "linkflags=${_install_rpath_linkflag}") endif() set(_build_cmd "/b2" ${APPLE_SYSROOT_FLAG} ${_boost_layout} "--prefix=" ${_install_lib_dir} ${_with_boost_libs} # Use the option below to view the shell commands (for debugging) #-d+4 variant=${_boost_variant} link=${_boost_link} ${_boost_cxxflags} ${_boost_linkflags} ${_boost_address_model} threading=multi runtime-link=shared -q ) if(MITK_USE_Boost_LIBRARIES) set(_boost_build_cmd BUILD_COMMAND ${_build_cmd}) set(_install_cmd ${_build_cmd} install ${_macos_change_install_name_cmd} ${_windows_move_libs_cmd}) else() set(_boost_build_cmd BUILD_COMMAND ${CMAKE_COMMAND} -E echo "no binary libraries") set(_install_cmd ${CMAKE_COMMAND} -E echo "copying Boost header..." COMMAND ${CMAKE_COMMAND} -E copy_directory "/boost" "/${_boost_install_include_dir}") endif() ExternalProject_Add(${proj} LIST_SEPARATOR ${sep} URL ${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/boost_${_boost_version}_0.tar.bz2 URL_MD5 a744cf167b05d72335f27c88115f211d # We use in-source builds for Boost BINARY_DIR ${ep_prefix}/src/${proj} CONFIGURE_COMMAND "/bootstrap${_shell_extension}" --with-toolset=${_boost_toolset} --with-libraries=${_boost_libs} "--prefix=" ${_boost_build_cmd} INSTALL_COMMAND ${_install_cmd} DEPENDS ${proj_DEPENDENCIES} ) ExternalProject_Get_Property(${proj} install_dir) if(WIN32) set(BOOST_LIBRARYDIR "${install_dir}/lib") endif() # Manual install commands (for a MITK super-build install) # until the Boost CMake system is used. # We just copy the include directory install(DIRECTORY "${install_dir}/${_boost_install_include_dir}" DESTINATION "include" COMPONENT dev ) if(MITK_USE_Boost_LIBRARIES) # Copy the boost libraries file(GLOB _boost_libs "${install_dir}/lib/libboost*.so*" "${install_dir}/lib/libboost*.dylib") install(FILES ${_boost_libs} DESTINATION "lib" COMPONENT runtime) file(GLOB _boost_libs "${install_dir}/bin/libboost*.dll") install(FILES ${_boost_libs} DESTINATION "bin" COMPONENT runtime) file(GLOB _boost_libs "${install_dir}/lib/libboost*.lib" "${install_dir}/lib/libboost*.a") install(FILES ${_boost_libs} DESTINATION "lib" COMPONENT dev) endif() else() mitkMacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}") endif() endif() diff --git a/CMakeExternals/CTK.cmake b/CMakeExternals/CTK.cmake index d30db02761..cc8c807b41 100644 --- a/CMakeExternals/CTK.cmake +++ b/CMakeExternals/CTK.cmake @@ -1,110 +1,116 @@ #----------------------------------------------------------------------------- # CTK #----------------------------------------------------------------------------- if(MITK_USE_CTK) # Sanity checks if(DEFINED CTK_DIR AND NOT EXISTS ${CTK_DIR}) message(FATAL_ERROR "CTK_DIR variable is defined but corresponds to non-existing directory") endif() set(proj CTK) set(proj_DEPENDENCIES ) set(CTK_DEPENDS ${proj}) if(NOT DEFINED CTK_DIR) set(revision_tag d8cd14e7) #IF(${proj}_REVISION_TAG) # SET(revision_tag ${${proj}_REVISION_TAG}) #ENDIF() set(ctk_optional_cache_args ) if(MITK_USE_Python) if(NOT MITK_USE_SYSTEM_PYTHON) list(APPEND proj_DEPENDENCIES Python) endif() list(APPEND ctk_optional_cache_args -DCTK_LIB_Scripting/Python/Widgets:BOOL=ON -DCTK_ENABLE_Python_Wrapping:BOOL=ON -DCTK_APP_ctkSimplePythonShell:BOOL=ON -DPYTHON_EXECUTABLE:FILEPATH=${PYTHON_EXECUTABLE} -DPYTHON_INCLUDE_DIR:PATH=${PYTHON_INCLUDE_DIR} -DPYTHON_INCLUDE_DIR2:PATH=${PYTHON_INCLUDE_DIR2} -DPYTHON_LIBRARY:FILEPATH=${PYTHON_LIBRARY} ) else() list(APPEND ctk_optional_cache_args -DCTK_LIB_Scripting/Python/Widgets:BOOL=OFF -DCTK_ENABLE_Python_Wrapping:BOOL=OFF -DCTK_APP_ctkSimplePythonShell:BOOL=OFF ) endif() if(MITK_USE_DCMTK) list(APPEND ctk_optional_cache_args -DDCMTK_DIR:PATH=${DCMTK_DIR} -DDCMTK_CMAKE_DEBUG_POSTFIX:STRING=d ) list(APPEND proj_DEPENDENCIES DCMTK) else() list(APPEND ctk_optional_cache_args -DDCMTK_URL:STRING=${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/CTK_DCMTK_085525e6.tar.gz ) endif() + if(CTEST_USE_LAUNCHERS) + list(APPEND ctk_optional_cache_args + "-DCMAKE_PROJECT_${proj}_INCLUDE:FILEPATH=${CMAKE_ROOT}/Modules/CTestUseLaunchers.cmake" + ) + endif() + set (ctk_qt_args -DCTK_QT_VERSION:STRING=${DESIRED_QT_VERSION}) if (DESIRED_QT_VERSION MATCHES "4") list(APPEND ctk_qt_args -DQT_QMAKE_EXECUTABLE:FILEPATH=${QT_QMAKE_EXECUTABLE}) endif() FOREACH(type RUNTIME ARCHIVE LIBRARY) IF(DEFINED CTK_PLUGIN_${type}_OUTPUT_DIRECTORY) LIST(APPEND mitk_optional_cache_args -DCTK_PLUGIN_${type}_OUTPUT_DIRECTORY:PATH=${CTK_PLUGIN_${type}_OUTPUT_DIRECTORY}) ENDIF() ENDFOREACH() ExternalProject_Add(${proj} LIST_SEPARATOR ${sep} URL ${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/CTK_${revision_tag}.tar.gz URL_MD5 2f1255494de6ae19aae3d4dc5f2ea6de UPDATE_COMMAND "" INSTALL_COMMAND "" CMAKE_GENERATOR ${gen} CMAKE_ARGS ${ep_common_args} ${ctk_optional_cache_args} ${ctk_qt_args} # The CTK PluginFramework cannot cope with # a non-empty CMAKE_DEBUG_POSTFIX for the plugin # libraries yet. -DCMAKE_DEBUG_POSTFIX:STRING= -DGit_EXECUTABLE:FILEPATH=${GIT_EXECUTABLE} -DGIT_EXECUTABLE:FILEPATH=${GIT_EXECUTABLE} -DCTK_LIB_CommandLineModules/Backend/LocalProcess:BOOL=ON -DCTK_LIB_CommandLineModules/Frontend/QtGui:BOOL=ON -DCTK_LIB_PluginFramework:BOOL=ON -DCTK_LIB_DICOM/Widgets:BOOL=ON -DCTK_LIB_XNAT/Core:BOOL=ON -DCTK_PLUGIN_org.commontk.eventadmin:BOOL=ON -DCTK_PLUGIN_org.commontk.configadmin:BOOL=ON -DCTK_USE_GIT_PROTOCOL:BOOL=OFF -DDCMTK_URL:STRING=${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/CTK_DCMTK_085525e6.tar.gz -DqRestAPI_URL:STRING=${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/qRestAPI_5f3a03b1.tar.gz DEPENDS ${proj_DEPENDENCIES} ) ExternalProject_Get_Property(${proj} binary_dir) set(CTK_DIR ${binary_dir}) #set(CTK_DIR ${ep_prefix}) #mitkFunctionInstallExternalCMakeProject(${proj}) else() mitkMacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}") endif() endif() diff --git a/CMakeExternals/CppUnit.cmake b/CMakeExternals/CppUnit.cmake index 009ad6a164..a5d4298dda 100644 --- a/CMakeExternals/CppUnit.cmake +++ b/CMakeExternals/CppUnit.cmake @@ -1,37 +1,45 @@ #----------------------------------------------------------------------------- # CppUnit #----------------------------------------------------------------------------- # Sanity checks if(DEFINED CppUnit_DIR AND NOT EXISTS ${CppUnit_DIR}) message(FATAL_ERROR "CppUnit_DIR variable is defined but corresponds to non-existing directory") endif() set(proj CppUnit) set(proj_DEPENDENCIES ) set(${proj}_DEPENDS ${proj}) if(NOT DEFINED CppUnit_DIR) + set(additional_args ) + if(CTEST_USE_LAUNCHERS) + list(APPEND additional_args + "-DCMAKE_PROJECT_${proj}_INCLUDE:FILEPATH=${CMAKE_ROOT}/Modules/CTestUseLaunchers.cmake" + ) + endif() + ExternalProject_Add(${proj} LIST_SEPARATOR ${sep} URL ${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/cppunit-1.12.1.tar.gz URL_MD5 bd30e9cf5523cdfc019b94f5e1d7fd19 PATCH_COMMAND ${PATCH_COMMAND} -N -p1 -i ${CMAKE_CURRENT_LIST_DIR}/CppUnit-1.12.1.patch COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_LIST_DIR}/${proj}config.h.cmake /config/config.h.cmake COMMAND ${CMAKE_COMMAND} -Dproj=${proj} -Dproj_target:STRING=cppunit -P ${CMAKE_CURRENT_LIST_DIR}/GenerateDefaultCMakeBuildSystem.cmake CMAKE_GENERATOR ${gen} CMAKE_ARGS ${ep_common_args} + ${additional_args} DEPENDS ${proj_DEPENDENCIES} ) set(${proj}_DIR ${ep_prefix}/lib/cmake/CppUnit) mitkFunctionInstallExternalCMakeProject(${proj}) else() mitkMacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}") endif() diff --git a/CMakeExternals/DCMTK.cmake b/CMakeExternals/DCMTK.cmake index d78d090851..cf64305f75 100644 --- a/CMakeExternals/DCMTK.cmake +++ b/CMakeExternals/DCMTK.cmake @@ -1,57 +1,65 @@ #----------------------------------------------------------------------------- # DCMTK #----------------------------------------------------------------------------- if(MITK_USE_DCMTK) # Sanity checks if(DEFINED DCMTK_DIR AND NOT EXISTS ${DCMTK_DIR}) message(FATAL_ERROR "DCMTK_DIR variable is defined but corresponds to non-existing directory") endif() set(proj DCMTK) set(proj_DEPENDENCIES ) set(DCMTK_DEPENDS ${proj}) if(NOT DEFINED DCMTK_DIR) if(DCMTK_DICOM_ROOT_ID) set(DCMTK_CXX_FLAGS "${DCMTK_CXX_FLAGS} -DSITE_UID_ROOT=\\\"${DCMTK_DICOM_ROOT_ID}\\\"") set(DCMTK_C_FLAGS "${DCMTK_CXX_FLAGS} -DSITE_UID_ROOT=\\\"${DCMTK_DICOM_ROOT_ID}\\\"") endif() + set(additional_args ) + if(CTEST_USE_LAUNCHERS) + list(APPEND additional_args + "-DCMAKE_PROJECT_${proj}_INCLUDE:FILEPATH=${CMAKE_ROOT}/Modules/CTestUseLaunchers.cmake" + ) + endif() + ExternalProject_Add(${proj} LIST_SEPARATOR ${sep} URL ${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/dcmtk-3.6.1_20121102.tar.gz URL_MD5 39d97456027a4219ce47e566e3ab123b # See http://bugs.mitk.org/show_bug.cgi?id=14513 except for the changes # in dcmtkMacros.cmake which allow installing release and debug executables # of dcmtk in the same install prefix. # The other patches were originally for the Xcode generator, but we always # apply them for consistency. PATCH_COMMAND ${PATCH_COMMAND} -N -p1 -i ${CMAKE_CURRENT_LIST_DIR}/DCMTK-3.6.1.patch CMAKE_GENERATOR ${gen} CMAKE_ARGS ${ep_common_args} + ${additional_args} #-DDCMTK_OVERWRITE_WIN32_COMPILER_FLAGS:BOOL=OFF "-DCMAKE_CXX_FLAGS:STRING=${CMAKE_CXX_FLAGS} ${DCMTK_CXX_FLAGS}" "-DCMAKE_C_FLAGS:STRING=${CMAKE_C_FLAGS} ${DCMTK_C_FLAGS}" #-DDCMTK_INSTALL_BINDIR:STRING=bin/${CMAKE_CFG_INTDIR} #-DDCMTK_INSTALL_LIBDIR:STRING=lib/${CMAKE_CFG_INTDIR} -DDCMTK_WITH_DOXYGEN:BOOL=OFF -DDCMTK_WITH_ZLIB:BOOL=OFF # see bug #9894 -DDCMTK_WITH_OPENSSL:BOOL=OFF # see bug #9894 -DDCMTK_WITH_PNG:BOOL=OFF # see bug #9894 -DDCMTK_WITH_TIFF:BOOL=OFF # see bug #9894 -DDCMTK_WITH_XML:BOOL=OFF # see bug #9894 -DDCMTK_WITH_ICONV:BOOL=OFF # see bug #9894 DEPENDS ${proj_DEPENDENCIES} ) set(DCMTK_DIR ${ep_prefix}) mitkFunctionInstallExternalCMakeProject(${proj}) else() mitkMacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}") endif() endif() diff --git a/CMakeExternals/GDCM.cmake b/CMakeExternals/GDCM.cmake index a8f4d72266..95301b4581 100644 --- a/CMakeExternals/GDCM.cmake +++ b/CMakeExternals/GDCM.cmake @@ -1,46 +1,54 @@ #----------------------------------------------------------------------------- # GDCM #----------------------------------------------------------------------------- # Sanity checks if(DEFINED GDCM_DIR AND NOT EXISTS ${GDCM_DIR}) message(FATAL_ERROR "GDCM_DIR variable is defined but corresponds to non-existing directory") endif() # Check if an external ITK build tree was specified. # If yes, use the GDCM from ITK, otherwise ITK will complain if(ITK_DIR) find_package(ITK) if(ITK_GDCM_DIR) set(GDCM_DIR ${ITK_GDCM_DIR}) endif() endif() set(proj GDCM) set(proj_DEPENDENCIES ) set(GDCM_DEPENDS ${proj}) if(NOT DEFINED GDCM_DIR) + set(additional_args ) + if(CTEST_USE_LAUNCHERS) + list(APPEND additional_args + "-DCMAKE_PROJECT_${proj}_INCLUDE:FILEPATH=${CMAKE_ROOT}/Modules/CTestUseLaunchers.cmake" + ) + endif() + ExternalProject_Add(${proj} LIST_SEPARATOR ${sep} URL ${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/gdcm-2.4.1.tar.bz2 URL_MD5 1120f9a5ebcef7df6933ca83545f514d PATCH_COMMAND ${PATCH_COMMAND} -N -p1 -i ${CMAKE_CURRENT_LIST_DIR}/GDCM-2.4.1.patch CMAKE_GENERATOR ${gen} CMAKE_ARGS ${ep_common_args} + ${additional_args} -DGDCM_BUILD_SHARED_LIBS:BOOL=ON DEPENDS ${proj_DEPENDENCIES} ) set(GDCM_DIR ${ep_prefix}) mitkFunctionInstallExternalCMakeProject(${proj}) else() mitkMacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}") find_package(GDCM) endif() diff --git a/CMakeExternals/GLEW.cmake b/CMakeExternals/GLEW.cmake index 344fc9e4d4..457198f7e6 100644 --- a/CMakeExternals/GLEW.cmake +++ b/CMakeExternals/GLEW.cmake @@ -1,36 +1,44 @@ #----------------------------------------------------------------------------- # GLEW #----------------------------------------------------------------------------- # Sanity checks if(DEFINED GLEW_DIR AND NOT EXISTS ${GLEW_DIR}) message(FATAL_ERROR "GLEW_DIR variable is defined but corresponds to non-existing directory") endif() set(proj GLEW) set(proj_DEPENDENCIES ) set(GLEW_DEPENDS ${proj}) if(NOT DEFINED GLEW_DIR) + set(additional_args ) + if(CTEST_USE_LAUNCHERS) + list(APPEND additional_args + "-DCMAKE_PROJECT_${proj}_INCLUDE:FILEPATH=${CMAKE_ROOT}/Modules/CTestUseLaunchers.cmake" + ) + endif() + set(patch_cmd ${CMAKE_COMMAND} -Dproj:STRING=${proj} -Dproj_target:STRING=glew -P ${CMAKE_CURRENT_LIST_DIR}/GenerateDefaultCMakeBuildSystem.cmake) ExternalProject_Add(${proj} LIST_SEPARATOR ${sep} URL ${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/glew-1.10.0.tgz URL_MD5 2f09e5e6cb1b9f3611bcac79bc9c2d5d PATCH_COMMAND ${patch_cmd} CMAKE_GENERATOR ${gen} CMAKE_ARGS ${ep_common_args} + ${additional_args} DEPENDS ${proj_DEPENDENCIES} ) set(GLEW_DIR ${ep_prefix}) mitkFunctionInstallExternalCMakeProject(${proj}) else() mitkMacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}") endif() diff --git a/CMakeExternals/GLUT.cmake b/CMakeExternals/GLUT.cmake index 0e5f26650f..e4ab34dd69 100644 --- a/CMakeExternals/GLUT.cmake +++ b/CMakeExternals/GLUT.cmake @@ -1,48 +1,56 @@ #----------------------------------------------------------------------------- # freeglut #----------------------------------------------------------------------------- if(MITK_USE_GLUT) # Sanity checks if(DEFINED GLUT_DIR AND NOT EXISTS ${GLUT_DIR}) message(FATAL_ERROR "GLUT_DIR variable is defined but corresponds to non-existing directory") endif() set(proj GLUT) set(proj_DEPENDENCIES ) set(${proj}_DEPENDS ${proj}) if(NOT DEFINED GLUT_DIR) if(APPLE) find_library(GLUT_LIBRARY GLUT) # add_library(GLUT SHARED IMPORTED) # set_property(TARGET GLUT PROPERTY IMPORTED_LOCATION ${GLUT_LIBRARY}) mitkMacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}") get_filename_component(GLUT_DIR ${GLUT_LIBRARY} PATH) else() set(patch_cmd ${CMAKE_COMMAND} -Dproj:STRING=${proj} -Dproj_target:STRING=freeglut -P ${CMAKE_CURRENT_LIST_DIR}/GenerateDefaultCMakeBuildSystem.cmake) + set(additional_args ) + if(CTEST_USE_LAUNCHERS) + list(APPEND additional_args + "-DCMAKE_PROJECT_${proj}_INCLUDE:FILEPATH=${CMAKE_ROOT}/Modules/CTestUseLaunchers.cmake" + ) + endif() + ExternalProject_Add(${proj} LIST_SEPARATOR ${sep} URL http://mitk.org/download/thirdparty/freeglut-2.8.1.tar.gz URL_MD5 918ffbddcffbac83c218bc52355b6d5a PATCH_COMMAND ${patch_cmd} CMAKE_GENERATOR ${gen} CMAKE_ARGS ${ep_common_args} + ${additional_args} DEPENDS ${proj_DEPENDENCIES} ) set(GLUT_DIR ${ep_prefix}) mitkFunctionInstallExternalCMakeProject(${proj}) endif() else() mitkMacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}") endif() endif() diff --git a/CMakeExternals/HDF5.cmake b/CMakeExternals/HDF5.cmake index 13091b6970..3d6c1867eb 100644 --- a/CMakeExternals/HDF5.cmake +++ b/CMakeExternals/HDF5.cmake @@ -1,46 +1,54 @@ #----------------------------------------------------------------------------- # HDF5 #----------------------------------------------------------------------------- if(MITK_USE_HDF5) # Sanity checks if(DEFINED HDF5_DIR AND NOT EXISTS ${HDF5_DIR}) message(FATAL_ERROR "HDF5_DIR variable is defined but corresponds to non-existing directory") endif() set(proj HDF5) set(proj_DEPENDENCIES ) set(HDF5_DEPENDS ${proj}) if(NOT DEFINED HDF5_DIR) + set(additional_args ) + if(CTEST_USE_LAUNCHERS) + list(APPEND additional_args + "-DCMAKE_PROJECT_${proj}_INCLUDE:FILEPATH=${CMAKE_ROOT}/Modules/CTestUseLaunchers.cmake" + ) + endif() + # We might build static libs with -DBUILD_SHARED_LIBS=0 but this conflicts with # the in ITK integrated version! So we need to go the way with dynamic libs. Too # bad :( This would be fixed by using an external HDF-Installation with ITK/VTK ExternalProject_Add(${proj} URL ${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/hdf5-1.8.12.tar.gz URL_MD5 d804802feb99b87fc668a90e6fa34411 CMAKE_GENERATOR ${gen} CMAKE_ARGS ${ep_common_args} + ${additional_args} -DHDF5_BUILD_HL_LIB:BOOL=ON -DHDF5_BUILD_CPP_LIB:BOOL=ON -DCMAKE_INSTALL_PREFIX:PATH= DEPENDS ${proj_DEPENDENCIES} ) ExternalProject_Get_Property(${proj} install_dir) if(WIN32) set(HDF5_DIR ${install_dir}/cmake/hdf5) else() set(HDF5_DIR ${install_dir}/share/cmake/hdf5) endif() else() mitkMacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}") endif() endif(MITK_USE_HDF5) diff --git a/CMakeExternals/ITK.cmake b/CMakeExternals/ITK.cmake index 9389663998..855f8df88b 100644 --- a/CMakeExternals/ITK.cmake +++ b/CMakeExternals/ITK.cmake @@ -1,82 +1,88 @@ #----------------------------------------------------------------------------- # ITK #----------------------------------------------------------------------------- # Sanity checks if(DEFINED ITK_DIR AND NOT EXISTS ${ITK_DIR}) message(FATAL_ERROR "ITK_DIR variable is defined but corresponds to non-existing directory") endif() set(proj ITK) set(proj_DEPENDENCIES GDCM) if(MITK_USE_OpenCV) list(APPEND proj_DEPENDENCIES OpenCV) endif() if(MITK_USE_HDF5) list(APPEND proj_DEPENDENCIES HDF5) endif() set(ITK_DEPENDS ${proj}) if(NOT DEFINED ITK_DIR) set(additional_cmake_args ) if(MINGW) set(additional_cmake_args -DCMAKE_USE_WIN32_THREADS:BOOL=ON -DCMAKE_USE_PTHREADS:BOOL=OFF) endif() list(APPEND additional_cmake_args -DUSE_WRAP_ITK:BOOL=OFF ) if(MITK_USE_OpenCV) list(APPEND additional_cmake_args -DModule_ITKVideoBridgeOpenCV:BOOL=ON -DOpenCV_DIR:PATH=${OpenCV_DIR} ) endif() # Keep the behaviour of ITK 4.3 which by default turned on ITK Review # see MITK bug #17338 list(APPEND additional_cmake_args -DModule_ITKReview:BOOL=ON # for 4.7, the OpenJPEG is needed by review but the variable must be set -DModule_ITKOpenJPEG:BOOL=ON ) + if(CTEST_USE_LAUNCHERS) + list(APPEND additional_cmake_args + "-DCMAKE_PROJECT_${proj}_INCLUDE:FILEPATH=${CMAKE_ROOT}/Modules/CTestUseLaunchers.cmake" + ) + endif() + set(vcl_constexpr_patch) if(GCC_VERSION VERSION_LESS 4.7 AND GCC_VERSION VERSION_GREATER 4) set(vcl_constexpr_patch COMMAND ${PATCH_COMMAND} -N -p1 -i ${CMAKE_CURRENT_LIST_DIR}/ITK-4.5.1-gcc-4.6.patch ) endif() ExternalProject_Add(${proj} LIST_SEPARATOR ${sep} URL ${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/InsightToolkit-4.7.1-20c0592.tar.gz URL_MD5 f778a5f0e297c06dc629c33ec45733dc # work with external GDCM PATCH_COMMAND ${PATCH_COMMAND} -N -p1 -i ${CMAKE_CURRENT_LIST_DIR}/ITK-4.5.1.patch ${vcl_constexpr_patch} CMAKE_GENERATOR ${gen} CMAKE_ARGS ${ep_common_args} ${additional_cmake_args} -DBUILD_EXAMPLES:BOOL=OFF -DITK_USE_SYSTEM_GDCM:BOOL=ON -DGDCM_DIR:PATH=${GDCM_DIR} DEPENDS ${proj_DEPENDENCIES} ) set(ITK_DIR ${ep_prefix}) mitkFunctionInstallExternalCMakeProject(${proj}) else() mitkMacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}") endif() diff --git a/CMakeExternals/OpenCV.cmake b/CMakeExternals/OpenCV.cmake index 0534497145..c9ac40ea79 100644 --- a/CMakeExternals/OpenCV.cmake +++ b/CMakeExternals/OpenCV.cmake @@ -1,93 +1,99 @@ #----------------------------------------------------------------------------- # OpenCV #----------------------------------------------------------------------------- if(MITK_USE_OpenCV) # Sanity checks if(DEFINED OpenCV_DIR AND NOT EXISTS ${OpenCV_DIR}) message(FATAL_ERROR "OpenCV_DIR variable is defined but corresponds to non-existing directory") endif() set(proj OpenCV) set(proj_DEPENDENCIES) set(OpenCV_DEPENDS ${proj}) if(NOT DEFINED OpenCV_DIR) set(additional_cmake_args -DBUILD_opencv_java:BOOL=OFF -DBUILD_opencv_ts:BOOL=OFF -DBUILD_PERF_TESTS:BOOL=OFF ) if(MITK_USE_Python) #message(STATUS "PYTHON_EXECUTABLE: ${PYTHON_EXECUTABLE}") #message(STATUS "PYTHON_DEBUG_LIBRARY: ${PYTHON_DEBUG_LIBRARY}") #message(STATUS "PYTHON_INCLUDE_DIR: ${PYTHON_INCLUDE_DIR}") #message(STATUS "PYTHON_LIBRARY: ${PYTHON_LIBRARY}") list(APPEND additional_cmake_args -DBUILD_opencv_python:BOOL=ON -DBUILD_NEW_PYTHON_SUPPORT:BOOL=ON -DPYTHON_DEBUG_LIBRARY:FILEPATH=${PYTHON_DEBUG_LIBRARY} -DPYTHON_EXECUTABLE:FILEPATH=${PYTHON_EXECUTABLE} -DPYTHON_INCLUDE_DIR:PATH=${PYTHON_INCLUDE_DIR} -DPYTHON_INCLUDE_DIR2:PATH=${PYTHON_INCLUDE_DIR2} -DPYTHON_LIBRARY:FILEPATH=${PYTHON_LIBRARY} #-DPYTHON_LIBRARIES=${PYTHON_LIBRARY} #-DPYTHON_DEBUG_LIBRARIES=${PYTHON_DEBUG_LIBRARIES} ) if(NOT MITK_USE_SYSTEM_PYTHON) list(APPEND proj_DEPENDENCIES Python Numpy) # export python home set(ENV{PYTHONHOME} "${Python_DIR}") endif() else() list(APPEND additional_cmake_args -DBUILD_opencv_python:BOOL=OFF -DBUILD_NEW_PYTHON_SUPPORT:BOOL=OFF ) endif() # 12-05-02, muellerm, added QT usage by OpenCV if QT is used in MITK # 12-09-11, muellerm, removed automatic usage again, since this will struggle with the MITK Qt application object if(MITK_USE_QT) list(APPEND additional_cmake_args -DWITH_QT:BOOL=OFF -DWITH_QT_OPENGL:BOOL=OFF -DQT_QMAKE_EXECUTABLE:FILEPATH=${QT_QMAKE_EXECUTABLE} ) endif() + if(CTEST_USE_LAUNCHERS) + list(APPEND additional_cmake_args + "-DCMAKE_PROJECT_${proj}_INCLUDE:FILEPATH=${CMAKE_ROOT}/Modules/CTestUseLaunchers.cmake" + ) + endif() + set(opencv_url ${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/OpenCV-2.4.11.tar.gz) set(opencv_url_md5 54fe3dba49ea276ec0228f8819e653bc) ExternalProject_Add(${proj} LIST_SEPARATOR ${sep} URL ${opencv_url} URL_MD5 ${opencv_url_md5} # Related bug: http://bugs.mitk.org/show_bug.cgi?id=5912 PATCH_COMMAND ${PATCH_COMMAND} -N -p1 -i ${CMAKE_CURRENT_LIST_DIR}/OpenCV-2.4.11.patch CMAKE_GENERATOR ${gen} CMAKE_ARGS ${ep_common_args} -DBUILD_TESTS:BOOL=OFF -DBUILD_DOCS:BOOL=OFF -DBUILD_EXAMPLES:BOOL=OFF -DBUILD_DOXYGEN_DOCS:BOOL=OFF -DWITH_CUDA:BOOL=OFF ${additional_cmake_args} DEPENDS ${proj_DEPENDENCIES} ) set(OpenCV_DIR ${ep_prefix}) mitkFunctionInstallExternalCMakeProject(${proj}) else() mitkMacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}") endif() endif() diff --git a/CMakeExternals/OpenIGTLink.cmake b/CMakeExternals/OpenIGTLink.cmake index 1f17caa6f9..824a48f77e 100644 --- a/CMakeExternals/OpenIGTLink.cmake +++ b/CMakeExternals/OpenIGTLink.cmake @@ -1,47 +1,53 @@ #----------------------------------------------------------------------------- # OpenIGTLink #----------------------------------------------------------------------------- if(MITK_USE_OpenIGTLink) # Sanity checks if(DEFINED OpenIGTLink_DIR AND NOT EXISTS ${OpenIGTLink_DIR}) message(FATAL_ERROR "OpenIGTLink_DIR variable is defined but corresponds to non-existing directory") endif() set(proj OpenIGTLink) set(proj_DEPENDENCIES ) set(${proj}_DEPENDS ${proj}) if(NOT DEFINED OpenIGTLink_DIR) set(additional_cmake_args ) if(MINGW) set(additional_cmake_args -DCMAKE_USE_WIN32_THREADS:BOOL=ON -DCMAKE_USE_PTHREADS:BOOL=OFF) endif() + if(CTEST_USE_LAUNCHERS) + list(APPEND additional_cmake_args + "-DCMAKE_PROJECT_${proj}_INCLUDE:FILEPATH=${CMAKE_ROOT}/Modules/CTestUseLaunchers.cmake" + ) + endif() + ExternalProject_Add(${proj} URL ${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/OpenIGTLink-54df50de.tar.gz URL_MD5 b9fd8351b059f4ec615f2dfd74ab2458 PATCH_COMMAND ${PATCH_COMMAND} -N -p1 -i ${CMAKE_CURRENT_LIST_DIR}/OpenIGTLink-54df50de.patch CMAKE_GENERATOR ${gen} CMAKE_ARGS ${ep_common_args} ${additional_cmake_args} -DBUILD_EXAMPLES:BOOL=OFF -DOpenIGTLink_PROTOCOL_VERSION_2:BOOL=ON -DOpenIGTLink_INSTALL_LIB_DIR:STRING=lib -DOpenIGTLink_INSTALL_PACKAGE_DIR:STRING=lib/cmake/OpenIGTLink -DOpenIGTLink_INSTALL_NO_DOCUMENTATION:BOOL=ON DEPENDS ${proj_DEPENDENCIES} ) set(OpenIGTLink_DIR "${ep_prefix}/lib/cmake/OpenIGTLink") else() mitkMacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}") endif() endif() diff --git a/CMakeExternals/PCRE.cmake b/CMakeExternals/PCRE.cmake index 4bf9fcda11..6c5858ff9d 100644 --- a/CMakeExternals/PCRE.cmake +++ b/CMakeExternals/PCRE.cmake @@ -1,53 +1,62 @@ #-------------------------------------------------------------------------- # PCRE (Perl Compatible Regular Expressions) #-------------------------------------------------------------------------- if(MITK_USE_PCRE) if(DEFINED PCRE_DIR AND NOT EXISTS ${PCRE_DIR}) message(FATAL_ERROR "PCRE_DIR variable is defined but corresponds to non-existing directory") endif() if(NOT PCRE_DIR) set(proj PCRE) set(${proj}_DEPENDENCIES "") set(${proj}_DEPENDS ${proj}) if(UNIX) # Some other projects (e.g. Swig) require a pcre-config script which is not # generated when using the CMake build system. set(configure_cmd CONFIGURE_COMMAND /./configure CC=${CMAKE_C_COMPILER}${CMAKE_C_COMPILER_ARG1} CFLAGS=-fPIC "CXXFLAGS=-fPIC ${MITK_CXX11_FLAG} ${CMAKE_CXX_FLAGS} ${CMAKE_CXX_FLAGS_RELEASE}" "LDFLAGS=${CMAKE_LINKER_FLAGS} ${CMAKE_LINKER_FLAGS_RELEASE} ${_install_rpath_linkflag}" CXX=${CMAKE_CXX_COMPILER}${CMAKE_CXX_COMPILER_ARG1} --prefix= --disable-shared --enable-jit ) else() + + set(additional_cmake_args ) + if(CTEST_USE_LAUNCHERS) + list(APPEND additional_cmake_args + "-DCMAKE_PROJECT_${proj}_INCLUDE:FILEPATH=${CMAKE_ROOT}/Modules/CTestUseLaunchers.cmake" + ) + endif() + set(configure_cmd CMAKE_ARGS ${ep_common_args} + ${additional_cmake_args} "-DCMAKE_C_FLAGS:STRING=${CMAKE_C_FLAGS} -fPIC" -DBUILD_SHARED_LIBS:BOOL=OFF -DPCRE_BUILD_PCREGREP:BOOL=OFF -DPCRE_BUILD_TESTS:BOOL=OFF -DPCRE_SUPPORT_JIT:BOOL=ON ) endif() ExternalProject_add(${proj} LIST_SEPARATOR ${sep} URL ${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/pcre-8.35.tar.gz URL_MD5 "ed58bcbe54d3b1d59e9f5415ef45ce1c" ${configure_cmd} DEPENDS "${${proj}_DEPENDENCIES}" ) set(PCRE_DIR ${ep_prefix}) else() mitkMacroEmptyExternalProject(${proj} "${${proj}_DEPENDENCIES}") endif() endif() diff --git a/CMakeExternals/Poco.cmake b/CMakeExternals/Poco.cmake index e3aee023fa..c32b276d82 100644 --- a/CMakeExternals/Poco.cmake +++ b/CMakeExternals/Poco.cmake @@ -1,58 +1,66 @@ #----------------------------------------------------------------------------- # Poco #----------------------------------------------------------------------------- if(MITK_USE_Poco) # Sanity checks if(DEFINED Poco_DIR AND NOT EXISTS ${Poco_DIR}) message(FATAL_ERROR "Poco_DIR variable is defined but corresponds to non-existing directory") endif() set(proj Poco) set(proj_DEPENDENCIES ) set(${proj}_DEPENDS ${proj}) if(NOT DEFINED ${proj}_DIR) + set(additional_cmake_args ) + if(CTEST_USE_LAUNCHERS) + list(APPEND additional_cmake_args + "-DCMAKE_PROJECT_${proj}_INCLUDE:FILEPATH=${CMAKE_ROOT}/Modules/CTestUseLaunchers.cmake" + ) + endif() + ExternalProject_Add(${proj} LIST_SEPARATOR ${sep} URL ${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/poco-1.6.0-all.tar.gz URL_MD5 4fed893d4ca57db98b0e10d82545232a PATCH_COMMAND ${PATCH_COMMAND} -N -p1 -i ${CMAKE_CURRENT_LIST_DIR}/Poco-1.6.0.patch CMAKE_GENERATOR ${gen} CMAKE_ARGS ${ep_common_args} + ${additional_cmake_args} -DENABLE_XML:BOOL=ON -DENABLE_JSON:BOOL=ON -DENABLE_MONGODB:BOOL=OFF -DENABLE_PDF:BOOL=OFF -DENABLE_UTIL:BOOL=ON -DENABLE_NET:BOOL=OFF -DENABLE_NETSSL:BOOL=OFF -DENABLE_NETSSL_WIN:BOOL=OFF -DENABLE_CRYPTO:BOOL=OFF -DENABLE_DATA:BOOL=OFF -DENABLE_DATA_SQLITE:BOOL=OFF -DENABLE_DATA_MYSQL:BOOL=OFF -DENABLE_DATA_ODBC:BOOL=OFF -DENABLE_SEVENZIP:BOOL=OFF -DENABLE_ZIP:BOOL=ON -DENABLE_APACHECONNECTOR:BOOL=OFF -DENABLE_CPPPARSER:BOOL=OFF -DENABLE_POCODOC:BOOL=OFF -DENABLE_PAGECOMPILER:BOOL=OFF -DENABLE_PAGECOMPILER_FILE2PAGE:BOOL=OFF DEPENDS ${proj_DEPENDENCIES} ) set(${proj}_DIR ${ep_prefix}) mitkFunctionInstallExternalCMakeProject(${proj}) else() mitkMacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}") endif() endif() diff --git a/CMakeExternals/Python.cmake b/CMakeExternals/Python.cmake index 54614d1e2b..96bf98b5fb 100644 --- a/CMakeExternals/Python.cmake +++ b/CMakeExternals/Python.cmake @@ -1,199 +1,205 @@ #---------------------------------------------------------------------- # Python #---------------------------------------------------------------------- if( MITK_USE_Python AND NOT MITK_USE_SYSTEM_PYTHON ) # Sanity checks if(DEFINED Python_DIR AND NOT EXISTS ${Python_DIR}) message(FATAL_ERROR "Python_DIR variable is defined but corresponds to non-existing directory") endif() if(NOT DEFINED Python_DIR) set(MITK_PYTHON_MAJOR_VERSION 2) set(MITK_PYTHON_MINOR_VERSION 7) set(MITK_PYTHON_PATCH_VERSION 3) set(PYTHON_SOURCE_PACKAGE Python-${MITK_PYTHON_MAJOR_VERSION}.${MITK_PYTHON_MINOR_VERSION}.${MITK_PYTHON_PATCH_VERSION}) set(proj ${PYTHON_SOURCE_PACKAGE}) # download the source code ExternalProject_Add(${proj} LIST_SEPARATOR ${sep} URL ${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/${PYTHON_SOURCE_PACKAGE}.tgz URL_MD5 "2cf641732ac23b18d139be077bd906cd" # patch the VS compiler config PATCH_COMMAND ${PATCH_COMMAND} -N -p1 -i ${CMAKE_CURRENT_LIST_DIR}/Python-2.7.3.patch CONFIGURE_COMMAND "" BUILD_COMMAND "" INSTALL_COMMAND "" ) set(proj Python) set(Python_DEPENDENCIES ZLIB ${PYTHON_SOURCE_PACKAGE}) set(Python_DEPENDS ${proj}) set(additional_cmake_cache_args ) list(APPEND additional_cmake_cache_args -DBUILTIN_ARRAY:BOOL=ON -DBUILTIN_AUDIOOP:BOOL=ON -DBUILTIN_BINASCII:BOOL=ON -DBUILTIN_BISECT:BOOL=ON -DBUILTIN_BSDB:BOOL=ON -DBUILTIN_BSSDB:BOOL=ON -DBUILTIN_BZ2:BOOL=ON -DBUILTIN_CMATH:BOOL=ON -DBUILTIN_COLLECTIONS:BOOL=ON -DBUILTIN_CODECS_CN:BOOL=ON -DBUILTIN_CODECS_HK:BOOL=ON -DBUILTIN_CODECS_ISO2022:BOOL=ON -DBUILTIN_CODECS_JP:BOOL=ON -DBUILTIN_CODECS_KR:BOOL=ON -DBUILTIN_CODECS_TW:BOOL=ON -DBUILTIN_CPICKLE:BOOL=ON -DBUILTIN_CRYPT:BOOL=ON -DBUILTIN_CSTRINGIO:BOOL=ON -DBUILTIN_CSV:BOOL=ON -DBUILTIN_CTYPES:BOOL=OFF #-DBUILTIN_CTYPES_TEST:BOOL=OFF #-DBUILTIN_CURSES:BOOL=ON -DBUILTIN_DATETIME:BOOL=ON -DBUILTIN_DBM:BOOL=ON -DBUILTIN_ELEMENTTREE:BOOL=ON -DBUILTIN_FCNTL:BOOL=ON -DBUILTIN_FUNCTOOLS:BOOL=ON -DBUILTIN_FUTURE_BUILTINS:BOOL=ON -DBULTIN_GDBM:BOOL=ON -DBUILTIN_GRP:BOOL=ON -DBUILTIN_HASHLIB:BOOL=ON -DBUILTIN_HEAPQ:BOOL=ON -DBUILTIN_HOTSHOT:BOOL=ON -DBUILTIN_IO:BOOL=ON -DBUILTIN_ITERTOOLS:BOOL=ON -DBUILTIN_JSON:BOOL=ON -DBUILTIN_LOCALE:BOOL=ON -DBUILTIN_LSPROF:BOOL=ON -DBUILTIN_MATH:BOOL=ON -DBUILTIN_MMAP:BOOL=ON -DBUILTIN_MULTIBYTECODEC:BOOL=ON -DBUILTIN_MD5:BOOL=ON -DBUILTIN_MULTIPROCESSING:BOOL=ON -DBUILTIN_NIS:BOOL=ON -DBUILTIN_NIT:BOOL=ON -DBUILTIN_OPERATOR:BOOL=ON -DBUILTIN_PARSER:BOOL=ON -DBUILTIN_POSIX:BOOL=ON -DBUILTIN_PWD:BOOL=ON -DBUILTIN_PYEXPAT:BOOL=ON -DBUILTIN_READLINE:BOOL=ON -DBUILTIN_RESOURCE:BOOL=ON -DBULTIN_RANDOM:BOOL=ON -DBUILTIN_SCPROXY:BOOL=OFF -DBUILTIN_SELECT:BOOL=ON -DBUILTIN_SHA:BOOL=ON -DBUILTIN_SHA256:BOOL=ON -DBUILTIN_SHA512:BOOL=ON -DBUILTIN_SOCKET:BOOL=ON -DBUILTIN_SPWD:BOOL=ON -DBUILTIN_SQLITE3:BOOL=OFF -DBUILTIN_SSL:BOOL=ON -DBUILTIN_STROP:BOOL=ON -DBUILTIN_STRUCT:BOOL=ON -DBUILTIN_SUBPROCESS:BOOL=ON -DBUILTIN_SYSLOG:BOOL=ON -DBUILTIN_TERMIOS:BOOL=ON #-DBUILTIN_TESTCAPI:BOOL=OFF -DBUILTIN_TIME:BOOL=ON -DBUILTIN_TKINTER:BOOL=ON -DBUILTIN_UNICODEDATA:BOOL=ON -DBUILTIN_WINREG:BOOL=ON -DBUILTIN_ZLIB:BOOL=OFF -DUSE_SYSTEM_ZLIB:BOOL=ON ) + if(CTEST_USE_LAUNCHERS) + list(APPEND additional_cmake_cache_args + "-DCMAKE_PROJECT_${proj}_INCLUDE:FILEPATH=${CMAKE_ROOT}/Modules/CTestUseLaunchers.cmake" + ) + endif() + # CMake build environment for python from: # https://github.com/davidsansome/python-cmake-buildsystem ExternalProject_Add(${proj} LIST_SEPARATOR ${sep} URL ${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/python-cmake-buildsystem-47845c55.tar.gz URL_MD5 "6e49d1ed93a5a0fff7621430c163d2d1" # fix to build python on i686 and i386 with the python cmake build system, # the x86 path must be set as default PATCH_COMMAND ${PATCH_COMMAND} -N -p1 -i ${CMAKE_CURRENT_LIST_DIR}/python-cmake-buildsystem-47845c55.patch CMAKE_ARGS ${ep_common_args} CMAKE_CACHE_ARGS -DCMAKE_CXX_COMPILER:FILEPATH=${CMAKE_CXX_COMPILER} -DCMAKE_C_COMPILER:FILEPATH=${CMAKE_C_COMPILER} #-DBUILD_TESTING:BOOL=OFF -DBUILD_SHARED:BOOL=ON -DBUILD_STATIC:BOOL=OFF -DUSE_SYSTEM_LIBRARIES:BOOL=OFF ${additional_cmake_cache_args} -DZLIB_INCLUDE_DIR:PATH=${ZLIB_INCLUDE_DIR} -DZLIB_LIBRARY:FILEPATH=${ZLIB_LIBRARY} # Python (and Numpy) do not like different shared library names -DCMAKE_DEBUG_POSTFIX:STRING= DEPENDS ${Python_DEPENDENCIES} ) set(Python_DIR "${ep_prefix}") if(UNIX) set(PYTHON_EXECUTABLE "${Python_DIR}/bin/python${CMAKE_EXECUTABLE_SUFFIX}") set(PYTHON_INCLUDE_DIR "${Python_DIR}/include/python${MITK_PYTHON_MAJOR_VERSION}.${MITK_PYTHON_MINOR_VERSION}") set(PYTHON_INCLUDE_DIR2 "${PYTHON_INCLUDE_DIR}") set(PYTHON_LIBRARY "${Python_DIR}/lib/${CMAKE_SHARED_LIBRARY_PREFIX}python${MITK_PYTHON_MAJOR_VERSION}.${MITK_PYTHON_MINOR_VERSION}${CMAKE_SHARED_LIBRARY_SUFFIX}") set(MITK_PYTHON_SITE_DIR "${Python_DIR}/lib/python${MITK_PYTHON_MAJOR_VERSION}.${MITK_PYTHON_MINOR_VERSION}/site-packages") # linux custom compile step, set the environment variables and python home to the right # path. Other runtimes can mess up the paths of the installation and the stripped executable # used to compile links to the wrong library in /usr/lib set(_python_compile_step ${ep_prefix}/tmp/python_compile_step.sh) file(WRITE ${_python_compile_step} "#!/bin/bash export PYTHONHOME=${Python_DIR} export LD_LIBRARY_PATH=${Python_DIR}/lib ${PYTHON_EXECUTABLE} -m compileall ") # pre compile all *.py files in the runtime after install step ExternalProject_Add_Step(${proj} compile_step COMMAND sh ${_python_compile_step} WORKING_DIRECTORY ${Python_DIR} DEPENDEES install ) # use the python executable in the build dir for unix systems. The stripped # ones will cause conflicts if system libraries are present during the build/configure process # of opencv, since they will try to lookup the sys path first if no lib is directly # linked with it s path into the executable #ExternalProject_Get_Property(${proj} binary_dir) #set(PYTHON_EXECUTABLE "${binary_dir}/bin/python${CMAKE_EXECUTABLE_SUFFIX}") else() set(PYTHON_EXECUTABLE "${Python_DIR}/bin/python${CMAKE_EXECUTABLE_SUFFIX}") set(PYTHON_INCLUDE_DIR "${Python_DIR}/include") set(PYTHON_INCLUDE_DIR2 "${PYTHON_INCLUDE_DIR}") set(PYTHON_LIBRARY "${Python_DIR}/libs/python${MITK_PYTHON_MAJOR_VERSION}${MITK_PYTHON_MINOR_VERSION}.lib") set(MITK_PYTHON_SITE_DIR "${Python_DIR}/Lib/site-packages") # pre compile all *.py files in the runtime after install step ExternalProject_Add_Step(${proj} compile_step COMMAND ${PYTHON_EXECUTABLE} -m compileall WORKING_DIRECTORY ${Python_DIR} DEPENDEES install ) endif() mitkFunctionInstallExternalCMakeProject(${proj}) install(DIRECTORY ${Python_DIR} DESTINATION . COMPONENT runtime FILES_MATCHING PATTERN "*.pyc" ) else() mitkMacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}") endif() endif() diff --git a/CMakeExternals/Qwt.cmake b/CMakeExternals/Qwt.cmake index 2c9ab3fb1e..5cd20b5a2f 100644 --- a/CMakeExternals/Qwt.cmake +++ b/CMakeExternals/Qwt.cmake @@ -1,43 +1,51 @@ #----------------------------------------------------------------------------- # Qwt #----------------------------------------------------------------------------- if(MITK_USE_Qwt) # Sanity checks if(DEFINED Qwt_DIR AND NOT EXISTS ${Qwt_DIR}) message(FATAL_ERROR "Qwt_DIR variable is defined but corresponds to non-existing directory") endif() set(proj Qwt) set(proj_DEPENDENCIES ) set(${proj}_DEPENDS ${proj}) if(NOT DEFINED ${proj}_DIR) set(patch_cmd ${CMAKE_COMMAND} -Dproj:STRING=${proj} -Dproj_target:STRING=qwt -P ${CMAKE_CURRENT_LIST_DIR}/GenerateDefaultCMakeBuildSystem.cmake) set(qt54patch_cmd ${CMAKE_COMMAND} -DTEMPLATE_FILE:FILEPATH=${MITK_SOURCE_DIR}/CMakeExternals/EmptyFileForPatching.dummy -P ${MITK_SOURCE_DIR}/CMakeExternals/PatchQwt-6.1.0.cmake) + set(additional_cmake_args ) + if(CTEST_USE_LAUNCHERS) + list(APPEND additional_cmake_args + "-DCMAKE_PROJECT_${proj}_INCLUDE:FILEPATH=${CMAKE_ROOT}/Modules/CTestUseLaunchers.cmake" + ) + endif() + ExternalProject_Add(${proj} LIST_SEPARATOR ${sep} URL ${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/qwt-6.1.0.tar.bz2 URL_MD5 aef0437b37f191067a6a9dc01c30ba64 PATCH_COMMAND ${PATCH_COMMAND} -N -p1 -i ${CMAKE_CURRENT_LIST_DIR}/Qwt-6.1.0.patch COMMAND ${CMAKE_COMMAND} -Dproj=${proj} -Dproj_target:STRING=qwt -P ${CMAKE_CURRENT_LIST_DIR}/GenerateDefaultCMakeBuildSystem.cmake CMAKE_GENERATOR ${gen} CMAKE_ARGS ${ep_common_args} + ${additional_cmake_args} ${qt_project_args} DEPENDS ${proj_DEPENDENCIES} ) set(${proj}_DIR ${ep_prefix}) mitkFunctionInstallExternalCMakeProject(${proj}) else() mitkMacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}") endif() endif() diff --git a/CMakeExternals/Raptor2.cmake b/CMakeExternals/Raptor2.cmake index fa361905bb..be8c450e8b 100644 --- a/CMakeExternals/Raptor2.cmake +++ b/CMakeExternals/Raptor2.cmake @@ -1,59 +1,67 @@ #----------------------------------------------------------------------------- # raptor2 #----------------------------------------------------------------------------- if(MITK_USE_Raptor2) # Sanity checks if(DEFINED Raptor2_DIR AND NOT EXISTS ${Raptor2_DIR}) message(FATAL_ERROR "Raptor2_DIR variable is defined but corresponds to non-existing directory") endif() set(proj Raptor2) set(proj_DEPENDENCIES ) set(${proj}_DEPENDS ${proj}) if(NOT DEFINED Raptor2_DIR) + set(additional_cmake_args ) + if(CTEST_USE_LAUNCHERS) + list(APPEND additional_cmake_args + "-DCMAKE_PROJECT_${proj}_INCLUDE:FILEPATH=${CMAKE_ROOT}/Modules/CTestUseLaunchers.cmake" + ) + endif() + ExternalProject_Add(${proj} LIST_SEPARATOR ${sep} URL ${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/raptor2-2.0.15.tar.gz URL_MD5 a39f6c07ddb20d7dd2ff1f95fa21e2cd PATCH_COMMAND ${PATCH_COMMAND} -N -p1 -i ${CMAKE_CURRENT_LIST_DIR}/Raptor2-2.0.15.patch CMAKE_GENERATOR ${gen} CMAKE_ARGS ${ep_common_args} + ${additional_cmake_args} -DRAPTOR_ENABLE_TESTING:BOOL=OFF -DRAPTOR_PARSER_GRDDL:BOOL=OFF -DRAPTOR_PARSER_GUESS:BOOL=OFF -DRAPTOR_PARSER_JSON:BOOL=OFF -DRAPTOR_PARSER_NQUADS:BOOL=ON -DRAPTOR_PARSER_NTRIPLES:BOOL=ON -DRAPTOR_PARSER_RDFA:BOOL=OFF -DRAPTOR_PARSER_RDFXML:BOOL=OFF -DRAPTOR_PARSER_RSS:BOOL=OFF -DRAPTOR_PARSER_TRIG:BOOL=OFF -DRAPTOR_PARSER_TURTLE:BOOL=ON -DRAPTOR_SERIALIZER_ATOM:BOOL=OFF -DRAPTOR_SERIALIZER_DOT:BOOL=OFF -DRAPTOR_SERIALIZER_HTML:BOOL=OFF -DRAPTOR_SERIALIZER_JSON:BOOL=OFF -DRAPTOR_SERIALIZER_NQUADS:BOOL=ON -DRAPTOR_SERIALIZER_NTRIPLES:BOOL=ON -DRAPTOR_SERIALIZER_RDFXML:BOOL=OFF -DRAPTOR_SERIALIZER_RDFXML_ABBREV:BOOL=OFF -DRAPTOR_SERIALIZER_RSS_1_0:BOOL=OFF -DRAPTOR_SERIALIZER_TURTLE:BOOL=ON DEPENDS ${proj_DEPENDENCIES} ) set(${proj}_DIR ${ep_prefix}/lib/raptor2/cmake) mitkFunctionInstallExternalCMakeProject(${proj}) else() mitkMacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}") endif() endif() diff --git a/CMakeExternals/Rasqal.cmake b/CMakeExternals/Rasqal.cmake index 427542b085..07c859ce4d 100644 --- a/CMakeExternals/Rasqal.cmake +++ b/CMakeExternals/Rasqal.cmake @@ -1,43 +1,51 @@ #----------------------------------------------------------------------------- # rasqal #----------------------------------------------------------------------------- if(MITK_USE_Rasqal) # Sanity checks if(DEFINED Rasqal_DIR AND NOT EXISTS ${Rasqal_DIR}) message(FATAL_ERROR "Rasqal_DIR variable is defined but corresponds to non-existing directory") endif() set(proj Rasqal) set(proj_DEPENDENCIES ${Raptor2_DEPENDS} ${PCRE_DEPENDS}) set(${proj}_DEPENDS ${proj}) if(NOT DEFINED Rasqal_DIR) + set(additional_cmake_args ) + if(CTEST_USE_LAUNCHERS) + list(APPEND additional_cmake_args + "-DCMAKE_PROJECT_${proj}_INCLUDE:FILEPATH=${CMAKE_ROOT}/Modules/CTestUseLaunchers.cmake" + ) + endif() + ExternalProject_Add(${proj} LIST_SEPARATOR ${sep} URL ${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/rasqal-0.9.32.tar.gz URL_MD5 dc7c6107de00c47f85f6ab7db164a136 PATCH_COMMAND ${PATCH_COMMAND} -N -p1 -i ${CMAKE_CURRENT_LIST_DIR}/Rasqal-0.9.32.patch LIST_SEPARATOR ^^ CMAKE_GENERATOR ${gen} CMAKE_ARGS ${ep_common_args} + ${additional_cmake_args} "-DCMAKE_C_FLAGS:STRING=-DPCRE_STATIC ${CMAKE_C_FLAGS}" -DRASQAL_REGEX:STRING=pcre -DCMAKE_PREFIX_PATH:STRING=${PCRE_DIR}^^${REDLAND_INSTALL_DIR} -DPCRE_INCLUDE_DIR:PATH=${PCRE_DIR}/include DEPENDS ${proj_DEPENDENCIES} ) set(${proj}_DIR ${ep_prefix}/lib/rasqal/cmake) mitkFunctionInstallExternalCMakeProject(${proj}) else() mitkMacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}") endif() endif() diff --git a/CMakeExternals/Redland.cmake b/CMakeExternals/Redland.cmake index b156f51fb6..ddf3a28cf8 100644 --- a/CMakeExternals/Redland.cmake +++ b/CMakeExternals/Redland.cmake @@ -1,39 +1,47 @@ #----------------------------------------------------------------------------- # redland #----------------------------------------------------------------------------- if(MITK_USE_Redland) # Sanity checks if(DEFINED Redland_DIR AND NOT EXISTS ${Redland_DIR}) message(FATAL_ERROR "Redland_DIR variable is defined but corresponds to non-existing directory") endif() set(proj Redland) set(proj_DEPENDENCIES ${Raptor2_DEPENDS} ${Rasqal_DEPENDS}) set(${proj}_DEPENDS ${proj}) if(NOT DEFINED Redland_DIR) + set(additional_cmake_args ) + if(CTEST_USE_LAUNCHERS) + list(APPEND additional_cmake_args + "-DCMAKE_PROJECT_${proj}_INCLUDE:FILEPATH=${CMAKE_ROOT}/Modules/CTestUseLaunchers.cmake" + ) + endif() + ExternalProject_Add(${proj} LIST_SEPARATOR ${sep} URL ${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/redland-1.0.17.tar.gz URL_MD5 e5be03eda13ef68aabab6e42aa67715e PATCH_COMMAND ${PATCH_COMMAND} -N -p1 -i ${CMAKE_CURRENT_LIST_DIR}/Redland-1.0.17.patch CMAKE_GENERATOR ${gen} CMAKE_ARGS ${ep_common_args} + ${additional_cmake_args} -DWITH_THREADS:BOOL=OFF DEPENDS ${proj_DEPENDENCIES} ) set(${proj}_DIR ${ep_prefix}/lib/redland/cmake) mitkFunctionInstallExternalCMakeProject(${proj}) else() mitkMacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}") endif() endif() diff --git a/CMakeExternals/SOFA.cmake b/CMakeExternals/SOFA.cmake index 12dba14e39..bff8bb20e3 100644 --- a/CMakeExternals/SOFA.cmake +++ b/CMakeExternals/SOFA.cmake @@ -1,100 +1,108 @@ #----------------------------------------------------------------------------- # SOFA #----------------------------------------------------------------------------- if(MITK_USE_SOFA) # Sanity checks if(DEFINED SOFA_DIR AND NOT EXISTS ${SOFA_DIR}) message(FATAL_ERROR "SOFA_DIR variable is defined but corresponds to non-existing directory") endif() set(proj SOFA) set(proj_DEPENDENCIES Boost GLEW) set(SOFA_DEPENDS ${proj}) set(preconfigure_cmake_args -DGLEW_DIR:PATH=${GLEW_DIR} -DSOFA-APPLICATION_GENERATERIGID:BOOL=OFF -DSOFA-APPLICATION_MODELER:BOOL=OFF -DSOFA-APPLICATION_RUNSOFA:BOOL=OFF -DSOFA-EXTERNAL_BOOST:BOOL=ON -DSOFA-EXTERNAL_BOOST_PATH:PATH=${BOOST_LIBRARYDIR} -DSOFA-EXTERNAL_CSPARSE:BOOL=ON -DSOFA-EXTERNAL_GLEW:BOOL=ON -DSOFA-EXTERNAL_PNG:BOOL=OFF -DSOFA-EXTERNAL_ZLIB:BOOL=OFF -DSOFA-LIB_COMPONENT_SPARSE_SOLVER:BOOL=ON -DSOFA-LIB_GUI_GLUT:BOOL=OFF -DSOFA-LIB_GUI_QT:BOOL=OFF -DSOFA-LIB_GUI_QTVIEWER:BOOL=OFF -DSOFA-TUTORIAL_COMPOSITE_OBJECT:BOOL=OFF -DSOFA-TUTORIAL_MIXED_PENDULUM:BOOL=OFF -DSOFA-TUTORIAL_ONE_PARTICLE:BOOL=OFF -DSOFA-TUTORIAL_ONE_TETRAHEDRON:BOOL=OFF ) if(NOT APPLE) list(APPEND proj_DEPENDENCIES GLUT) list(APPEND preconfigure_cmake_args -DSOFA-EXTERNAL_FREEGLUT:BOOL=ON -DGLUT_DIR:PATH=${GLUT_DIR} ) endif() if(NOT MITK_USE_SYSTEM_Boost) list(APPEND preconfigure_cmake_args -DBoost_NO_SYSTEM_PATHS:BOOL=ON -DBOOST_ROOT:PATH=${BOOST_ROOT} -DBOOST_LIBRARYDIR:PATH=${BOOST_LIBRARYDIR} ) endif() if(MITK_USE_SOFA_PLUGINS_DIR) list(APPEND preconfigure_cmake_args -DSOFA_APPLICATIONS_PLUGINS_DIR:PATH=${MITK_USE_SOFA_PLUGINS_DIR} ) foreach(plugin ${MITK_USE_SOFA_PLUGINS}) string(TOUPPER ${plugin} plugin) list(APPEND preconfigure_cmake_args -DSOFA-PLUGIN_${plugin}:BOOL=ON ) endforeach() endif() + set(additional_cmake_args ) + if(CTEST_USE_LAUNCHERS) + list(APPEND additional_cmake_args + "-DCMAKE_PROJECT_${proj}_INCLUDE:FILEPATH=${CMAKE_ROOT}/Modules/CTestUseLaunchers.cmake" + ) + endif() + set(rev "386a3a7") set(SOFA_PATCH_COMMAND ${CMAKE_COMMAND} -DTEMPLATE_FILE:FILEPATH=${MITK_SOURCE_DIR}/CMakeExternals/EmptyFileForPatching.dummy -P ${MITK_SOURCE_DIR}/CMakeExternals/PatchSOFA-${rev}.cmake) set(SOFA_PRECONFIGURE_COMMAND ${CMAKE_COMMAND} -G${gen} ${ep_common_args} ${preconfigure_cmake_args} ${boost_cmake_args} ) if(NOT DEFINED SOFA_DIR) ExternalProject_Add(${proj} LIST_SEPARATOR ${sep} URL ${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/SOFA-${rev}.tar.gz URL_MD5 31ca701e985331e96bd52d9e58842a86 PATCH_COMMAND ${SOFA_PATCH_COMMAND} INSTALL_COMMAND "" CMAKE_GENERATOR ${gen} CMAKE_ARGS ${ep_common_args} + ${additional_cmake_args} DEPENDS ${proj_DEPENDENCIES} ) ExternalProject_Add_Step(${proj} preconfigure COMMAND ${SOFA_PRECONFIGURE_COMMAND} WORKING_DIRECTORY DEPENDEES patch DEPENDERS configure LOG 1 ) # SOFA does not support "make install" yet # set(SOFA_DIR ${ep_prefix} ExternalProject_Get_Property(${proj} binary_dir) set(SOFA_DIR ${binary_dir}) else() mitkMacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}") endif() endif() diff --git a/CMakeExternals/SimpleITK.cmake b/CMakeExternals/SimpleITK.cmake index c04f0d876c..f6d8b0b11d 100644 --- a/CMakeExternals/SimpleITK.cmake +++ b/CMakeExternals/SimpleITK.cmake @@ -1,126 +1,132 @@ #----------------------------------------------------------------------------- # SimpleITK #----------------------------------------------------------------------------- if(MITK_USE_SimpleITK) # Sanity checks if(DEFINED SimpleITK_DIR AND NOT EXISTS ${SimpleITK_DIR}) message(FATAL_ERROR "SimpleITK_DIR variable is defined but corresponds to non-existing directory") endif() set(proj SimpleITK) set(proj_DEPENDENCIES ITK GDCM SWIG) if(MITK_USE_OpenCV) list(APPEND proj_DEPENDENCIES OpenCV) endif() set(SimpleITK_DEPENDS ${proj}) if(NOT DEFINED SimpleITK_DIR) set(additional_cmake_args ) list(APPEND additional_cmake_args -DWRAP_CSHARP:BOOL=OFF -DWRAP_TCL:BOOL=OFF -DWRAP_LUA:BOOL=OFF -DWRAP_PYTHON:BOOL=OFF -DWRAP_JAVA:BOOL=OFF -DWRAP_RUBY:BOOL=OFF -DWRAP_R:BOOL=OFF ) if(MITK_USE_Python) list(APPEND additional_cmake_args -DWRAP_PYTHON:BOOL=ON -DPYTHON_EXECUTABLE:FILEPATH=${PYTHON_EXECUTABLE} -DPYTHON_INCLUDE_DIR:PATH=${PYTHON_INCLUDE_DIR} -DPYTHON_INCLUDE_DIR2:PATH=${PYTHON_INCLUDE_DIR2} -DPYTHON_LIBRARY:FILEPATH=${PYTHON_LIBRARY} ) if(NOT MITK_USE_SYSTEM_PYTHON) list(APPEND proj_DEPENDENCIES Python) endif() endif() + if(CTEST_USE_LAUNCHERS) + list(APPEND additional_cmake_args + "-DCMAKE_PROJECT_${proj}_INCLUDE:FILEPATH=${CMAKE_ROOT}/Modules/CTestUseLaunchers.cmake" + ) + endif() + #TODO: Installer and testing works only with static libs on MAC set(_build_shared ON) if(APPLE) set(_build_shared OFF) endif() ExternalProject_Add(${proj} LIST_SEPARATOR ${sep} URL ${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/SimpleITK-0.8.1.tar.gz URL_MD5 9126ab2eda9e88f598a962c02a705c43 PATCH_COMMAND ${PATCH_COMMAND} -N -p1 -i ${CMAKE_CURRENT_LIST_DIR}/SimpleITK-0.8.1.patch CMAKE_ARGS ${ep_common_args} # -DCMAKE_BUILD_WITH_INSTALL_RPATH:BOOL=ON CMAKE_CACHE_ARGS ${additional_cmake_args} -DBUILD_SHARED_LIBS:BOOL=${_build_shared} -DSimpleITK_BUILD_DISTRIBUTE:BOOL=ON -DSimpleITK_PYTHON_THREADS:BOOL=ON -DUSE_SYSTEM_ITK:BOOL=ON -DBUILD_EXAMPLES:BOOL=OFF -DGDCM_DIR:PATH=${GDCM_DIR} -DITK_DIR:PATH=${ITK_DIR} -DSWIG_DIR:PATH=${SWIG_DIR} -DSWIG_EXECUTABLE:FILEPATH=${SWIG_EXECUTABLE} DEPENDS ${proj_DEPENDENCIES} ) set(SimpleITK_DIR ${ep_prefix}) if( MITK_USE_Python AND NOT MITK_USE_SYSTEM_PYTHON ) # PythonDir needs to be fixed for the python interpreter by # changing dir delimiter for Windows set(_install_dir ${Python_DIR}) if(WIN32) STRING(REPLACE "/" "\\\\" _install_dir ${Python_DIR}) else() # escape spaces in the install path for linux STRING(REPLACE " " "\ " _install_dir ${Python_DIR}) endif() # Build python distribution with easy install. If a own runtime is used # embedd the egg into the site-package folder of the runtime if(NOT MITK_USE_SYSTEM_PYTHON) ExternalProject_Add_Step(${proj} sitk_python_install_step COMMAND ${PYTHON_EXECUTABLE} setup.py install --prefix=${_install_dir} DEPENDEES build WORKING_DIRECTORY /Wrapping/PythonPackage ) # Build egg into custom user base folder and deploy it later into installer # https://pythonhosted.org/setuptools/easy_install.html#use-the-user-option-and-customize-pythonuserbase else() set(_userbase_install /Wrapping/PythonPackage/lib/python${PYTHON_VERSION_MAJOR}.${PYTHON_VERSION_MINOR}/site-packages) if(WIN32) set(_userbase_install /Wrapping/PythonPackage/Lib/site-packages) endif() ExternalProject_Add_Step(${proj} sitk_create_userbase_step COMMAND ${CMAKE_COMMAND} -E make_directory ${_userbase_install} DEPENDEES build WORKING_DIRECTORY ${SimpleITK_DIR}/Wrapping/PythonPackage ) ExternalProject_Add_Step(${proj} sitk_python_install_step COMMAND PYTHONUSERBASE=/Wrapping/PythonPackage ${PYTHON_EXECUTABLE} setup.py install --user DEPENDEES sitk_create_userbase_step WORKING_DIRECTORY /Wrapping/PythonPackage ) endif() endif() mitkFunctionInstallExternalCMakeProject(${proj}) # Still need to install the SimpleITK Python wrappings else() mitkMacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}") endif() endif() diff --git a/CMakeExternals/VTK.cmake b/CMakeExternals/VTK.cmake index 07f3cd1c29..12a6143d51 100644 --- a/CMakeExternals/VTK.cmake +++ b/CMakeExternals/VTK.cmake @@ -1,112 +1,118 @@ #----------------------------------------------------------------------------- # VTK #----------------------------------------------------------------------------- if(WIN32) option(VTK_USE_SYSTEM_FREETYPE OFF) else(WIN32) option(VTK_USE_SYSTEM_FREETYPE ON) endif(WIN32) # Sanity checks if(DEFINED VTK_DIR AND NOT EXISTS ${VTK_DIR}) message(FATAL_ERROR "VTK_DIR variable is defined but corresponds to non-existing directory") endif() set(proj VTK) set(proj_DEPENDENCIES ) set(VTK_DEPENDS ${proj}) if(MITK_USE_HDF5) list(APPEND proj_DEPENDENCIES HDF5) endif() if(NOT DEFINED VTK_DIR) set(additional_cmake_args ) if(MINGW) set(additional_cmake_args -DCMAKE_USE_WIN32_THREADS:BOOL=ON -DCMAKE_USE_PTHREADS:BOOL=OFF -DVTK_USE_VIDEO4WINDOWS:BOOL=OFF # no header files provided by MinGW ) endif() if(WIN32) # see http://bugs.mitk.org/show_bug.cgi?id=17858 list(APPEND additional_cmake_args -DVTK_DO_NOT_DEFINE_OSTREAM_SLL:BOOL=ON -DVTK_DO_NOT_DEFINE_OSTREAM_ULL:BOOL=ON ) endif() # Optionally enable memory leak checks for any objects derived from vtkObject. This # will force unit tests to fail if they have any of these memory leaks. option(MITK_VTK_DEBUG_LEAKS OFF) mark_as_advanced(MITK_VTK_DEBUG_LEAKS) list(APPEND additional_cmake_args -DVTK_DEBUG_LEAKS:BOOL=${MITK_VTK_DEBUG_LEAKS} ) if(MITK_USE_Python) if(NOT MITK_USE_SYSTEM_PYTHON) list(APPEND proj_DEPENDENCIES Python) endif() list(APPEND additional_cmake_args -DVTK_WRAP_PYTHON:BOOL=ON -DVTK_USE_TK:BOOL=OFF -DVTK_WINDOWS_PYTHON_DEBUGGABLE:BOOL=OFF -DPYTHON_EXECUTABLE:FILEPATH=${PYTHON_EXECUTABLE} -DPYTHON_INCLUDE_DIR:PATH=${PYTHON_INCLUDE_DIR} -DPYTHON_INCLUDE_DIR2:PATH=${PYTHON_INCLUDE_DIR2} -DPYTHON_LIBRARY:FILEPATH=${PYTHON_LIBRARY} ) else() list(APPEND additional_cmake_args -DVTK_WRAP_PYTHON:BOOL=OFF -DVTK_WINDOWS_PYTHON_DEBUGGABLE:BOOL=OFF ) endif() if(MITK_USE_QT) list(APPEND additional_cmake_args -DVTK_QT_VERSION:STRING=${DESIRED_QT_VERSION} -DQT_QMAKE_EXECUTABLE:FILEPATH=${QT_QMAKE_EXECUTABLE} -DModule_vtkGUISupportQt:BOOL=ON -DModule_vtkGUISupportQtWebkit:BOOL=ON -DModule_vtkGUISupportQtSQL:BOOL=ON -DModule_vtkRenderingQt:BOOL=ON -DVTK_Group_Qt:BOOL=ON ) endif() + if(CTEST_USE_LAUNCHERS) + list(APPEND additional_cmake_args + "-DCMAKE_PROJECT_${proj}_INCLUDE:FILEPATH=${CMAKE_ROOT}/Modules/CTestUseLaunchers.cmake" + ) + endif() + set(VTK_URL ${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/VTK-6.1.0+74f4888.tar.gz) set(VTK_URL_MD5 1f19dae22c42c032109bd3cf91c4e8c9) ExternalProject_Add(${proj} LIST_SEPARATOR ${sep} URL ${VTK_URL} URL_MD5 ${VTK_URL_MD5} PATCH_COMMAND ${PATCH_COMMAND} -N -p1 -i ${CMAKE_CURRENT_LIST_DIR}/VTK-6.1.0+74f4888.patch CMAKE_GENERATOR ${gen} CMAKE_ARGS ${ep_common_args} -DVTK_WRAP_TCL:BOOL=OFF -DVTK_WRAP_PYTHON:BOOL=OFF -DVTK_WRAP_JAVA:BOOL=OFF -DVTK_USE_SYSTEM_FREETYPE:BOOL=${VTK_USE_SYSTEM_FREETYPE} -DVTK_LEGACY_REMOVE:BOOL=ON -DModule_vtkTestingRendering:BOOL=ON -DVTK_MAKE_INSTANTIATORS:BOOL=ON ${additional_cmake_args} DEPENDS ${proj_DEPENDENCIES} ) set(VTK_DIR ${ep_prefix}) mitkFunctionInstallExternalCMakeProject(${proj}) else() mitkMacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}") endif() diff --git a/CMakeExternals/Vigra.cmake b/CMakeExternals/Vigra.cmake index c0f9517438..14b7ccffa3 100644 --- a/CMakeExternals/Vigra.cmake +++ b/CMakeExternals/Vigra.cmake @@ -1,43 +1,52 @@ #----------------------------------------------------------------------------- # VIGRA #----------------------------------------------------------------------------- if(MITK_USE_Vigra) # Sanity checks if(DEFINED Vigra_DIR AND NOT EXISTS ${Vigra_DIR}) message(FATAL_ERROR "Vigra_DIR variable is defined but corresponds to non-existing directory") endif() if(NOT ${MITK_USE_HDF5}) message(FATAL_ERROR "HDF5 is required for Vigra. Please enable it.") endif() set(proj Vigra) set(proj_DEPENDENCIES HDF5) set(Vigra_DEPENDS ${proj}) if(NOT DEFINED Vigra_DIR) + + set(additional_cmake_args ) + if(CTEST_USE_LAUNCHERS) + list(APPEND additional_cmake_args + "-DCMAKE_PROJECT_${proj}_INCLUDE:FILEPATH=${CMAKE_ROOT}/Modules/CTestUseLaunchers.cmake" + ) + endif() + ExternalProject_Add(${proj} URL ${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/vigra-1.10.0-src.tar.gz URL_MD5 4f963f0be4fcb8b06271c2aa40baa9be PATCH_COMMAND ${PATCH_COMMAND} -N -p1 -i ${CMAKE_CURRENT_LIST_DIR}/Vigra.patch CMAKE_GENERATOR ${gen} CMAKE_ARGS ${ep_common_args} + ${additional_cmake_args} -DAUTOEXEC_TESTS:BOOL=OFF -DWITH_VIGRANUMPY:BOOL=OFF -DHDF5_DIR:PATH=${HDF5_DIR} -DCMAKE_INSTALL_RPATH_USE_LINK_PATH:BOOL=TRUE -DCMAKE_INSTALL_PREFIX:PATH= DEPENDS ${proj_DEPENDENCIES} ) set(Vigra_DIR ${ep_prefix}) else() mitkMacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}") endif() endif(MITK_USE_Vigra) diff --git a/CMakeExternals/ZLIB.cmake b/CMakeExternals/ZLIB.cmake index 5d22ffbd97..7dca372581 100644 --- a/CMakeExternals/ZLIB.cmake +++ b/CMakeExternals/ZLIB.cmake @@ -1,60 +1,68 @@ #------------------------------------------------------------------ # ZLIB #------------------------------------------------------------------ if(MITK_USE_ZLIB) if(NOT DEFINED ZLIB_DIR) set(proj ZLIB) set(${proj}_DEPENDENCIES ) set(ZLIB_DEPENDS ${proj}) + set(additional_cmake_args ) + if(CTEST_USE_LAUNCHERS) + list(APPEND additional_cmake_args + "-DCMAKE_PROJECT_${proj}_INCLUDE:FILEPATH=${CMAKE_ROOT}/Modules/CTestUseLaunchers.cmake" + ) + endif() + # Using the ZLIB from CTK: # https://github.com/commontk/zlib ExternalProject_Add(${proj} LIST_SEPARATOR ${sep} URL ${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/zlib-66a75305.tar.gz URL_MD5 "4c3f572b487ae7947fd88ec363533bc5" CMAKE_ARGS ${ep_common_args} + ${additional_cmake_args} CMAKE_CACHE_ARGS -DBUILD_SHARED_LIBS:BOOL=OFF -DZLIB_MANGLE_PREFIX:STRING=mitk_zlib_ -DZLIB_INSTALL_INCLUDE_DIR:STRING=include/mitk_zlib DEPENDS ${ZLIB_DEPENDENCIES} ) set(ZLIB_DIR ${ep_prefix}) set(ZLIB_INCLUDE_DIR ${ZLIB_DIR}/include/mitk_zlib) install(DIRECTORY ${ZLIB_INCLUDE_DIR} DESTINATION include COMPONENT dev) find_library(ZLIB_LIBRARY_RELEASE NAMES zlib PATHS ${ZLIB_DIR} PATH_SUFFIXES lib lib/Release NO_DEFAULT_PATH) find_library(ZLIB_LIBRARY_DEBUG NAMES zlibd PATHS ${ZLIB_DIR} PATH_SUFFIXES lib lib/Debug NO_DEFAULT_PATH) set(ZLIB_LIBRARY ) if(ZLIB_LIBRARY_RELEASE) list(APPEND ZLIB_LIBRARY optimized ${ZLIB_LIBRARY_RELEASE}) install(FILES ${ZLIB_LIBRARY_RELEASE} DESTINATION lib CONFIGURATIONS Release COMPONENT dev) endif() if(ZLIB_LIBRARY_DEBUG) list(APPEND ZLIB_LIBRARY debug ${ZLIB_LIBRARY_DEBUG}) install(FILES ${ZLIB_LIBRARY_DEBUG} DESTINATION lib CONFIGURATIONS Debug COMPONENT dev) endif() else() mitkMacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}") endif() endif() diff --git a/CMakeExternals/tinyxml.cmake b/CMakeExternals/tinyxml.cmake index 0057df3443..93a16f22ef 100644 --- a/CMakeExternals/tinyxml.cmake +++ b/CMakeExternals/tinyxml.cmake @@ -1,41 +1,47 @@ #----------------------------------------------------------------------------- # tinyxml #----------------------------------------------------------------------------- # Sanity checks if(DEFINED tinyxml_DIR AND NOT EXISTS ${tinyxml_DIR}) message(FATAL_ERROR "tinyxml_DIR variable is defined but corresponds to non-existing directory") endif() set(proj tinyxml) set(proj_DEPENDENCIES ) set(${proj}_DEPENDS ${proj}) if(NOT DEFINED tinyxml_DIR) set(additional_cmake_args ) if(WIN32) set(additional_cmake_args -DBUILD_SHARED_LIBS:BOOL=OFF) endif() + if(CTEST_USE_LAUNCHERS) + list(APPEND additional_cmake_args + "-DCMAKE_PROJECT_${proj}_INCLUDE:FILEPATH=${CMAKE_ROOT}/Modules/CTestUseLaunchers.cmake" + ) + endif() + ExternalProject_Add(${proj} LIST_SEPARATOR ${sep} URL ${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/tinyxml_2_6_2.tar.gz URL_MD5 c1b864c96804a10526540c664ade67f0 PATCH_COMMAND ${PATCH_COMMAND} -N -p1 -i ${CMAKE_CURRENT_LIST_DIR}/tinyxml-2.6.2.patch COMMAND ${CMAKE_COMMAND} -Dproj=${proj} -Dproj_target:STRING=tinyxml -P ${CMAKE_CURRENT_LIST_DIR}/GenerateDefaultCMakeBuildSystem.cmake CMAKE_GENERATOR ${gen} CMAKE_ARGS ${ep_common_args} ${additional_cmake_args} DEPENDS ${proj_DEPENDENCIES} ) set(${proj}_DIR ${ep_prefix}) mitkFunctionInstallExternalCMakeProject(${proj}) else() mitkMacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}") endif() diff --git a/Modules/Core/include/mitkManufacturerLogo.h b/Modules/Core/include/mitkManufacturerLogo.h index a7a18837bc..90de1168ef 100644 --- a/Modules/Core/include/mitkManufacturerLogo.h +++ b/Modules/Core/include/mitkManufacturerLogo.h @@ -1,183 +1,183 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef _vtk_Logo_Rendering_h_ #define _vtk_Logo_Rendering_h_ #include class vtkRenderer; class vtkRenderWindow; class vtkMapper; class vtkCamera; class vtkImageActor; class vtkImageMapper; class vtkLookupTable; class vtkPolyData; class vtkPNGReader; class vtkImageImport; namespace mitk { class RenderWindow; /** * Renders a company logo in the foreground * of a vtkRenderWindow. - + * @deprecatedSince{next_release} Use mitk::LogoOverlay instead */ class MITKCORE_EXPORT ManufacturerLogo : public BaseData { public: mitkClassMacro( ManufacturerLogo, BaseData ); itkFactorylessNewMacro(Self) itkCloneMacro(Self) enum LogoPosition{ UpperLeft, UpperRight, LowerLeft, LowerRight, Middle }; /** * Sets the renderwindow, in which the logo * will be shown. Make sure, you have called this function * before calling Enable() */ virtual void SetRenderWindow( vtkRenderWindow* renderWindow ); /** * Sets the source file for the logo. */ virtual void SetLogoSource(const char* filename); /** * Sets the opacity level of the logo. */ virtual void SetOpacity(double opacity); /** * Specifies the logo size, values from 0...10, * where 1 is a nice little logo */ virtual void SetZoomFactor( double factor ); /** * Enables drawing of the logo. * If you want to disable it, call the Disable() function. */ virtual void Enable(); /** * Disables drawing of the logo. * If you want to enable it, call the Enable() function. */ virtual void Disable(); /** * Checks, if the logo is currently * enabled (visible) */ virtual bool IsEnabled(); /** * Empty implementation, since the ManufacturerLogo doesn't * support the requested region concept */ virtual void SetRequestedRegionToLargestPossibleRegion(); /** * Empty implementation, since the ManufacturerLogo doesn't * support the requested region concept */ virtual bool RequestedRegionIsOutsideOfTheBufferedRegion(); /** * Empty implementation, since the ManufacturerLogo doesn't * support the requested region concept */ virtual bool VerifyRequestedRegion(); /** * Empty implementation, since the ManufacturerLogo doesn't * support the requested region concept */ virtual void SetRequestedRegion( const itk::DataObject*); /** * Returns the vtkRenderWindow, which is used * for displaying the logo */ virtual vtkRenderWindow* GetRenderWindow(); /** * Returns the renderer responsible for * rendering the logo into the * vtkRenderWindow */ virtual vtkRenderer* GetVtkRenderer(); /** * Returns the actor associated with the logo */ virtual vtkImageActor* GetActor(); /** * Returns the mapper associated with the logo */ virtual vtkImageMapper* GetMapper(); /** * If set true, this method forces the logo rendering mechanism that it always * renders the MBI department logo, independent from mainapp option settings. */ virtual void ForceMBILogoVisible(bool visible); protected: void SetupCamera(); void SetupPosition(); /** * Constructor */ ManufacturerLogo(); /** * Destructor */ ~ManufacturerLogo(); vtkRenderWindow* m_RenderWindow; vtkRenderer* m_Renderer; vtkImageActor* m_Actor; vtkImageMapper* m_Mapper; vtkPNGReader* m_PngReader; vtkCamera* m_Camera; vtkImageImport* m_VtkImageImport; std::string m_FileName; bool m_IsEnabled; bool m_ForceShowMBIDepartmentLogo; LogoPosition m_LogoPosition; double m_ZoomFactor; double m_Opacity; char * m_ImageData; }; } //end of namespace mitk #endif diff --git a/Modules/Core/include/mitkPlaneGeometryDataMapper2D.h b/Modules/Core/include/mitkPlaneGeometryDataMapper2D.h index 583dd04db2..d2ae5d38d1 100644 --- a/Modules/Core/include/mitkPlaneGeometryDataMapper2D.h +++ b/Modules/Core/include/mitkPlaneGeometryDataMapper2D.h @@ -1,133 +1,137 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef mitkPlaneGeometryDataMapper2D_h #define mitkPlaneGeometryDataMapper2D_h #include "mitkVtkMapper.h" #include "mitkBaseRenderer.h" #include #include #include -class vtkActor; +class vtkActor2D; class vtkPropAssembly; class vtkFloatArray; class vtkCellArray; +class vtkPolyDataMapper2D; namespace mitk { /** * @brief Vtk-based 2D mapper for rendering a crosshair with the plane geometry. * * This mapper uses the mitkPlaneGeometryData from the three helper objects in * the StdMultiWidget to render a crosshair in all 2D render windows. The crosshair * is assembled as lines and rendered with a vtkPolyDataMapper. The mapper * requires multiple plane geometry to compute the correct crosshair position. * The mapper offers the following properties: * \b Crosshair.Line width: The thickness of the crosshair. * \b Crosshair.Gap Size: The gap between the lines in pixels. * \b Crosshair.Orientation Decoration: Adds a PlaneOrientationProperty, which * indicates the direction of the plane normal. See mitkPlaneOrientationProperty. * * @ingroup Mapper */ class MITKCORE_EXPORT PlaneGeometryDataMapper2D : public VtkMapper { public: mitkClassMacro(PlaneGeometryDataMapper2D, VtkMapper); itkFactorylessNewMacro(Self) itkCloneMacro(Self) virtual const mitk::PlaneGeometryData* GetInput() const; /** \brief returns the a prop assembly */ virtual vtkProp* GetVtkProp(mitk::BaseRenderer* renderer); /** Applies properties specific to this mapper */ virtual void ApplyAllProperties( BaseRenderer *renderer ); virtual void UpdateVtkTransform(mitk::BaseRenderer *renderer); /** \brief set the default properties for this mapper */ static void SetDefaultProperties(mitk::DataNode* node, mitk::BaseRenderer* renderer = NULL, bool overwrite = false); /** \brief Internal class holding the mapper, actor, etc. for each of the 3 2D render windows */ class LocalStorage : public mitk::Mapper::BaseLocalStorage { public: /* constructor */ LocalStorage(); /* destructor */ ~LocalStorage(); // actor - vtkSmartPointer m_CrosshairActor; - vtkSmartPointer m_CrosshairHelperLineActor; + vtkSmartPointer m_CrosshairActor; + vtkSmartPointer m_CrosshairHelperLineActor; vtkSmartPointer m_CrosshairAssembly; + vtkSmartPointer m_HelperLinesmapper; + vtkSmartPointer m_Mapper; }; /** \brief The LocalStorageHandler holds all (three) LocalStorages for the three 2D render windows. */ mitk::LocalStorageHandler m_LSH; protected: /* constructor */ PlaneGeometryDataMapper2D(); /* destructor */ virtual ~PlaneGeometryDataMapper2D(); /* \brief Applies the color and opacity properties and calls CreateVTKRenderObjects */ virtual void GenerateDataForRenderer(mitk::BaseRenderer* renderer); void CreateVtkCrosshair(BaseRenderer *renderer); /** * \brief Returns the thick slice mode for the given datanode. * * This method returns the value of the 'reslice.thickslices' property for * the given datanode. * '0': thick slice mode disabled * '1': thick slice mode enabled * * The variable 'thickSlicesNum' contains the value of the 'reslice.thickslices.num' * property that defines how many slices are shown at once. */ int DetermineThickSliceMode( DataNode * dn, int &thickSlicesNum ); void DrawLine(Point3D p0, Point3D p1, vtkCellArray *lines, vtkPoints *points); // member variables holding the current value of the properties used in this mapper typedef std::vector NodesVectorType; NodesVectorType m_OtherPlaneGeometries; typedef std::set AllInstancesContainer; static AllInstancesContainer s_AllInstances; bool m_RenderOrientationArrows; bool m_ArrowOrientationPositive; mitk::ScalarType m_DepthValue; + void ApplyColorAndOpacityProperties2D(BaseRenderer *renderer, vtkActor2D *actor); }; } // namespace mitk #endif /* mitkPlaneGeometryDataMapper2D_h */ diff --git a/Modules/Core/src/IO/mitkItkImageIO.cpp b/Modules/Core/src/IO/mitkItkImageIO.cpp index 5c08472171..90b4e85d5a 100644 --- a/Modules/Core/src/IO/mitkItkImageIO.cpp +++ b/Modules/Core/src/IO/mitkItkImageIO.cpp @@ -1,477 +1,481 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkItkImageIO.h" #include #include #include #include #include #include #include #include #include #include namespace mitk { ItkImageIO::ItkImageIO(const ItkImageIO& other) : AbstractFileIO(other) , m_ImageIO(dynamic_cast(other.m_ImageIO->Clone().GetPointer())) { } std::vector ItkImageIO::FixUpImageIOExtensions(const std::string& imageIOName) { std::vector extensions; // Try to fix-up some known ITK image IO classes if (imageIOName == "GiplImageIO") { extensions.push_back("gipl"); extensions.push_back("gipl.gz"); } else if (imageIOName == "GDCMImageIO") { extensions.push_back("gdcm"); extensions.push_back("dcm"); extensions.push_back("DCM"); extensions.push_back("dc3"); extensions.push_back("DC3"); extensions.push_back("ima"); extensions.push_back("img"); } else if (imageIOName == "PNGImageIO") { extensions.push_back("png"); extensions.push_back("PNG"); } else if (imageIOName == "StimulateImageIO") { extensions.push_back("spr"); } else if (imageIOName == "HDF5ImageIO") { extensions.push_back("hdf"); extensions.push_back("h4"); extensions.push_back("hdf4"); extensions.push_back("h5"); extensions.push_back("hdf5"); extensions.push_back("he4"); extensions.push_back("he5"); extensions.push_back("hd5"); } + else if (imageIOName == "GE4ImageIO" || imageIOName == "GE5ImageIO") + { + extensions.push_back(""); + } if (!extensions.empty()) { MITK_DEBUG << "Fixing up known extensions for " << imageIOName; } return extensions; } ItkImageIO::ItkImageIO(itk::ImageIOBase::Pointer imageIO) : AbstractFileIO(Image::GetStaticNameOfClass()) , m_ImageIO(imageIO) { if (m_ImageIO.IsNull() ) { mitkThrow() << "ITK ImageIOBase argument must not be NULL"; } this->AbstractFileReader::SetMimeTypePrefix(IOMimeTypes::DEFAULT_BASE_NAME() + ".image."); std::vector readExtensions = m_ImageIO->GetSupportedReadExtensions(); if (readExtensions.empty()) { std::string imageIOName = m_ImageIO->GetNameOfClass(); MITK_DEBUG << "ITK ImageIOBase " << imageIOName << " does not provide read extensions"; readExtensions = FixUpImageIOExtensions(imageIOName); } CustomMimeType customReaderMimeType; customReaderMimeType.SetCategory("Images"); for(std::vector::const_iterator iter = readExtensions.begin(), endIter = readExtensions.end(); iter != endIter; ++iter) { std::string extension = *iter; if (!extension.empty() && extension[0] == '.') { extension.assign(iter->begin()+1, iter->end()); } customReaderMimeType.AddExtension(extension); } this->AbstractFileReader::SetMimeType(customReaderMimeType); std::vector writeExtensions = imageIO->GetSupportedWriteExtensions(); if (writeExtensions.empty()) { std::string imageIOName = imageIO->GetNameOfClass(); MITK_DEBUG << "ITK ImageIOBase " << imageIOName << " does not provide write extensions"; writeExtensions = FixUpImageIOExtensions(imageIOName); } if (writeExtensions != readExtensions) { CustomMimeType customWriterMimeType; customWriterMimeType.SetCategory("Images"); for(std::vector::const_iterator iter = writeExtensions.begin(), endIter = writeExtensions.end(); iter != endIter; ++iter) { std::string extension = *iter; if (!extension.empty() && extension[0] == '.') { extension.assign(iter->begin()+1, iter->end()); } customWriterMimeType.AddExtension(extension); } this->AbstractFileWriter::SetMimeType(customWriterMimeType); } std::string description = std::string("ITK ") + imageIO->GetNameOfClass(); this->SetReaderDescription(description); this->SetWriterDescription(description); this->RegisterService(); } ItkImageIO::ItkImageIO(const CustomMimeType& mimeType, itk::ImageIOBase::Pointer imageIO, int rank) : AbstractFileIO(Image::GetStaticNameOfClass(), mimeType, std::string("ITK ") + imageIO->GetNameOfClass()) , m_ImageIO(imageIO) { if (m_ImageIO.IsNull() ) { mitkThrow() << "ITK ImageIOBase argument must not be NULL"; } this->AbstractFileReader::SetMimeTypePrefix(IOMimeTypes::DEFAULT_BASE_NAME() + ".image."); if (rank) { this->AbstractFileReader::SetRanking(rank); this->AbstractFileWriter::SetRanking(rank); } this->RegisterService(); } std::vector ItkImageIO::Read() { std::vector result; const std::string& locale = "C"; const std::string& currLocale = setlocale( LC_ALL, NULL ); if ( locale.compare(currLocale)!=0 ) { try { setlocale(LC_ALL, locale.c_str()); } catch(...) { MITK_INFO << "Could not set locale " << locale; } } Image::Pointer image = Image::New(); const unsigned int MINDIM = 2; const unsigned int MAXDIM = 4; const std::string path = this->GetLocalFileName(); MITK_INFO << "loading " << path << " via itk::ImageIOFactory... " << std::endl; // Check to see if we can read the file given the name or prefix if (path.empty()) { mitkThrow() << "Empty filename in mitk::ItkImageIO "; } // Got to allocate space for the image. Determine the characteristics of // the image. m_ImageIO->SetFileName( path ); m_ImageIO->ReadImageInformation(); unsigned int ndim = m_ImageIO->GetNumberOfDimensions(); if ( ndim < MINDIM || ndim > MAXDIM ) { MITK_WARN << "Sorry, only dimensions 2, 3 and 4 are supported. The given file has " << ndim << " dimensions! Reading as 4D."; ndim = MAXDIM; } itk::ImageIORegion ioRegion( ndim ); itk::ImageIORegion::SizeType ioSize = ioRegion.GetSize(); itk::ImageIORegion::IndexType ioStart = ioRegion.GetIndex(); unsigned int dimensions[ MAXDIM ]; dimensions[ 0 ] = 0; dimensions[ 1 ] = 0; dimensions[ 2 ] = 0; dimensions[ 3 ] = 0; ScalarType spacing[ MAXDIM ]; spacing[ 0 ] = 1.0f; spacing[ 1 ] = 1.0f; spacing[ 2 ] = 1.0f; spacing[ 3 ] = 1.0f; Point3D origin; origin.Fill(0); unsigned int i; for ( i = 0; i < ndim ; ++i ) { ioStart[ i ] = 0; ioSize[ i ] = m_ImageIO->GetDimensions( i ); if(iGetDimensions( i ); spacing[ i ] = m_ImageIO->GetSpacing( i ); if(spacing[ i ] <= 0) spacing[ i ] = 1.0f; } if(i<3) { origin[ i ] = m_ImageIO->GetOrigin( i ); } } ioRegion.SetSize( ioSize ); ioRegion.SetIndex( ioStart ); MITK_INFO << "ioRegion: " << ioRegion << std::endl; m_ImageIO->SetIORegion( ioRegion ); void* buffer = new unsigned char[m_ImageIO->GetImageSizeInBytes()]; m_ImageIO->Read( buffer ); image->Initialize( MakePixelType(m_ImageIO), ndim, dimensions ); image->SetImportChannel( buffer, 0, Image::ManageMemory ); // access direction of itk::Image and include spacing mitk::Matrix3D matrix; matrix.SetIdentity(); unsigned int j, itkDimMax3 = (ndim >= 3? 3 : ndim); for ( i=0; i < itkDimMax3; ++i) for( j=0; j < itkDimMax3; ++j ) matrix[i][j] = m_ImageIO->GetDirection(j)[i]; // re-initialize PlaneGeometry with origin and direction PlaneGeometry* planeGeometry = image->GetSlicedGeometry(0)->GetPlaneGeometry(0); planeGeometry->SetOrigin(origin); planeGeometry->GetIndexToWorldTransform()->SetMatrix(matrix); // re-initialize SlicedGeometry3D SlicedGeometry3D* slicedGeometry = image->GetSlicedGeometry(0); slicedGeometry->InitializeEvenlySpaced(planeGeometry, image->GetDimension(2)); slicedGeometry->SetSpacing(spacing); MITK_INFO << slicedGeometry->GetCornerPoint(false,false,false); MITK_INFO << slicedGeometry->GetCornerPoint(true,true,true); // re-initialize TimeGeometry ProportionalTimeGeometry::Pointer timeGeometry = ProportionalTimeGeometry::New(); timeGeometry->Initialize(slicedGeometry, image->GetDimension(3)); image->SetTimeGeometry(timeGeometry); buffer = NULL; MITK_INFO << "number of image components: "<< image->GetPixelType().GetNumberOfComponents() << std::endl; const itk::MetaDataDictionary& dictionary = m_ImageIO->GetMetaDataDictionary(); for (itk::MetaDataDictionary::ConstIterator iter = dictionary.Begin(), iterEnd = dictionary.End(); iter != iterEnd; ++iter) { std::string key = std::string("meta.") + iter->first; if (iter->second->GetMetaDataObjectTypeInfo() == typeid(std::string)) { std::string value = dynamic_cast*>(iter->second.GetPointer())->GetMetaDataObjectValue(); image->SetProperty(key.c_str(), mitk::StringProperty::New(value)); } } MITK_INFO << "...finished!" << std::endl; try { setlocale(LC_ALL, currLocale.c_str()); } catch(...) { MITK_INFO << "Could not reset locale " << currLocale; } result.push_back(image.GetPointer()); return result; } AbstractFileIO::ConfidenceLevel ItkImageIO::GetReaderConfidenceLevel() const { return m_ImageIO->CanReadFile(GetLocalFileName().c_str()) ? IFileReader::Supported : IFileReader::Unsupported; } void ItkImageIO::Write() { const mitk::Image* image = dynamic_cast(this->GetInput()); if (image == NULL) { mitkThrow() << "Cannot write non-image data"; } // Switch the current locale to "C" LocaleSwitch localeSwitch("C"); // Clone the image geometry, because we might have to change it // for writing purposes BaseGeometry::Pointer geometry = image->GetGeometry()->Clone(); // Check if geometry information will be lost if (image->GetDimension() == 2 && !geometry->Is2DConvertable()) { MITK_WARN << "Saving a 2D image with 3D geometry information. Geometry information will be lost! You might consider using Convert2Dto3DImageFilter before saving."; // set matrix to identity mitk::AffineTransform3D::Pointer affTrans = mitk::AffineTransform3D::New(); affTrans->SetIdentity(); mitk::Vector3D spacing = geometry->GetSpacing(); mitk::Point3D origin = geometry->GetOrigin(); geometry->SetIndexToWorldTransform(affTrans); geometry->SetSpacing(spacing); geometry->SetOrigin(origin); } LocalFile localFile(this); const std::string path = localFile.GetFileName(); MITK_INFO << "Writing image: " << path << std::endl; try { // Implementation of writer using itkImageIO directly. This skips the use // of templated itkImageFileWriter, which saves the multiplexing on MITK side. const unsigned int dimension = image->GetDimension(); const unsigned int* const dimensions = image->GetDimensions(); const mitk::PixelType pixelType = image->GetPixelType(); const mitk::Vector3D mitkSpacing = geometry->GetSpacing(); const mitk::Point3D mitkOrigin = geometry->GetOrigin(); // Due to templating in itk, we are forced to save a 4D spacing and 4D Origin, // though they are not supported in MITK itk::Vector spacing4D; spacing4D[0] = mitkSpacing[0]; spacing4D[1] = mitkSpacing[1]; spacing4D[2] = mitkSpacing[2]; spacing4D[3] = 1; // There is no support for a 4D spacing. However, we should have a valid value here itk::Vector origin4D; origin4D[0] = mitkOrigin[0]; origin4D[1] = mitkOrigin[1]; origin4D[2] = mitkOrigin[2]; origin4D[3] = 0; // There is no support for a 4D origin. However, we should have a valid value here // Set the necessary information for imageIO m_ImageIO->SetNumberOfDimensions(dimension); m_ImageIO->SetPixelType(pixelType.GetPixelType()); m_ImageIO->SetComponentType(pixelType.GetComponentType() < PixelComponentUserType ? static_cast(pixelType.GetComponentType()) : itk::ImageIOBase::UNKNOWNCOMPONENTTYPE); m_ImageIO->SetNumberOfComponents( pixelType.GetNumberOfComponents() ); itk::ImageIORegion ioRegion( dimension ); for(unsigned int i = 0; i < dimension; i++) { m_ImageIO->SetDimensions(i, dimensions[i]); m_ImageIO->SetSpacing(i, spacing4D[i]); m_ImageIO->SetOrigin(i, origin4D[i]); mitk::Vector3D mitkDirection; mitkDirection.SetVnlVector(geometry->GetIndexToWorldTransform()->GetMatrix().GetVnlMatrix().get_column(i)); itk::Vector direction4D; direction4D[0] = mitkDirection[0]; direction4D[1] = mitkDirection[1]; direction4D[2] = mitkDirection[2]; // MITK only supports a 3x3 direction matrix. Due to templating in itk, however, we must // save a 4x4 matrix for 4D images. in this case, add an homogneous component to the matrix. if (i == 3) { direction4D[3] = 1; // homogenous component } else { direction4D[3] = 0; } vnl_vector axisDirection(dimension); for(unsigned int j = 0; j < dimension; j++) { axisDirection[j] = direction4D[j] / spacing4D[i]; } m_ImageIO->SetDirection(i, axisDirection); ioRegion.SetSize(i, image->GetLargestPossibleRegion().GetSize(i)); ioRegion.SetIndex(i, image->GetLargestPossibleRegion().GetIndex(i)); } //use compression if available m_ImageIO->UseCompressionOn(); m_ImageIO->SetIORegion(ioRegion); m_ImageIO->SetFileName(path); // ***** Remove const_cast after bug 17952 is fixed **** ImageReadAccessor imageAccess(const_cast(image)); m_ImageIO->Write(imageAccess.GetData()); } catch (const std::exception& e) { mitkThrow() << e.what(); } } AbstractFileIO::ConfidenceLevel ItkImageIO::GetWriterConfidenceLevel() const { // Check if the image dimension is supported const Image* image = dynamic_cast(this->GetInput()); if (image == NULL || !m_ImageIO->SupportsDimension(image->GetDimension())) { return IFileWriter::Unsupported; } // Check if geometry information will be lost if (image->GetDimension() == 2 && !image->GetGeometry()->Is2DConvertable()) { return IFileWriter::PartiallySupported; } return IFileWriter::Supported; } ItkImageIO* ItkImageIO::IOClone() const { return new ItkImageIO(*this); } } diff --git a/Modules/Core/src/Rendering/mitkImageVtkMapper2D.cpp b/Modules/Core/src/Rendering/mitkImageVtkMapper2D.cpp index 96f122d406..8f9c1af106 100644 --- a/Modules/Core/src/Rendering/mitkImageVtkMapper2D.cpp +++ b/Modules/Core/src/Rendering/mitkImageVtkMapper2D.cpp @@ -1,1080 +1,1079 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ //MITK #include #include #include #include #include #include #include #include #include #include //#include #include #include "mitkImageStatisticsHolder.h" #include "mitkPlaneClipping.h" //MITK Rendering #include "mitkImageVtkMapper2D.h" #include "vtkMitkThickSlicesFilter.h" #include "vtkMitkLevelWindowFilter.h" #include "vtkNeverTranslucentTexture.h" //VTK #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include //ITK #include #include mitk::ImageVtkMapper2D::ImageVtkMapper2D() { } mitk::ImageVtkMapper2D::~ImageVtkMapper2D() { //The 3D RW Mapper (PlaneGeometryDataVtkMapper3D) is listening to this event, //in order to delete the images from the 3D RW. this->InvokeEvent( itk::DeleteEvent() ); } //set the two points defining the textured plane according to the dimension and spacing void mitk::ImageVtkMapper2D::GeneratePlane(mitk::BaseRenderer* renderer, double planeBounds[6]) { LocalStorage *localStorage = m_LSH.GetLocalStorage(renderer); float depth = this->CalculateLayerDepth(renderer); //Set the origin to (xMin; yMin; depth) of the plane. This is necessary for obtaining the correct //plane size in crosshair rotation and swivel mode. localStorage->m_Plane->SetOrigin(planeBounds[0], planeBounds[2], depth); //These two points define the axes of the plane in combination with the origin. //Point 1 is the x-axis and point 2 the y-axis. //Each plane is transformed according to the view (axial, coronal and saggital) afterwards. localStorage->m_Plane->SetPoint1(planeBounds[1] , planeBounds[2], depth); //P1: (xMax, yMin, depth) localStorage->m_Plane->SetPoint2(planeBounds[0], planeBounds[3], depth); //P2: (xMin, yMax, depth) } float mitk::ImageVtkMapper2D::CalculateLayerDepth(mitk::BaseRenderer* renderer) { //get the clipping range to check how deep into z direction we can render images double maxRange = renderer->GetVtkRenderer()->GetActiveCamera()->GetClippingRange()[1]; //Due to a VTK bug, we cannot use the whole clipping range. /100 is empirically determined float depth = -maxRange*0.01; // divide by 100 int layer = 0; GetDataNode()->GetIntProperty( "layer", layer, renderer); //add the layer property for each image to render images with a higher layer on top of the others depth += layer*10; //*10: keep some room for each image (e.g. for QBalls in between) if(depth > 0.0f) { depth = 0.0f; MITK_WARN << "Layer value exceeds clipping range. Set to minimum instead."; } return depth; } const mitk::Image* mitk::ImageVtkMapper2D::GetInput( void ) { return static_cast< const mitk::Image * >( GetDataNode()->GetData() ); } vtkProp* mitk::ImageVtkMapper2D::GetVtkProp(mitk::BaseRenderer* renderer) { //return the actor corresponding to the renderer return m_LSH.GetLocalStorage(renderer)->m_Actors; } void mitk::ImageVtkMapper2D::GenerateDataForRenderer( mitk::BaseRenderer *renderer ) { LocalStorage *localStorage = m_LSH.GetLocalStorage(renderer); mitk::Image *input = const_cast< mitk::Image * >( this->GetInput() ); mitk::DataNode* datanode = this->GetDataNode(); if ( input == NULL || input->IsInitialized() == false ) { return; } //check if there is a valid worldGeometry const PlaneGeometry *worldGeometry = renderer->GetCurrentWorldPlaneGeometry(); if( ( worldGeometry == NULL ) || ( !worldGeometry->IsValid() ) || ( !worldGeometry->HasReferenceGeometry() )) { return; } input->Update(); // early out if there is no intersection of the current rendering geometry // and the geometry of the image that is to be rendered. if ( !RenderingGeometryIntersectsImage( worldGeometry, input->GetSlicedGeometry() ) ) { // set image to NULL, to clear the texture in 3D, because // the latest image is used there if the plane is out of the geometry // see bug-13275 localStorage->m_ReslicedImage = NULL; localStorage->m_Mapper->SetInputData( localStorage->m_EmptyPolyData ); return; } //set main input for ExtractSliceFilter localStorage->m_Reslicer->SetInput(input); localStorage->m_Reslicer->SetWorldGeometry(worldGeometry); localStorage->m_Reslicer->SetTimeStep( this->GetTimestep() ); //set the transformation of the image to adapt reslice axis localStorage->m_Reslicer->SetResliceTransformByGeometry( input->GetTimeGeometry()->GetGeometryForTimeStep( this->GetTimestep() ) ); //is the geometry of the slice based on the input image or the worldgeometry? bool inPlaneResampleExtentByGeometry = false; datanode->GetBoolProperty("in plane resample extent by geometry", inPlaneResampleExtentByGeometry, renderer); localStorage->m_Reslicer->SetInPlaneResampleExtentByGeometry(inPlaneResampleExtentByGeometry); // Initialize the interpolation mode for resampling; switch to nearest // neighbor if the input image is too small. if ( (input->GetDimension() >= 3) && (input->GetDimension(2) > 1) ) { VtkResliceInterpolationProperty *resliceInterpolationProperty; datanode->GetProperty( resliceInterpolationProperty, "reslice interpolation", renderer ); int interpolationMode = VTK_RESLICE_NEAREST; if ( resliceInterpolationProperty != NULL ) { interpolationMode = resliceInterpolationProperty->GetInterpolation(); } switch ( interpolationMode ) { case VTK_RESLICE_NEAREST: localStorage->m_Reslicer->SetInterpolationMode(ExtractSliceFilter::RESLICE_NEAREST); break; case VTK_RESLICE_LINEAR: localStorage->m_Reslicer->SetInterpolationMode(ExtractSliceFilter::RESLICE_LINEAR); break; case VTK_RESLICE_CUBIC: localStorage->m_Reslicer->SetInterpolationMode(ExtractSliceFilter::RESLICE_CUBIC); break; } } else { localStorage->m_Reslicer->SetInterpolationMode(ExtractSliceFilter::RESLICE_NEAREST); } //set the vtk output property to true, makes sure that no unneeded mitk image convertion //is done. localStorage->m_Reslicer->SetVtkOutputRequest(true); //Thickslicing int thickSlicesMode = 0; int thickSlicesNum = 1; // Thick slices parameters if( input->GetPixelType().GetNumberOfComponents() == 1 ) // for now only single component are allowed { DataNode *dn=renderer->GetCurrentWorldPlaneGeometryNode(); if(dn) { ResliceMethodProperty *resliceMethodEnumProperty=0; if( dn->GetProperty( resliceMethodEnumProperty, "reslice.thickslices", renderer ) && resliceMethodEnumProperty ) thickSlicesMode = resliceMethodEnumProperty->GetValueAsId(); IntProperty *intProperty=0; if( dn->GetProperty( intProperty, "reslice.thickslices.num", renderer ) && intProperty ) { thickSlicesNum = intProperty->GetValue(); if(thickSlicesNum < 1) thickSlicesNum=1; } } else { MITK_WARN << "no associated widget plane data tree node found"; } } const PlaneGeometry *planeGeometry = dynamic_cast< const PlaneGeometry * >( worldGeometry ); if(thickSlicesMode > 0) { double dataZSpacing = 1.0; Vector3D normInIndex, normal; const mitk::AbstractTransformGeometry* abstractGeometry = dynamic_cast< const AbstractTransformGeometry * >(worldGeometry); if(abstractGeometry != NULL) normal = abstractGeometry->GetPlane()->GetNormal(); else{ if ( planeGeometry != NULL ){ normal = planeGeometry->GetNormal(); } else return; //no fitting geometry set } normal.Normalize(); input->GetTimeGeometry()->GetGeometryForTimeStep( this->GetTimestep() )->WorldToIndex( normal, normInIndex ); dataZSpacing = 1.0 / normInIndex.GetNorm(); localStorage->m_Reslicer->SetOutputDimensionality( 3 ); localStorage->m_Reslicer->SetOutputSpacingZDirection(dataZSpacing); localStorage->m_Reslicer->SetOutputExtentZDirection( -thickSlicesNum, 0+thickSlicesNum ); // Do the reslicing. Modified() is called to make sure that the reslicer is // executed even though the input geometry information did not change; this // is necessary when the input /em data, but not the /em geometry changes. localStorage->m_TSFilter->SetThickSliceMode( thickSlicesMode-1 ); localStorage->m_TSFilter->SetInputData( localStorage->m_Reslicer->GetVtkOutput() ); //vtkFilter=>mitkFilter=>vtkFilter update mechanism will fail without calling manually localStorage->m_Reslicer->Modified(); localStorage->m_Reslicer->Update(); localStorage->m_TSFilter->Modified(); localStorage->m_TSFilter->Update(); localStorage->m_ReslicedImage = localStorage->m_TSFilter->GetOutput(); } else { //this is needed when thick mode was enable bevore. These variable have to be reset to default values localStorage->m_Reslicer->SetOutputDimensionality( 2 ); localStorage->m_Reslicer->SetOutputSpacingZDirection(1.0); localStorage->m_Reslicer->SetOutputExtentZDirection( 0, 0 ); localStorage->m_Reslicer->Modified(); //start the pipeline with updating the largest possible, needed if the geometry of the input has changed localStorage->m_Reslicer->UpdateLargestPossibleRegion(); localStorage->m_ReslicedImage = localStorage->m_Reslicer->GetVtkOutput(); } // Bounds information for reslicing (only reuqired if reference geometry // is present) //this used for generating a vtkPLaneSource with the right size double sliceBounds[6]; for ( int i = 0; i < 6; ++i ) { sliceBounds[i] = 0.0; } localStorage->m_Reslicer->GetClippedPlaneBounds(sliceBounds); //get the spacing of the slice localStorage->m_mmPerPixel = localStorage->m_Reslicer->GetOutputSpacing(); // calculate minimum bounding rect of IMAGE in texture { double textureClippingBounds[6]; for ( int i = 0; i < 6; ++i ) { textureClippingBounds[i] = 0.0; } // Calculate the actual bounds of the transformed plane clipped by the // dataset bounding box; this is required for drawing the texture at the // correct position during 3D mapping. mitk::PlaneClipping::CalculateClippedPlaneBounds( input->GetGeometry(), planeGeometry, textureClippingBounds ); textureClippingBounds[0] = static_cast< int >( textureClippingBounds[0] / localStorage->m_mmPerPixel[0] + 0.5 ); textureClippingBounds[1] = static_cast< int >( textureClippingBounds[1] / localStorage->m_mmPerPixel[0] + 0.5 ); textureClippingBounds[2] = static_cast< int >( textureClippingBounds[2] / localStorage->m_mmPerPixel[1] + 0.5 ); textureClippingBounds[3] = static_cast< int >( textureClippingBounds[3] / localStorage->m_mmPerPixel[1] + 0.5 ); //clipping bounds for cutting the image localStorage->m_LevelWindowFilter->SetClippingBounds(textureClippingBounds); } //get the number of scalar components to distinguish between different image types int numberOfComponents = localStorage->m_ReslicedImage->GetNumberOfScalarComponents(); //get the binary property bool binary = false; bool binaryOutline = false; datanode->GetBoolProperty( "binary", binary, renderer ); if(binary) //binary image { datanode->GetBoolProperty( "outline binary", binaryOutline, renderer ); if(binaryOutline) //contour rendering { if ( input->GetPixelType().GetBpe() <= 8 ) { //generate contours/outlines localStorage->m_OutlinePolyData = CreateOutlinePolyData(renderer); float binaryOutlineWidth(1.0); if ( datanode->GetFloatProperty( "outline width", binaryOutlineWidth, renderer ) ) { if ( localStorage->m_Actors->GetNumberOfPaths() > 1 ) { float binaryOutlineShadowWidth(1.5); datanode->GetFloatProperty( "outline shadow width", binaryOutlineShadowWidth, renderer ); dynamic_cast(localStorage->m_Actors->GetParts()->GetItemAsObject(0)) ->GetProperty()->SetLineWidth( binaryOutlineWidth * binaryOutlineShadowWidth ); } localStorage->m_Actor->GetProperty()->SetLineWidth( binaryOutlineWidth ); } } else { binaryOutline = false; this->ApplyLookuptable(renderer); MITK_WARN << "Type of all binary images should be (un)signed char. Outline does not work on other pixel types!"; } } else //standard binary image { if(numberOfComponents != 1) { MITK_ERROR << "Rendering Error: Binary Images with more then 1 component are not supported!"; } } } this->ApplyOpacity( renderer ); this->ApplyRenderingMode(renderer); // do not use a VTK lookup table (we do that ourselves in m_LevelWindowFilter) localStorage->m_Texture->MapColorScalarsThroughLookupTableOff(); int displayedComponent = 0; if (datanode->GetIntProperty("Image.Displayed Component", displayedComponent, renderer) && numberOfComponents > 1) { localStorage->m_VectorComponentExtractor->SetComponents(displayedComponent); localStorage->m_VectorComponentExtractor->SetInputData(localStorage->m_ReslicedImage); localStorage->m_LevelWindowFilter->SetInputConnection(localStorage->m_VectorComponentExtractor->GetOutputPort(0)); } else { //connect the input with the levelwindow filter localStorage->m_LevelWindowFilter->SetInputData(localStorage->m_ReslicedImage); } // check for texture interpolation property bool textureInterpolation = false; GetDataNode()->GetBoolProperty( "texture interpolation", textureInterpolation, renderer ); //set the interpolation modus according to the property localStorage->m_Texture->SetInterpolate(textureInterpolation); // connect the texture with the output of the levelwindow filter localStorage->m_Texture->SetInputConnection(localStorage->m_LevelWindowFilter->GetOutputPort()); this->TransformActor( renderer ); vtkActor* contourShadowActor = dynamic_cast (localStorage->m_Actors->GetParts()->GetItemAsObject(0)); if(binary && binaryOutline) //connect the mapper with the polyData which contains the lines { //We need the contour for the binary outline property as actor localStorage->m_Mapper->SetInputData(localStorage->m_OutlinePolyData); localStorage->m_Actor->SetTexture(NULL); //no texture for contours bool binaryOutlineShadow( false ); datanode->GetBoolProperty( "outline binary shadow", binaryOutlineShadow, renderer ); if ( binaryOutlineShadow ) contourShadowActor->SetVisibility( true ); else contourShadowActor->SetVisibility( false ); } else { //Connect the mapper with the input texture. This is the standard case. //setup the textured plane this->GeneratePlane( renderer, sliceBounds ); //set the plane as input for the mapper localStorage->m_Mapper->SetInputConnection(localStorage->m_Plane->GetOutputPort()); //set the texture for the actor localStorage->m_Actor->SetTexture(localStorage->m_Texture); contourShadowActor->SetVisibility( false ); } // We have been modified => save this for next Update() localStorage->m_LastUpdateTime.Modified(); } void mitk::ImageVtkMapper2D::ApplyLevelWindow(mitk::BaseRenderer *renderer) { LocalStorage *localStorage = this->GetLocalStorage( renderer ); LevelWindow levelWindow; this->GetDataNode()->GetLevelWindow( levelWindow, renderer, "levelwindow" ); localStorage->m_LevelWindowFilter->GetLookupTable()->SetRange( levelWindow.GetLowerWindowBound(), levelWindow.GetUpperWindowBound() ); mitk::LevelWindow opacLevelWindow; if( this->GetDataNode()->GetLevelWindow( opacLevelWindow, renderer, "opaclevelwindow" ) ) { //pass the opaque level window to the filter localStorage->m_LevelWindowFilter->SetMinOpacity(opacLevelWindow.GetLowerWindowBound()); localStorage->m_LevelWindowFilter->SetMaxOpacity(opacLevelWindow.GetUpperWindowBound()); } else { //no opaque level window localStorage->m_LevelWindowFilter->SetMinOpacity(0.0); localStorage->m_LevelWindowFilter->SetMaxOpacity(255.0); } } void mitk::ImageVtkMapper2D::ApplyColor( mitk::BaseRenderer* renderer ) { LocalStorage *localStorage = this->GetLocalStorage( renderer ); float rgb[3]= { 1.0f, 1.0f, 1.0f }; // check for color prop and use it for rendering if it exists // binary image hovering & binary image selection bool hover = false; bool selected = false; bool binary = false; GetDataNode()->GetBoolProperty("binaryimage.ishovering", hover, renderer); GetDataNode()->GetBoolProperty("selected", selected, renderer); GetDataNode()->GetBoolProperty("binary", binary, renderer); if(binary && hover && !selected) { mitk::ColorProperty::Pointer colorprop = dynamic_cast(GetDataNode()->GetProperty ("binaryimage.hoveringcolor", renderer)); if(colorprop.IsNotNull()) { memcpy(rgb, colorprop->GetColor().GetDataPointer(), 3*sizeof(float)); } else { GetDataNode()->GetColor( rgb, renderer, "color" ); } } if(binary && selected) { mitk::ColorProperty::Pointer colorprop = dynamic_cast(GetDataNode()->GetProperty ("binaryimage.selectedcolor", renderer)); if(colorprop.IsNotNull()) { memcpy(rgb, colorprop->GetColor().GetDataPointer(), 3*sizeof(float)); } else { GetDataNode()->GetColor(rgb, renderer, "color"); } } if(!binary || (!hover && !selected)) { GetDataNode()->GetColor( rgb, renderer, "color" ); } double rgbConv[3] = {(double)rgb[0], (double)rgb[1], (double)rgb[2]}; //conversion to double for VTK dynamic_cast (localStorage->m_Actors->GetParts()->GetItemAsObject(0))->GetProperty()->SetColor(rgbConv); localStorage->m_Actor->GetProperty()->SetColor(rgbConv); if ( localStorage->m_Actors->GetParts()->GetNumberOfItems() > 1 ) { float rgb[3]= { 1.0f, 1.0f, 1.0f }; mitk::ColorProperty::Pointer colorprop = dynamic_cast(GetDataNode()->GetProperty ("outline binary shadow color", renderer)); if(colorprop.IsNotNull()) { memcpy(rgb, colorprop->GetColor().GetDataPointer(), 3*sizeof(float)); } double rgbConv[3] = {(double)rgb[0], (double)rgb[1], (double)rgb[2]}; //conversion to double for VTK dynamic_cast( localStorage->m_Actors->GetParts()->GetItemAsObject(0) )->GetProperty()->SetColor(rgbConv); } } void mitk::ImageVtkMapper2D::ApplyOpacity( mitk::BaseRenderer* renderer ) { LocalStorage* localStorage = this->GetLocalStorage( renderer ); float opacity = 1.0f; // check for opacity prop and use it for rendering if it exists GetDataNode()->GetOpacity( opacity, renderer, "opacity" ); //set the opacity according to the properties localStorage->m_Actor->GetProperty()->SetOpacity(opacity); if ( localStorage->m_Actors->GetParts()->GetNumberOfItems() > 1 ) { dynamic_cast( localStorage->m_Actors->GetParts()->GetItemAsObject(0) )->GetProperty()->SetOpacity(opacity); } } void mitk::ImageVtkMapper2D::ApplyRenderingMode( mitk::BaseRenderer* renderer ) { LocalStorage* localStorage = m_LSH.GetLocalStorage(renderer); bool binary = false; this->GetDataNode()->GetBoolProperty( "binary", binary, renderer ); if(binary) // is it a binary image? { //for binary images, we always use our default LuT and map every value to (0,1) //the opacity of 0 will always be 0.0. We never a apply a LuT/TfF nor a level window. localStorage->m_LevelWindowFilter->SetLookupTable(localStorage->m_BinaryLookupTable); } else { //all other image types can make use of the rendering mode int renderingMode = mitk::RenderingModeProperty::LOOKUPTABLE_LEVELWINDOW_COLOR; mitk::RenderingModeProperty::Pointer mode = dynamic_cast(this->GetDataNode()->GetProperty( "Image Rendering.Mode", renderer )); if(mode.IsNotNull()) { renderingMode = mode->GetRenderingMode(); } switch(renderingMode) { case mitk::RenderingModeProperty::LOOKUPTABLE_LEVELWINDOW_COLOR: MITK_DEBUG << "'Image Rendering.Mode' = LevelWindow_LookupTable_Color"; this->ApplyLookuptable( renderer ); this->ApplyLevelWindow( renderer ); break; case mitk::RenderingModeProperty::COLORTRANSFERFUNCTION_LEVELWINDOW_COLOR: MITK_DEBUG << "'Image Rendering.Mode' = LevelWindow_ColorTransferFunction_Color"; this->ApplyColorTransferFunction( renderer ); this->ApplyLevelWindow( renderer ); break; case mitk::RenderingModeProperty::LOOKUPTABLE_COLOR: MITK_DEBUG << "'Image Rendering.Mode' = LookupTable_Color"; this->ApplyLookuptable( renderer ); break; case mitk::RenderingModeProperty::COLORTRANSFERFUNCTION_COLOR: MITK_DEBUG << "'Image Rendering.Mode' = ColorTransferFunction_Color"; this->ApplyColorTransferFunction( renderer ); break; default: MITK_ERROR << "No valid 'Image Rendering.Mode' set. Using LOOKUPTABLE_LEVELWINDOW_COLOR instead."; this->ApplyLookuptable( renderer ); this->ApplyLevelWindow( renderer ); break; } } //we apply color for all images (including binaries). this->ApplyColor( renderer ); } void mitk::ImageVtkMapper2D::ApplyLookuptable( mitk::BaseRenderer* renderer ) { LocalStorage* localStorage = m_LSH.GetLocalStorage(renderer); vtkLookupTable* usedLookupTable = localStorage->m_ColorLookupTable; // If lookup table or transferfunction use is requested... mitk::LookupTableProperty::Pointer lookupTableProp = dynamic_cast(this->GetDataNode()->GetProperty("LookupTable")); if( lookupTableProp.IsNotNull() ) // is a lookuptable set? { usedLookupTable = lookupTableProp->GetLookupTable()->GetVtkLookupTable(); } else { //"Image Rendering.Mode was set to use a lookup table but there is no property 'LookupTable'. //A default (rainbow) lookup table will be used. //Here have to do nothing. Warning for the user has been removed, due to unwanted console output //in every interation of the rendering. } localStorage->m_LevelWindowFilter->SetLookupTable(usedLookupTable); } void mitk::ImageVtkMapper2D::ApplyColorTransferFunction(mitk::BaseRenderer *renderer) { mitk::TransferFunctionProperty::Pointer transferFunctionProp = dynamic_cast(this->GetDataNode()->GetProperty("Image Rendering.Transfer Function",renderer )); if( transferFunctionProp.IsNull() ) { MITK_ERROR << "'Image Rendering.Mode'' was set to use a color transfer function but there is no property 'Image Rendering.Transfer Function'. Nothing will be done."; return; } LocalStorage* localStorage = m_LSH.GetLocalStorage(renderer); //pass the transfer function to our level window filter localStorage->m_LevelWindowFilter->SetLookupTable(transferFunctionProp->GetValue()->GetColorTransferFunction()); localStorage->m_LevelWindowFilter->SetOpacityPiecewiseFunction(transferFunctionProp->GetValue()->GetScalarOpacityFunction()); } void mitk::ImageVtkMapper2D::Update(mitk::BaseRenderer* renderer) { bool visible = true; GetDataNode()->GetVisibility(visible, renderer, "visible"); if ( !visible ) { return; } mitk::Image* data = const_cast( this->GetInput() ); if ( data == NULL ) { return; } // Calculate time step of the input data for the specified renderer (integer value) this->CalculateTimeStep( renderer ); // Check if time step is valid const TimeGeometry *dataTimeGeometry = data->GetTimeGeometry(); if ( ( dataTimeGeometry == NULL ) || ( dataTimeGeometry->CountTimeSteps() == 0 ) || ( !dataTimeGeometry->IsValidTimeStep( this->GetTimestep() ) ) ) { return; } const DataNode *node = this->GetDataNode(); data->UpdateOutputInformation(); LocalStorage *localStorage = m_LSH.GetLocalStorage(renderer); //check if something important has changed and we need to rerender if ( (localStorage->m_LastUpdateTime < node->GetMTime()) //was the node modified? || (localStorage->m_LastUpdateTime < data->GetPipelineMTime()) //Was the data modified? || (localStorage->m_LastUpdateTime < renderer->GetCurrentWorldPlaneGeometryUpdateTime()) //was the geometry modified? || (localStorage->m_LastUpdateTime < renderer->GetCurrentWorldPlaneGeometry()->GetMTime()) || (localStorage->m_LastUpdateTime < node->GetPropertyList()->GetMTime()) //was a property modified? || (localStorage->m_LastUpdateTime < node->GetPropertyList(renderer)->GetMTime()) ) { this->GenerateDataForRenderer( renderer ); } // since we have checked that nothing important has changed, we can set // m_LastUpdateTime to the current time localStorage->m_LastUpdateTime.Modified(); } void mitk::ImageVtkMapper2D::SetDefaultProperties(mitk::DataNode* node, mitk::BaseRenderer* renderer, bool overwrite) { mitk::Image::Pointer image = dynamic_cast(node->GetData()); // Properties common for both images and segmentations node->AddProperty( "depthOffset", mitk::FloatProperty::New( 0.0 ), renderer, overwrite ); node->AddProperty( "outline binary", mitk::BoolProperty::New( false ), renderer, overwrite ); node->AddProperty( "outline width", mitk::FloatProperty::New( 1.0 ), renderer, overwrite ); node->AddProperty( "outline binary shadow", mitk::BoolProperty::New( false ), renderer, overwrite ); node->AddProperty( "outline binary shadow color", ColorProperty::New(0.0,0.0,0.0), renderer, overwrite ); node->AddProperty( "outline shadow width", mitk::FloatProperty::New( 1.5 ), renderer, overwrite ); if(image->IsRotated()) node->AddProperty( "reslice interpolation", mitk::VtkResliceInterpolationProperty::New(VTK_RESLICE_CUBIC) ); else node->AddProperty( "reslice interpolation", mitk::VtkResliceInterpolationProperty::New() ); node->AddProperty( "texture interpolation", mitk::BoolProperty::New( false ) ); node->AddProperty( "in plane resample extent by geometry", mitk::BoolProperty::New( false ) ); node->AddProperty( "bounding box", mitk::BoolProperty::New( false ) ); mitk::RenderingModeProperty::Pointer renderingModeProperty = mitk::RenderingModeProperty::New(); node->AddProperty( "Image Rendering.Mode", renderingModeProperty); // Set default grayscale look-up table mitk::LookupTable::Pointer mitkLut = mitk::LookupTable::New(); mitkLut->SetType(mitk::LookupTable::GRAYSCALE); mitk::LookupTableProperty::Pointer mitkLutProp = mitk::LookupTableProperty::New(); mitkLutProp->SetLookupTable(mitkLut); node->SetProperty("LookupTable", mitkLutProp); std::string photometricInterpretation; // DICOM tag telling us how pixel values should be displayed if ( node->GetStringProperty( "dicom.pixel.PhotometricInterpretation", photometricInterpretation ) ) { // modality provided by DICOM or other reader if ( photometricInterpretation.find("MONOCHROME1") != std::string::npos ) // meaning: display MINIMUM pixels as WHITE { // Set inverse grayscale look-up table mitkLut->SetType(mitk::LookupTable::INVERSE_GRAYSCALE); mitkLutProp->SetLookupTable(mitkLut); node->SetProperty( "LookupTable", mitkLutProp ); renderingModeProperty->SetValue( mitk::RenderingModeProperty::LOOKUPTABLE_LEVELWINDOW_COLOR ); // USE lookuptable } // Otherwise do nothing - the default grayscale look-up table has already been set } bool isBinaryImage(false); - if ( ! node->GetBoolProperty("binary", isBinaryImage) ) + if ( ! node->GetBoolProperty("binary", isBinaryImage) && image->GetPixelType().GetNumberOfComponents()==1 ) { // ok, property is not set, use heuristic to determine if this // is a binary image mitk::Image::Pointer centralSliceImage; ScalarType minValue = 0.0; ScalarType maxValue = 0.0; ScalarType min2ndValue = 0.0; ScalarType max2ndValue = 0.0; mitk::ImageSliceSelector::Pointer sliceSelector = mitk::ImageSliceSelector::New(); sliceSelector->SetInput(image); sliceSelector->SetSliceNr(image->GetDimension(2)/2); sliceSelector->SetTimeNr(image->GetDimension(3)/2); sliceSelector->SetChannelNr(image->GetDimension(4)/2); sliceSelector->Update(); centralSliceImage = sliceSelector->GetOutput(); if ( centralSliceImage.IsNotNull() && centralSliceImage->IsInitialized() ) { minValue = centralSliceImage->GetStatistics()->GetScalarValueMin(); maxValue = centralSliceImage->GetStatistics()->GetScalarValueMax(); min2ndValue = centralSliceImage->GetStatistics()->GetScalarValue2ndMin(); max2ndValue = centralSliceImage->GetStatistics()->GetScalarValue2ndMax(); } if ((maxValue == min2ndValue && minValue == max2ndValue) || minValue == maxValue) { // centralSlice is strange, lets look at all data minValue = image->GetStatistics()->GetScalarValueMin(); maxValue = image->GetStatistics()->GetScalarValueMaxNoRecompute(); min2ndValue = image->GetStatistics()->GetScalarValue2ndMinNoRecompute(); max2ndValue = image->GetStatistics()->GetScalarValue2ndMaxNoRecompute(); } isBinaryImage = ( maxValue == min2ndValue && minValue == max2ndValue ); } + std::string className = image->GetNameOfClass(); + if (className != "TensorImage" && className != "QBallImage") + { + PixelType pixelType = image->GetPixelType(); + size_t numComponents = pixelType.GetNumberOfComponents(); + + if ((pixelType.GetPixelType() == itk::ImageIOBase::VECTOR && numComponents > 1) || + numComponents == 2 || numComponents > 4) + { + node->AddProperty("Image.Displayed Component", mitk::IntProperty::New(0), renderer, overwrite); + } + } + // some more properties specific for a binary... if (isBinaryImage) { node->AddProperty( "opacity", mitk::FloatProperty::New(0.3f), renderer, overwrite ); node->AddProperty( "color", ColorProperty::New(1.0,0.0,0.0), renderer, overwrite ); node->AddProperty( "binaryimage.selectedcolor", ColorProperty::New(1.0,0.0,0.0), renderer, overwrite ); node->AddProperty( "binaryimage.selectedannotationcolor", ColorProperty::New(1.0,0.0,0.0), renderer, overwrite ); node->AddProperty( "binaryimage.hoveringcolor", ColorProperty::New(1.0,0.0,0.0), renderer, overwrite ); node->AddProperty( "binaryimage.hoveringannotationcolor", ColorProperty::New(1.0,0.0,0.0), renderer, overwrite ); node->AddProperty( "binary", mitk::BoolProperty::New( true ), renderer, overwrite ); node->AddProperty("layer", mitk::IntProperty::New(10), renderer, overwrite); } else //...or image type object { node->AddProperty( "opacity", mitk::FloatProperty::New(1.0f), renderer, overwrite ); node->AddProperty( "color", ColorProperty::New(1.0,1.0,1.0), renderer, overwrite ); node->AddProperty( "binary", mitk::BoolProperty::New( false ), renderer, overwrite ); node->AddProperty("layer", mitk::IntProperty::New(0), renderer, overwrite); - - std::string className = image->GetNameOfClass(); - - if (className != "TensorImage" && className != "QBallImage") - { - PixelType pixelType = image->GetPixelType(); - size_t numComponents = pixelType.GetNumberOfComponents(); - - if ((pixelType.GetPixelType() == itk::ImageIOBase::VECTOR && numComponents > 1) || - numComponents == 2 || numComponents > 4) - { - node->AddProperty("Image.Displayed Component", mitk::IntProperty::New(0), renderer, overwrite); - } - } } if(image.IsNotNull() && image->IsInitialized()) { if((overwrite) || (node->GetProperty("levelwindow", renderer)==NULL)) { /* initialize level/window from DICOM tags */ std::string sLevel; std::string sWindow; if ( image->GetPropertyList()->GetStringProperty( "dicom.voilut.WindowCenter", sLevel ) && image->GetPropertyList()->GetStringProperty( "dicom.voilut.WindowWidth", sWindow ) ) { float level = atof( sLevel.c_str() ); float window = atof( sWindow.c_str() ); mitk::LevelWindow contrast; std::string sSmallestPixelValueInSeries; std::string sLargestPixelValueInSeries; if ( image->GetPropertyList()->GetStringProperty( "dicom.series.SmallestPixelValueInSeries", sSmallestPixelValueInSeries ) && image->GetPropertyList()->GetStringProperty( "dicom.series.LargestPixelValueInSeries", sLargestPixelValueInSeries ) ) { float smallestPixelValueInSeries = atof( sSmallestPixelValueInSeries.c_str() ); float largestPixelValueInSeries = atof( sLargestPixelValueInSeries.c_str() ); contrast.SetRangeMinMax( smallestPixelValueInSeries-1, largestPixelValueInSeries+1 ); // why not a little buffer? // might remedy some l/w widget challenges } else { contrast.SetAuto( static_cast(node->GetData()), false, true ); // we need this as a fallback } contrast.SetLevelWindow( level, window, true ); node->SetProperty( "levelwindow", LevelWindowProperty::New( contrast ), renderer ); } } if(((overwrite) || (node->GetProperty("opaclevelwindow", renderer)==NULL)) && (image->GetPixelType().GetPixelType() == itk::ImageIOBase::RGBA) && (image->GetPixelType().GetComponentType() == itk::ImageIOBase::UCHAR) ) { mitk::LevelWindow opaclevwin; opaclevwin.SetRangeMinMax(0,255); opaclevwin.SetWindowBounds(0,255); mitk::LevelWindowProperty::Pointer prop = mitk::LevelWindowProperty::New(opaclevwin); node->SetProperty( "opaclevelwindow", prop, renderer ); } } Superclass::SetDefaultProperties(node, renderer, overwrite); } mitk::ImageVtkMapper2D::LocalStorage* mitk::ImageVtkMapper2D::GetLocalStorage(mitk::BaseRenderer* renderer) { return m_LSH.GetLocalStorage(renderer); } vtkSmartPointer mitk::ImageVtkMapper2D::CreateOutlinePolyData(mitk::BaseRenderer* renderer ){ LocalStorage* localStorage = this->GetLocalStorage(renderer); //get the min and max index values of each direction int* extent = localStorage->m_ReslicedImage->GetExtent(); int xMin = extent[0]; int xMax = extent[1]; int yMin = extent[2]; int yMax = extent[3]; int* dims = localStorage->m_ReslicedImage->GetDimensions(); //dimensions of the image int line = dims[0]; //how many pixels per line? int x = xMin; //pixel index x int y = yMin; //pixel index y char* currentPixel; //get the depth for each contour float depth = CalculateLayerDepth(renderer); vtkSmartPointer points = vtkSmartPointer::New(); //the points to draw vtkSmartPointer lines = vtkSmartPointer::New(); //the lines to connect the points // We take the pointer to the first pixel of the image currentPixel = static_cast(localStorage->m_ReslicedImage->GetScalarPointer() ); while (y <= yMax) { //if the current pixel value is set to something if ((currentPixel) && (*currentPixel != 0)) { //check in which direction a line is necessary //a line is added if the neighbor of the current pixel has the value 0 //and if the pixel is located at the edge of the image //if vvvvv not the first line vvvvv if (y > yMin && *(currentPixel-line) == 0) { //x direction - bottom edge of the pixel //add the 2 points vtkIdType p1 = points->InsertNextPoint(x*localStorage->m_mmPerPixel[0], y*localStorage->m_mmPerPixel[1], depth); vtkIdType p2 = points->InsertNextPoint((x+1)*localStorage->m_mmPerPixel[0], y*localStorage->m_mmPerPixel[1], depth); //add the line between both points lines->InsertNextCell(2); lines->InsertCellPoint(p1); lines->InsertCellPoint(p2); } //if vvvvv not the last line vvvvv if (y < yMax && *(currentPixel+line) == 0) { //x direction - top edge of the pixel vtkIdType p1 = points->InsertNextPoint(x*localStorage->m_mmPerPixel[0], (y+1)*localStorage->m_mmPerPixel[1], depth); vtkIdType p2 = points->InsertNextPoint((x+1)*localStorage->m_mmPerPixel[0], (y+1)*localStorage->m_mmPerPixel[1], depth); lines->InsertNextCell(2); lines->InsertCellPoint(p1); lines->InsertCellPoint(p2); } //if vvvvv not the first pixel vvvvv if ( (x > xMin || y > yMin) && *(currentPixel-1) == 0) { //y direction - left edge of the pixel vtkIdType p1 = points->InsertNextPoint(x*localStorage->m_mmPerPixel[0], y*localStorage->m_mmPerPixel[1], depth); vtkIdType p2 = points->InsertNextPoint(x*localStorage->m_mmPerPixel[0], (y+1)*localStorage->m_mmPerPixel[1], depth); lines->InsertNextCell(2); lines->InsertCellPoint(p1); lines->InsertCellPoint(p2); } //if vvvvv not the last pixel vvvvv if ( (y < yMax || (x < xMax) ) && *(currentPixel+1) == 0) { //y direction - right edge of the pixel vtkIdType p1 = points->InsertNextPoint((x+1)*localStorage->m_mmPerPixel[0], y*localStorage->m_mmPerPixel[1], depth); vtkIdType p2 = points->InsertNextPoint((x+1)*localStorage->m_mmPerPixel[0], (y+1)*localStorage->m_mmPerPixel[1], depth); lines->InsertNextCell(2); lines->InsertCellPoint(p1); lines->InsertCellPoint(p2); } /* now consider pixels at the edge of the image */ //if vvvvv left edge of image vvvvv if (x == xMin) { //draw left edge of the pixel vtkIdType p1 = points->InsertNextPoint(x*localStorage->m_mmPerPixel[0], y*localStorage->m_mmPerPixel[1], depth); vtkIdType p2 = points->InsertNextPoint(x*localStorage->m_mmPerPixel[0], (y+1)*localStorage->m_mmPerPixel[1], depth); lines->InsertNextCell(2); lines->InsertCellPoint(p1); lines->InsertCellPoint(p2); } //if vvvvv right edge of image vvvvv if (x == xMax) { //draw right edge of the pixel vtkIdType p1 = points->InsertNextPoint((x+1)*localStorage->m_mmPerPixel[0], y*localStorage->m_mmPerPixel[1], depth); vtkIdType p2 = points->InsertNextPoint((x+1)*localStorage->m_mmPerPixel[0], (y+1)*localStorage->m_mmPerPixel[1], depth); lines->InsertNextCell(2); lines->InsertCellPoint(p1); lines->InsertCellPoint(p2); } //if vvvvv bottom edge of image vvvvv if (y == yMin) { //draw bottom edge of the pixel vtkIdType p1 = points->InsertNextPoint(x*localStorage->m_mmPerPixel[0], y*localStorage->m_mmPerPixel[1], depth); vtkIdType p2 = points->InsertNextPoint((x+1)*localStorage->m_mmPerPixel[0], y*localStorage->m_mmPerPixel[1], depth); lines->InsertNextCell(2); lines->InsertCellPoint(p1); lines->InsertCellPoint(p2); } //if vvvvv top edge of image vvvvv if (y == yMax) { //draw top edge of the pixel vtkIdType p1 = points->InsertNextPoint(x*localStorage->m_mmPerPixel[0], (y+1)*localStorage->m_mmPerPixel[1], depth); vtkIdType p2 = points->InsertNextPoint((x+1)*localStorage->m_mmPerPixel[0], (y+1)*localStorage->m_mmPerPixel[1], depth); lines->InsertNextCell(2); lines->InsertCellPoint(p1); lines->InsertCellPoint(p2); } }//end if currentpixel is set x++; if (x > xMax) { //reached end of line x = xMin; y++; } // Increase the pointer-position to the next pixel. // This is safe, as the while-loop and the x-reset logic above makes // sure we do not exceed the bounds of the image currentPixel++; }//end of while // Create a polydata to store everything in vtkSmartPointer polyData = vtkSmartPointer::New(); // Add the points to the dataset polyData->SetPoints(points); // Add the lines to the dataset polyData->SetLines(lines); return polyData; } void mitk::ImageVtkMapper2D::TransformActor(mitk::BaseRenderer* renderer) { LocalStorage *localStorage = m_LSH.GetLocalStorage(renderer); //get the transformation matrix of the reslicer in order to render the slice as axial, coronal or saggital vtkSmartPointer trans = vtkSmartPointer::New(); vtkSmartPointer matrix = localStorage->m_Reslicer->GetResliceAxes(); trans->SetMatrix(matrix); //transform the plane/contour (the actual actor) to the corresponding view (axial, coronal or saggital) localStorage->m_Actor->SetUserTransform(trans); //transform the origin to center based coordinates, because MITK is center based. localStorage->m_Actor->SetPosition( -0.5*localStorage->m_mmPerPixel[0], -0.5*localStorage->m_mmPerPixel[1], 0.0); if ( localStorage->m_Actors->GetNumberOfPaths() > 1 ) { vtkActor* secondaryActor = dynamic_cast( localStorage->m_Actors->GetParts()->GetItemAsObject(0) ); secondaryActor->SetUserTransform(trans); secondaryActor->SetPosition( -0.5*localStorage->m_mmPerPixel[0], -0.5*localStorage->m_mmPerPixel[1], 0.0); } } bool mitk::ImageVtkMapper2D::RenderingGeometryIntersectsImage( const PlaneGeometry* renderingGeometry, SlicedGeometry3D* imageGeometry ) { // if either one of the two geometries is NULL we return true // for safety reasons if ( renderingGeometry == NULL || imageGeometry == NULL ) return true; // get the distance for the first cornerpoint ScalarType initialDistance = renderingGeometry->SignedDistance( imageGeometry->GetCornerPoint( 0 ) ); for( int i=1; i<8; i++ ) { mitk::Point3D cornerPoint = imageGeometry->GetCornerPoint( i ); // get the distance to the other cornerpoints ScalarType distance = renderingGeometry->SignedDistance( cornerPoint ); // if it has not the same signing as the distance of the first point if ( initialDistance * distance < 0 ) { // we have an intersection and return true return true; } } // all distances have the same sign, no intersection and we return false return false; } mitk::ImageVtkMapper2D::LocalStorage::~LocalStorage() { } mitk::ImageVtkMapper2D::LocalStorage::LocalStorage() : m_VectorComponentExtractor(vtkSmartPointer::New()) { m_LevelWindowFilter = vtkSmartPointer::New(); //Do as much actions as possible in here to avoid double executions. m_Plane = vtkSmartPointer::New(); m_Texture = vtkSmartPointer::New().GetPointer(); m_DefaultLookupTable = vtkSmartPointer::New(); m_BinaryLookupTable = vtkSmartPointer::New(); m_ColorLookupTable = vtkSmartPointer::New(); m_Mapper = vtkSmartPointer::New(); m_Actor = vtkSmartPointer::New(); m_Actors = vtkSmartPointer::New(); m_Reslicer = mitk::ExtractSliceFilter::New(); m_TSFilter = vtkSmartPointer::New(); m_OutlinePolyData = vtkSmartPointer::New(); m_ReslicedImage = vtkSmartPointer::New(); m_EmptyPolyData = vtkSmartPointer::New(); //the following actions are always the same and thus can be performed //in the constructor for each image (i.e. the image-corresponding local storage) m_TSFilter->ReleaseDataFlagOn(); mitk::LookupTable::Pointer mitkLUT = mitk::LookupTable::New(); //built a default lookuptable mitkLUT->SetType(mitk::LookupTable::GRAYSCALE); m_DefaultLookupTable = mitkLUT->GetVtkLookupTable(); mitkLUT->SetType(mitk::LookupTable::LEGACY_BINARY); m_BinaryLookupTable = mitkLUT->GetVtkLookupTable(); mitkLUT->SetType(mitk::LookupTable::LEGACY_RAINBOW_COLOR); m_ColorLookupTable = mitkLUT->GetVtkLookupTable(); //do not repeat the texture (the image) m_Texture->RepeatOff(); //set the mapper for the actor m_Actor->SetMapper( m_Mapper ); vtkSmartPointer outlineShadowActor = vtkSmartPointer::New(); outlineShadowActor->SetMapper( m_Mapper ); m_Actors->AddPart( outlineShadowActor ); m_Actors->AddPart( m_Actor ); } diff --git a/Modules/Core/src/Rendering/mitkManufacturerLogo.cpp b/Modules/Core/src/Rendering/mitkManufacturerLogo.cpp index 8f76cf2b22..bf1ab0d228 100644 --- a/Modules/Core/src/Rendering/mitkManufacturerLogo.cpp +++ b/Modules/Core/src/Rendering/mitkManufacturerLogo.cpp @@ -1,380 +1,380 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkManufacturerLogo.h" #include "mitkVtkLayerController.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include mitk::ManufacturerLogo::ManufacturerLogo() :m_ImageData(NULL) { m_RenderWindow = NULL; m_Renderer = vtkRenderer::New(); m_Actor = vtkImageActor::New(); m_Mapper = vtkImageMapper::New(); m_PngReader = vtkPNGReader::New(); m_VtkImageImport = vtkImageImport::New(); m_LogoPosition = mitk::ManufacturerLogo::LowerRight; m_IsEnabled = false; m_ForceShowMBIDepartmentLogo = false; m_ZoomFactor = 1.15; m_Opacity = 0.5; m_FileName = ""; m_PngReader->SetFileName(m_FileName.c_str()); } mitk::ManufacturerLogo::~ManufacturerLogo() { if ( m_RenderWindow != NULL ) if ( this->IsEnabled() ) this->Disable(); if ( m_Mapper != NULL ) m_Mapper->Delete(); if ( m_Actor!=NULL ) m_Actor->Delete(); if ( m_Renderer != NULL ) m_Renderer->Delete(); if ( m_PngReader != NULL ) m_PngReader->Delete(); if ( m_VtkImageImport != NULL ) m_VtkImageImport->Delete(); if ( m_ImageData != NULL) delete[] m_ImageData; } /** * Sets the renderwindow, in which the logo * will be shown. Make sure, you have called this function * before calling Enable() */ void mitk::ManufacturerLogo::SetRenderWindow( vtkRenderWindow* renderWindow ) { m_RenderWindow = renderWindow; } /** * Returns the vtkRenderWindow, which is used * for displaying the logo */ vtkRenderWindow* mitk::ManufacturerLogo::GetRenderWindow() { return m_RenderWindow; } /** * Returns the renderer responsible for * rendering the logo into the * vtkRenderWindow */ vtkRenderer* mitk::ManufacturerLogo::GetVtkRenderer() { return m_Renderer; } /** * Returns the actor associated with the logo */ vtkImageActor* mitk::ManufacturerLogo::GetActor() { return m_Actor; } /** * Returns the mapper associated with the * logo. */ vtkImageMapper* mitk::ManufacturerLogo::GetMapper() { return m_Mapper; } void mitk::ManufacturerLogo::SetLogoSource(const char* filename) { std::string file = filename; if(file.length() != 0) { m_FileName = filename; m_PngReader->SetFileName(m_FileName.c_str()); } } /** * Enables drawing of the logo. * If you want to disable it, call the Disable() function. */ void mitk::ManufacturerLogo::Enable() { if(m_IsEnabled) return; if(m_RenderWindow != NULL) { if(itksys::SystemTools::FileExists(m_FileName.c_str()) && !m_ForceShowMBIDepartmentLogo) { m_PngReader->Update(); m_Actor->SetInputData(m_PngReader->GetOutput()); } else // either logo file not found or logo renderer is forced to show the MBI logo { m_VtkImageImport->SetDataScalarTypeToUnsignedChar(); m_VtkImageImport->SetNumberOfScalarComponents(mbiLogo_NumberOfScalars); m_VtkImageImport->SetWholeExtent(0,mbiLogo_Width-1,0,mbiLogo_Height-1,0,1-1); m_VtkImageImport->SetDataExtentToWholeExtent(); // flip mbi logo around y axis and change color order m_ImageData = new char[mbiLogo_Height*mbiLogo_Width*mbiLogo_NumberOfScalars]; unsigned int column, row; char * dest = m_ImageData; char * source = (char*) &mbiLogo_Data[0];; char r, g, b, a; for (column = 0; column < mbiLogo_Height; column++) for (row = 0; row < mbiLogo_Width; row++) { //change r with b b = *source++; g = *source++; r = *source++; a = *source++; *dest++ = r; *dest++ = g; *dest++ = b; *dest++ = a; } m_VtkImageImport->SetImportVoidPointer(m_ImageData); m_VtkImageImport->Modified(); m_VtkImageImport->Update(); m_Actor->SetInputData(m_VtkImageImport->GetOutput()); } m_Actor->SetOpacity(m_Opacity); m_Renderer->AddActor( m_Actor ); m_Renderer->InteractiveOff(); SetupCamera(); SetupPosition(); mitk::VtkLayerController::GetInstance(m_RenderWindow)->InsertForegroundRenderer(m_Renderer,false); m_IsEnabled = true; } } void mitk::ManufacturerLogo::SetupCamera() { // set the vtk camera in way that stretches the logo all over the renderwindow vtkImageData * image = m_Actor->GetInput(); m_Camera = m_Renderer->GetActiveCamera(); m_Camera->SetClippingRange(1,100000); if ( !image ) return; double spacing[3]; double origin[3]; int dimensions[3]; image->GetSpacing(spacing); image->GetOrigin(origin); image->GetDimensions(dimensions); double focalPoint[3]; double position[3]; for ( unsigned int cc = 0; cc < 3; cc++) { focalPoint[cc] = origin[cc] + ( spacing[cc] * dimensions[cc] ) / 2.0; position[cc] = focalPoint[cc]; } m_Camera->SetViewUp (0,1,0); int idx = 2; const double distanceToFocalPoint = 1000; position[idx] = distanceToFocalPoint; m_Camera->ParallelProjectionOn(); m_Camera->SetPosition (position); m_Camera->SetFocalPoint (focalPoint); int d1 = (idx + 1) % 3; int d2 = (idx + 2) % 3; double max = std::max(dimensions[d1],dimensions[d2]); m_Camera->SetParallelScale( max / 2 ); } void mitk::ManufacturerLogo::SetupPosition() { // Position and Scale of the logo double newPos[4]; int dimensions[3]; vtkImageData * image = m_Actor->GetInput(); image->GetDimensions(dimensions); // normalize image dimensions double max = std::max(dimensions[0],dimensions[1]); double normX = dimensions[0] / max; double normY = dimensions[1] / max; double buffer = 0; // buffer to the boarder of the renderwindow switch(m_LogoPosition) { case mitk::ManufacturerLogo::LowerLeft: { newPos[0] = (0 + buffer); newPos[1] = (0 + buffer); newPos[2] = 0.2 * normX * m_ZoomFactor; newPos[3] = 0.2 * normY * m_ZoomFactor; break; } case mitk::ManufacturerLogo::LowerRight: { newPos[0] = (1 - buffer) - 0.2 * normX * m_ZoomFactor; newPos[1] = 0.0; newPos[2] = (1 - buffer); newPos[3] = 0.2 * normY * m_ZoomFactor; break; } case mitk::ManufacturerLogo::UpperLeft: { newPos[0] = (0 + buffer); newPos[1] = (1 - buffer) - 0.2 * normY * m_ZoomFactor; newPos[2] = 0.2 * normX * m_ZoomFactor; newPos[3] = (1 - buffer); break; } case mitk::ManufacturerLogo::UpperRight: { newPos[0] = (1 - buffer) - 0.2 * normX * m_ZoomFactor; newPos[1] = (1 - buffer) - 0.2 * normY * m_ZoomFactor; newPos[2] = (1 - buffer); newPos[3] = (1 - buffer); break; } case mitk::ManufacturerLogo::Middle: default: { - newPos[0] = 0.5 - 0.2 * normX * m_ZoomFactor; - newPos[1] = 0.5 + 0.2 * normY * m_ZoomFactor; - newPos[2] = 0.5 - 0.2 * normX * m_ZoomFactor; - newPos[3] = 0.5 + 0.2 * normY * m_ZoomFactor; + newPos[0] = 0.5 - 0.1 * normX * m_ZoomFactor; + newPos[1] = 0.5 - 0.1 * normY * m_ZoomFactor; + newPos[2] = 0.5 + 0.1 * normX * m_ZoomFactor; + newPos[3] = 0.5 + 0.1 * normY * m_ZoomFactor; break; } } m_Renderer->SetViewport(newPos); } void mitk::ManufacturerLogo::ForceMBILogoVisible(bool visible) { m_ForceShowMBIDepartmentLogo = visible; } void mitk::ManufacturerLogo::SetZoomFactor( double factor ) { m_ZoomFactor = factor; } void mitk::ManufacturerLogo::SetOpacity(double opacity) { m_Opacity = opacity; } /** * Disables drawing of the logo. * If you want to enable it, call the Enable() function. */ void mitk::ManufacturerLogo::Disable() { if ( this->IsEnabled() && !m_ForceShowMBIDepartmentLogo ) { mitk::VtkLayerController::GetInstance(m_RenderWindow)->RemoveRenderer(m_Renderer); m_IsEnabled = false; } } /** * Checks, if the logo is currently * enabled (visible) */ bool mitk::ManufacturerLogo::IsEnabled() { return m_IsEnabled; } void mitk::ManufacturerLogo::SetRequestedRegionToLargestPossibleRegion() { //nothing to do } bool mitk::ManufacturerLogo::RequestedRegionIsOutsideOfTheBufferedRegion() { return false; } bool mitk::ManufacturerLogo::VerifyRequestedRegion() { return true; } void mitk::ManufacturerLogo::SetRequestedRegion( const itk::DataObject*) { //nothing to do } diff --git a/Modules/Core/src/Rendering/mitkPlaneGeometryDataMapper2D.cpp b/Modules/Core/src/Rendering/mitkPlaneGeometryDataMapper2D.cpp index 7c56fe4036..771a7972bf 100644 --- a/Modules/Core/src/Rendering/mitkPlaneGeometryDataMapper2D.cpp +++ b/Modules/Core/src/Rendering/mitkPlaneGeometryDataMapper2D.cpp @@ -1,413 +1,440 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkPlaneGeometryDataMapper2D.h" //mitk includes #include "mitkVtkPropRenderer.h" #include #include #include #include #include #include #include #include #include //vtk includes #include -#include +#include +#include #include #include #include #include #include +#include mitk::PlaneGeometryDataMapper2D::AllInstancesContainer mitk::PlaneGeometryDataMapper2D::s_AllInstances; // input for this mapper ( = PlaneGeometryData) const mitk::PlaneGeometryData* mitk::PlaneGeometryDataMapper2D::GetInput() const { return static_cast< PlaneGeometryData * >(GetDataNode()->GetData()); } mitk::PlaneGeometryDataMapper2D::PlaneGeometryDataMapper2D() : m_RenderOrientationArrows( false ), m_ArrowOrientationPositive( true ), m_DepthValue(1.0f) { s_AllInstances.insert(this); } mitk::PlaneGeometryDataMapper2D::~PlaneGeometryDataMapper2D() { s_AllInstances.erase(this); } vtkProp* mitk::PlaneGeometryDataMapper2D::GetVtkProp(mitk::BaseRenderer * renderer) { LocalStorage *ls = m_LSH.GetLocalStorage(renderer); return ls->m_CrosshairAssembly; } void mitk::PlaneGeometryDataMapper2D::GenerateDataForRenderer( mitk::BaseRenderer *renderer ) { BaseLocalStorage *ls = m_LSH.GetLocalStorage(renderer); // The PlaneGeometryDataMapper2D mapper is special in that the rendering of // OTHER PlaneGeometryDatas affects how we render THIS PlaneGeometryData // (for the gap at the point where they intersect). A change in any of the // other PlaneGeometryData nodes could mean that we render ourself // differently, so we check for that here. bool generateDataRequired = false; for (AllInstancesContainer::iterator it = s_AllInstances.begin(); it != s_AllInstances.end(); ++it) { generateDataRequired = ls->IsGenerateDataRequired(renderer, this, (*it)->GetDataNode()); if (generateDataRequired) break; } ls->UpdateGenerateDataTime(); // Collect all other PlaneGeometryDatas that are being mapped by this mapper m_OtherPlaneGeometries.clear(); for (AllInstancesContainer::iterator it = s_AllInstances.begin(); it != s_AllInstances.end(); ++it) { Self *otherInstance = *it; // Skip ourself if (otherInstance == this) continue; mitk::DataNode *otherNode = otherInstance->GetDataNode(); if (!otherNode) continue; // Skip other PlaneGeometryData nodes that are not visible on this renderer if (!otherNode->IsVisible(renderer)) continue; PlaneGeometryData* otherData = dynamic_cast(otherNode->GetData()); if (!otherData) continue; PlaneGeometry* otherGeometry = dynamic_cast(otherData->GetPlaneGeometry()); if ( otherGeometry && !dynamic_cast(otherData->GetPlaneGeometry()) ) { m_OtherPlaneGeometries.push_back(otherNode); } } CreateVtkCrosshair(renderer); ApplyAllProperties(renderer); } void mitk::PlaneGeometryDataMapper2D::CreateVtkCrosshair(mitk::BaseRenderer *renderer) { bool visible = true; GetDataNode()->GetVisibility(visible, renderer, "visible"); - if(!visible) return; + if(!visible) + { + return; + } PlaneGeometryData::Pointer input = const_cast< PlaneGeometryData * >(this->GetInput()); mitk::DataNode* geometryDataNode = renderer->GetCurrentWorldPlaneGeometryNode(); const PlaneGeometryData* rendererWorldPlaneGeometryData = dynamic_cast< PlaneGeometryData * >(geometryDataNode->GetData()); // intersecting with ourself? if ( input.IsNull() || input.GetPointer() == rendererWorldPlaneGeometryData) { return; //nothing to do in this case } const PlaneGeometry *inputPlaneGeometry = dynamic_cast< const PlaneGeometry * >( input->GetPlaneGeometry() ); const PlaneGeometry* worldPlaneGeometry = dynamic_cast< const PlaneGeometry* >( rendererWorldPlaneGeometryData->GetPlaneGeometry() ); if ( worldPlaneGeometry && dynamic_cast(worldPlaneGeometry)==NULL && inputPlaneGeometry && dynamic_cast(input->GetPlaneGeometry() )==NULL && inputPlaneGeometry->GetReferenceGeometry() ) { const BaseGeometry *referenceGeometry = inputPlaneGeometry->GetReferenceGeometry(); // calculate intersection of the plane data with the border of the // world geometry rectangle Point3D point1, point2; Line3D crossLine; // Calculate the intersection line of the input plane with the world plane if ( worldPlaneGeometry->IntersectionLine( inputPlaneGeometry, crossLine ) ) { Point3D boundingBoxMin, boundingBoxMax; boundingBoxMin = referenceGeometry->GetCornerPoint(0); boundingBoxMax = referenceGeometry->GetCornerPoint(7); Point3D indexLinePoint; Vector3D indexLineDirection; referenceGeometry->WorldToIndex(crossLine.GetPoint(),indexLinePoint); referenceGeometry->WorldToIndex(crossLine.GetDirection(),indexLineDirection); referenceGeometry->WorldToIndex(boundingBoxMin,boundingBoxMin); referenceGeometry->WorldToIndex(boundingBoxMax,boundingBoxMax); // Then, clip this line with the (transformed) bounding box of the // reference geometry. Line3D::BoxLineIntersection( boundingBoxMin[0], boundingBoxMin[1], boundingBoxMin[2], boundingBoxMax[0], boundingBoxMax[1], boundingBoxMax[2], indexLinePoint, indexLineDirection, point1, point2 ); referenceGeometry->IndexToWorld(point1,point1); referenceGeometry->IndexToWorld(point2,point2); crossLine.SetPoints(point1,point2); vtkSmartPointer lines = vtkSmartPointer::New(); vtkSmartPointer points = vtkSmartPointer::New(); vtkSmartPointer linesPolyData = vtkSmartPointer::New(); // Now iterate through all other lines displayed in this window and // calculate the positions of intersection with the line to be // rendered; these positions will be stored in lineParams to form a // gap afterwards. NodesVectorType::iterator otherPlanesIt = m_OtherPlaneGeometries.begin(); NodesVectorType::iterator otherPlanesEnd = m_OtherPlaneGeometries.end(); std::vector intersections; intersections.push_back(point1); otherPlanesIt = m_OtherPlaneGeometries.begin(); int gapsize = 32; this->GetDataNode()->GetPropertyValue( "Crosshair.Gap Size",gapsize, NULL ); ScalarType lineLength = point1.EuclideanDistanceTo(point2); DisplayGeometry *displayGeometry = renderer->GetDisplayGeometry(); ScalarType gapinmm = gapsize * displayGeometry->GetScaleFactorMMPerDisplayUnit(); float gapSizeParam = gapinmm / lineLength; while ( otherPlanesIt != otherPlanesEnd ) { PlaneGeometry *otherPlane = static_cast< PlaneGeometry * >( static_cast< PlaneGeometryData * >((*otherPlanesIt)->GetData() )->GetPlaneGeometry() ); if (otherPlane != inputPlaneGeometry && otherPlane != worldPlaneGeometry) { Point3D planeIntersection; otherPlane->IntersectionPoint(crossLine,planeIntersection); ScalarType sectionLength = point1.EuclideanDistanceTo(planeIntersection); ScalarType lineValue = sectionLength/lineLength; if(lineValue-gapSizeParam > 0.0) intersections.push_back(crossLine.GetPoint(lineValue-gapSizeParam)); else intersections.pop_back(); if(lineValue+gapSizeParam < 1.0) intersections.push_back(crossLine.GetPoint(lineValue+gapSizeParam)); } ++otherPlanesIt; } if(intersections.size()%2 == 1) intersections.push_back(point2); if(intersections.empty()) { this->DrawLine(point1,point2,lines,points); } else for(unsigned int i = 0 ; i< intersections.size()-1 ; i+=2) { this->DrawLine(intersections[i],intersections[i+1],lines,points); } // Add the points to the dataset linesPolyData->SetPoints(points); // Add the lines to the dataset linesPolyData->SetLines(lines); // Visualize - vtkSmartPointer mapper = vtkSmartPointer::New(); - mapper->SetInputData(linesPolyData); LocalStorage* ls = m_LSH.GetLocalStorage(renderer); - ls->m_CrosshairActor->SetMapper(mapper); + ls->m_Mapper->SetInputData(linesPolyData); + ls->m_CrosshairActor->SetMapper(ls->m_Mapper); + + vtkCoordinate *tcoord = vtkCoordinate::New(); + tcoord->SetCoordinateSystemToWorld(); + ls->m_Mapper->SetTransformCoordinate(tcoord); + tcoord->Delete(); // Determine if we should draw the area covered by the thick slicing, default is false. // This will also show the area of slices that do not have thick slice mode enabled bool showAreaOfThickSlicing = false; GetDataNode()->GetBoolProperty( "reslice.thickslices.showarea", showAreaOfThickSlicing ); // get the normal of the inputPlaneGeometry Vector3D normal = inputPlaneGeometry->GetNormal(); // determine the pixelSpacing in that direction double thickSliceDistance = SlicedGeometry3D::CalculateSpacing( referenceGeometry->GetSpacing(), normal ); IntProperty *intProperty=0; if( GetDataNode()->GetProperty( intProperty, "reslice.thickslices.num" ) && intProperty ) thickSliceDistance *= intProperty->GetValue()+0.5; else showAreaOfThickSlicing = false; // not the nicest place to do it, but we have the width of the visible bloc in MM here // so we store it in this fancy property GetDataNode()->SetFloatProperty( "reslice.thickslices.sizeinmm", thickSliceDistance*2 ); + ls->m_CrosshairAssembly = vtkSmartPointer ::New(); + ls->m_CrosshairAssembly->AddPart(ls->m_CrosshairActor); + + // Visualize + vtkSmartPointer helperlinesPolyData = vtkSmartPointer::New(); + ls->m_HelperLinesmapper->SetInputData(helperlinesPolyData); + ls->m_CrosshairHelperLineActor->SetVisibility(showAreaOfThickSlicing); if ( showAreaOfThickSlicing ) { vtkSmartPointer helperlines = vtkSmartPointer::New(); - vtkSmartPointer helperlinesPolyData = vtkSmartPointer::New(); // vectorToHelperLine defines how to reach the helperLine from the mainLine Vector3D vectorToHelperLine; vectorToHelperLine = normal; vectorToHelperLine.Normalize(); // got the right direction, so we multiply the width vectorToHelperLine *= thickSliceDistance; this->DrawLine(point1 - vectorToHelperLine, point2 - vectorToHelperLine,helperlines,points); this->DrawLine(point1 + vectorToHelperLine, point2 + vectorToHelperLine,helperlines,points); // Add the points to the dataset helperlinesPolyData->SetPoints(points); // Add the lines to the dataset helperlinesPolyData->SetLines(helperlines); - // Visualize - vtkSmartPointer helperLinesmapper = vtkSmartPointer::New(); - helperLinesmapper->SetInputData(helperlinesPolyData); - ls->m_CrosshairActor->GetProperty()->SetLineStipplePattern(0xf0f0); ls->m_CrosshairActor->GetProperty()->SetLineStippleRepeatFactor(1); - - ls->m_CrosshairHelperLineActor->SetMapper(helperLinesmapper); ls->m_CrosshairAssembly->AddPart(ls->m_CrosshairHelperLineActor); } - else - { - ls->m_CrosshairAssembly->RemovePart(ls->m_CrosshairHelperLineActor); - ls->m_CrosshairActor->GetProperty()->SetLineStipplePattern(0xffff); - } } } } void mitk::PlaneGeometryDataMapper2D::DrawLine( mitk::Point3D p0,mitk::Point3D p1, vtkCellArray* lines, vtkPoints* points ) { vtkIdType pidStart = points->InsertNextPoint(p0[0],p0[1], p0[2]); vtkIdType pidEnd = points->InsertNextPoint(p1[0],p1[1], p1[2]); vtkSmartPointer lineVtk = vtkSmartPointer::New(); lineVtk->GetPointIds()->SetId(0,pidStart); lineVtk->GetPointIds()->SetId(1,pidEnd); lines->InsertNextCell(lineVtk); } int mitk::PlaneGeometryDataMapper2D::DetermineThickSliceMode( DataNode * dn, int &thickSlicesNum ) { int thickSlicesMode = 0; // determine the state and the extend of the thick-slice mode mitk::ResliceMethodProperty *resliceMethodEnumProperty=0; if( dn->GetProperty( resliceMethodEnumProperty, "reslice.thickslices" ) && resliceMethodEnumProperty ) thickSlicesMode = resliceMethodEnumProperty->GetValueAsId(); IntProperty *intProperty=0; if( dn->GetProperty( intProperty, "reslice.thickslices.num" ) && intProperty ) { thickSlicesNum = intProperty->GetValue(); if(thickSlicesNum < 1) thickSlicesNum=0; if(thickSlicesNum > 10) thickSlicesNum=10; } if ( thickSlicesMode == 0 ) thickSlicesNum = 0; return thickSlicesMode; } void mitk::PlaneGeometryDataMapper2D::ApplyAllProperties( BaseRenderer *renderer ) { LocalStorage *ls = m_LSH.GetLocalStorage(renderer); - Superclass::ApplyColorAndOpacityProperties(renderer, ls->m_CrosshairActor); - Superclass::ApplyColorAndOpacityProperties(renderer, ls->m_CrosshairHelperLineActor); + ApplyColorAndOpacityProperties2D(renderer, ls->m_CrosshairActor); + ApplyColorAndOpacityProperties2D(renderer, ls->m_CrosshairHelperLineActor); float thickness; this->GetDataNode()->GetFloatProperty("Line width",thickness,renderer); ls->m_CrosshairActor->GetProperty()->SetLineWidth(thickness); ls->m_CrosshairHelperLineActor->GetProperty()->SetLineWidth(thickness); PlaneOrientationProperty* decorationProperty; this->GetDataNode()->GetProperty( decorationProperty, "decoration", renderer ); if ( decorationProperty != NULL ) { if ( decorationProperty->GetPlaneDecoration() == PlaneOrientationProperty::PLANE_DECORATION_POSITIVE_ORIENTATION ) { m_RenderOrientationArrows = true; m_ArrowOrientationPositive = true; } else if ( decorationProperty->GetPlaneDecoration() == PlaneOrientationProperty::PLANE_DECORATION_NEGATIVE_ORIENTATION ) { m_RenderOrientationArrows = true; m_ArrowOrientationPositive = false; } else { m_RenderOrientationArrows = false; } } } +void mitk::PlaneGeometryDataMapper2D::ApplyColorAndOpacityProperties2D(BaseRenderer* renderer, vtkActor2D* actor) +{ + float rgba[4]={1.0f,1.0f,1.0f,1.0f}; + DataNode * node = GetDataNode(); + + // check for color prop and use it for rendering if it exists + node->GetColor(rgba, renderer, "color"); + // check for opacity prop and use it for rendering if it exists + node->GetOpacity(rgba[3], renderer, "opacity"); + + double drgba[4]={rgba[0],rgba[1],rgba[2],rgba[3]}; + actor->GetProperty()->SetColor(drgba); + actor->GetProperty()->SetOpacity(drgba[3]); +} + void mitk::PlaneGeometryDataMapper2D::SetDefaultProperties(mitk::DataNode* node, mitk::BaseRenderer* renderer, bool overwrite) { mitk::IPropertyAliases* aliases = mitk::CoreServices::GetPropertyAliases(); node->AddProperty( "Line width", mitk::FloatProperty::New(1), renderer, overwrite ); aliases->AddAlias( "line width", "Crosshair.Line Width", ""); node->AddProperty( "Crosshair.Gap Size", mitk::IntProperty::New(32), renderer, overwrite ); node->AddProperty( "decoration", mitk::PlaneOrientationProperty ::New(PlaneOrientationProperty::PLANE_DECORATION_NONE), renderer, overwrite ); aliases->AddAlias( "decoration", "Crosshair.Orientation Decoration", ""); Superclass::SetDefaultProperties(node, renderer, overwrite); } void mitk::PlaneGeometryDataMapper2D::UpdateVtkTransform(mitk::BaseRenderer* /*renderer*/) { } mitk::PlaneGeometryDataMapper2D::LocalStorage::LocalStorage() { m_CrosshairAssembly = vtkSmartPointer ::New(); - m_CrosshairActor = vtkSmartPointer ::New(); - m_CrosshairHelperLineActor = vtkSmartPointer ::New(); - m_CrosshairAssembly->AddPart(m_CrosshairActor); - m_CrosshairAssembly->AddPart(m_CrosshairHelperLineActor); + m_CrosshairActor = vtkSmartPointer ::New(); + m_CrosshairHelperLineActor = vtkSmartPointer ::New(); + m_HelperLinesmapper = vtkSmartPointer::New(); + m_Mapper = vtkSmartPointer::New(); + m_CrosshairActor->SetMapper(m_Mapper); + m_CrosshairHelperLineActor->SetMapper(m_HelperLinesmapper); + + vtkCoordinate *tcoord = vtkCoordinate::New(); + tcoord->SetCoordinateSystemToWorld(); + m_HelperLinesmapper->SetTransformCoordinate(tcoord); + m_Mapper->SetTransformCoordinate(tcoord); + tcoord->Delete(); } mitk::PlaneGeometryDataMapper2D::LocalStorage::~LocalStorage() { } diff --git a/Modules/DataTypesExt/src/mitkUnstructuredGrid.cpp b/Modules/DataTypesExt/src/mitkUnstructuredGrid.cpp index bc9577bba7..82ea53d899 100644 --- a/Modules/DataTypesExt/src/mitkUnstructuredGrid.cpp +++ b/Modules/DataTypesExt/src/mitkUnstructuredGrid.cpp @@ -1,265 +1,265 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkUnstructuredGrid.h" #include void mitk::UnstructuredGrid::SetVtkUnstructuredGrid( vtkUnstructuredGrid* grid, unsigned int t ) { - this->Expand(t); + this->Expand(t+1); if(m_GridSeries[ t ] != NULL) { m_GridSeries[ t ]->Delete(); } m_GridSeries[ t ] = grid; // call m_VtkPolyData->Register(NULL) to tell the reference counting that we // want to keep a reference on the object if (m_GridSeries[t] != 0) m_GridSeries[t]->Register(grid); this->Modified(); m_CalculateBoundingBox = true; } void mitk::UnstructuredGrid::Expand(unsigned int timeSteps) { // check if the vector is long enough to contain the new element // at the given position. If not, expand it with sufficient zero-filled elements. if(timeSteps > m_GridSeries.size()) { Superclass::Expand(timeSteps); vtkUnstructuredGrid* pdnull = 0; m_GridSeries.resize( timeSteps, pdnull ); m_CalculateBoundingBox = true; } } void mitk::UnstructuredGrid::ClearData() { for ( VTKUnstructuredGridSeries::iterator it = m_GridSeries.begin(); it != m_GridSeries.end(); ++it ) { if ( ( *it ) != 0 ) ( *it )->Delete(); } m_GridSeries.clear(); Superclass::ClearData(); } void mitk::UnstructuredGrid::InitializeEmpty() { vtkUnstructuredGrid* pdnull = 0; m_GridSeries.resize( 1, pdnull ); Superclass::InitializeTimeGeometry(1); m_Initialized = true; } vtkUnstructuredGrid* mitk::UnstructuredGrid::GetVtkUnstructuredGrid(unsigned int t) { if ( t < m_GridSeries.size() ) { vtkUnstructuredGrid* grid = m_GridSeries[ t ]; if((grid == 0) && (GetSource().GetPointer() != 0)) { RegionType requestedregion; requestedregion.SetIndex(3, t); requestedregion.SetSize(3, 1); SetRequestedRegion(&requestedregion); GetSource()->Update(); } grid = m_GridSeries[ t ]; return grid; } else return 0; } void mitk::UnstructuredGrid::Graft(const DataObject* data) { const UnstructuredGrid* grid = dynamic_cast(data); if(grid == NULL) mitkThrow() << "Data object used to graft surface is not a mitk::Surface."; this->CopyInformation(data); m_GridSeries.clear(); for (unsigned int i = 0; i < grid->m_GridSeries.size(); ++i) { m_GridSeries.push_back(vtkUnstructuredGrid::New()); m_GridSeries.back()->DeepCopy(const_cast(grid)->GetVtkUnstructuredGrid(i)); } } mitk::UnstructuredGrid::UnstructuredGrid() : m_CalculateBoundingBox( false ) { this->InitializeEmpty(); } mitk::UnstructuredGrid::UnstructuredGrid(const mitk::UnstructuredGrid &other) : BaseData(other), m_LargestPossibleRegion(other.m_LargestPossibleRegion), m_CalculateBoundingBox( other.m_CalculateBoundingBox ) { if(!other.m_Initialized) { this->InitializeEmpty(); } else { m_GridSeries = other.m_GridSeries; m_Initialized = other.m_Initialized; } this->SetRequestedRegion( const_cast(&other) ); } mitk::UnstructuredGrid::~UnstructuredGrid() { this->ClearData(); } void mitk::UnstructuredGrid::UpdateOutputInformation() { if ( this->GetSource() ) { this->GetSource()->UpdateOutputInformation(); } if ( ( m_CalculateBoundingBox ) && ( m_GridSeries.size() > 0 ) ) CalculateBoundingBox(); else GetTimeGeometry()->Update(); } void mitk::UnstructuredGrid::CalculateBoundingBox() { // // first make sure, that the associated time sliced geometry has // the same number of geometry 3d's as vtkUnstructuredGrids are present // TimeGeometry* timeGeometry = GetTimeGeometry(); if ( timeGeometry->CountTimeSteps() != m_GridSeries.size() ) { itkExceptionMacro(<<"timeGeometry->CountTimeSteps() != m_GridSeries.size() -- use Initialize(timeSteps) with correct number of timeSteps!"); } // // Iterate over the vtkUnstructuredGrids and update the Geometry // information of each of the items. // for ( unsigned int i = 0 ; i < m_GridSeries.size() ; ++i ) { vtkUnstructuredGrid* grid = m_GridSeries[ i ]; double bounds[ ] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0}; if ( ( grid != 0 ) && ( grid->GetNumberOfCells() > 0 ) ) { // grid->Update(); //VTK6_TODO grid->ComputeBounds(); grid->GetBounds( bounds ); } mitk::BaseGeometry::Pointer g3d = timeGeometry->GetGeometryForTimeStep( i ); assert( g3d.IsNotNull() ); g3d->SetFloatBounds( bounds ); } timeGeometry->Update(); mitk::BoundingBox::Pointer bb = const_cast( timeGeometry->GetBoundingBoxInWorld() ); itkDebugMacro( << "boundingbox min: "<< bb->GetMinimum()); itkDebugMacro( << "boundingbox max: "<< bb->GetMaximum()); m_CalculateBoundingBox = false; } void mitk::UnstructuredGrid::SetRequestedRegionToLargestPossibleRegion() { m_RequestedRegion = GetLargestPossibleRegion(); } bool mitk::UnstructuredGrid::RequestedRegionIsOutsideOfTheBufferedRegion() { RegionType::IndexValueType end = m_RequestedRegion.GetIndex(3)+m_RequestedRegion.GetSize(3); if(((RegionType::IndexValueType)m_GridSeries.size()) < end) return true; for( RegionType::IndexValueType t=m_RequestedRegion.GetIndex(3); t < end; ++t ) if(m_GridSeries[t] == 0) return true; return false; } bool mitk::UnstructuredGrid::VerifyRequestedRegion() { if( (m_RequestedRegion.GetIndex(3)>=0) && (m_RequestedRegion.GetIndex(3)+m_RequestedRegion.GetSize(3)<=m_GridSeries.size()) ) return true; return false; } void mitk::UnstructuredGrid::SetRequestedRegion(const itk::DataObject *data ) { const mitk::UnstructuredGrid *gridData; gridData = dynamic_cast(data); if (gridData) { m_RequestedRegion = gridData->GetRequestedRegion(); } else { // pointer could not be cast back down itkExceptionMacro( << "mitk::UnstructuredGrid::SetRequestedRegion(DataObject*) cannot cast " << typeid(data).name() << " to " << typeid(UnstructuredGrid*).name() ); } } void mitk::UnstructuredGrid::SetRequestedRegion(UnstructuredGrid::RegionType *region) //by arin { if(region != 0) { m_RequestedRegion = *region; } else { // pointer could not be cast back down itkExceptionMacro( << "mitk::UnstructuredGrid::SetRequestedRegion(UnstructuredGrid::RegionType*) cannot cast " << typeid(region).name() << " to " << typeid(UnstructuredGrid*).name() ); } } void mitk::UnstructuredGrid::CopyInformation( const itk::DataObject * data ) { Superclass::CopyInformation(data); } void mitk::UnstructuredGrid::Update() { if ( GetSource().IsNull() ) { for ( VTKUnstructuredGridSeries::iterator it = m_GridSeries.begin() ; it != m_GridSeries.end() ; ++it ) { // if ( ( *it ) != 0 ) // ( *it )->Update(); //VTK6_TODO } } Superclass::Update(); } diff --git a/Modules/MapperExt/include/mitkUnstructuredGridMapper2D.h b/Modules/MapperExt/include/mitkUnstructuredGridMapper2D.h index 7a7ac86004..ab8bb651bc 100644 --- a/Modules/MapperExt/include/mitkUnstructuredGridMapper2D.h +++ b/Modules/MapperExt/include/mitkUnstructuredGridMapper2D.h @@ -1,114 +1,114 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MitkPointSetSliceLMapper2D_H #define MitkPointSetSliceLMapper2D_H #include "mitkCommon.h" #include "MitkMapperExtExports.h" #include "mitkGLMapper.h" #include "mitkTransferFunction.h" #include "mitkProperties.h" #include "mitkColorProperty.h" #include "mitkVtkScalarModeProperty.h" class vtkPointSetSlicer; class vtkPlane; class vtkLookupTable; class vtkPointSet; class vtkScalarsToColors; class vtkPiecewiseFunction; class vtkAbstractMapper3D; namespace mitk { class BaseRenderer; /** * @brief OpenGL-based mapper to display a 2d cut through a poly data * OpenGL-based mapper to display a 2D cut through a poly data. The result is * normally a line. This class can be added to any data object, which is * rendered in 3D via a vtkPolyData. */ class MITKMAPPEREXT_EXPORT UnstructuredGridMapper2D : public GLMapper { public: mitkClassMacro( UnstructuredGridMapper2D, GLMapper ); itkFactorylessNewMacro(Self) itkCloneMacro(Self) /** * Renders a cut through a pointset by cutting trough the n-cells, * producing (n-1)-cells. * @param renderer the render to render in. */ virtual void Paint( mitk::BaseRenderer* renderer ); LocalStorageHandler m_LSH; protected: UnstructuredGridMapper2D(); virtual ~UnstructuredGridMapper2D(); virtual void GenerateDataForRenderer(BaseRenderer*); /** * Determines, if the associated BaseData is mapped three-dimensionally (mapper-slot id 2) * with a class convertable to vtkAbstractMapper3D(). * @returns NULL if it is not convertable or the appropriate Mapper otherwise */ virtual vtkAbstractMapper3D* GetVtkAbstractMapper3D(BaseRenderer* renderer); /** * Determines the pointset object to be cut. * returns the pointset if possible, otherwise NULL. */ - virtual vtkPointSet* GetVtkPointSet(BaseRenderer* renderer ); + virtual vtkPointSet* GetVtkPointSet(BaseRenderer* renderer, int time = 0 ); /** * Determines the LookupTable used by the associated vtkMapper. * returns the LUT if possible, otherwise NULL. */ virtual vtkScalarsToColors* GetVtkLUT(BaseRenderer* renderer ); /** * Checks if this mapper can be used to generate cuts through the associated * base data. * @return true if yes or false if not. */ virtual bool IsConvertibleToVtkPointSet(BaseRenderer* renderer); vtkPlane* m_Plane; vtkPointSetSlicer* m_Slicer; vtkPointSet* m_VtkPointSet; vtkScalarsToColors* m_ScalarsToColors; vtkPiecewiseFunction* m_ScalarsToOpacity; mitk::ColorProperty::Pointer m_Color; mitk::IntProperty::Pointer m_LineWidth; mitk::BoolProperty::Pointer m_Outline; mitk::BoolProperty::Pointer m_ScalarVisibility; mitk::VtkScalarModeProperty::Pointer m_ScalarMode; }; } // namespace mitk #endif /* MitkPointSetSliceLMapper2D_H */ diff --git a/Modules/MapperExt/src/mitkUnstructuredGridMapper2D.cpp b/Modules/MapperExt/src/mitkUnstructuredGridMapper2D.cpp index db4b67c26c..557aef248b 100644 --- a/Modules/MapperExt/src/mitkUnstructuredGridMapper2D.cpp +++ b/Modules/MapperExt/src/mitkUnstructuredGridMapper2D.cpp @@ -1,574 +1,574 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include #include "mitkUnstructuredGridMapper2D.h" #include "mitkBaseRenderer.h" #include "mitkPlaneGeometry.h" #include "mitkUnstructuredGrid.h" #include "mitkTransferFunction.h" #include "mitkTransferFunctionProperty.h" #include "mitkColorProperty.h" #include "mitkVtkScalarModeProperty.h" #include "mitkProperties.h" #include "mitkAbstractTransformGeometry.h" #include "mitkVtkMapper3D.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "vtkPointSetSlicer.h" void mitk::UnstructuredGridMapper2D::GenerateDataForRenderer( mitk::BaseRenderer* renderer ) { BaseLocalStorage *ls = m_LSH.GetLocalStorage(renderer); bool needGenerateData = ls->IsGenerateDataRequired( renderer, this, GetDataNode() ); if(needGenerateData) { ls->UpdateGenerateDataTime(); mitk::DataNode::ConstPointer node = this->GetDataNode(); if ( node.IsNull() ) return; if (!node->GetProperty(m_ScalarMode, "scalar mode")) { m_ScalarMode = mitk::VtkScalarModeProperty::New(0); } if (!node->GetProperty(m_ScalarVisibility, "scalar visibility")) { m_ScalarVisibility = mitk::BoolProperty::New(true); } if (!node->GetProperty(m_Outline, "outline polygons")) { m_Outline = mitk::BoolProperty::New(false); } if (!node->GetProperty(m_Color, "color")) { m_Color = mitk::ColorProperty::New(1.0f, 1.0f, 1.0f); } if (!node->GetProperty(m_LineWidth, "line width")) { m_LineWidth = mitk::IntProperty::New(1); } } mitk::BaseData::Pointer input = const_cast( GetDataNode()->GetData() ); assert( input ); input->Update(); if (m_VtkPointSet) m_VtkPointSet->UnRegister(0); - m_VtkPointSet = this->GetVtkPointSet(renderer); + m_VtkPointSet = this->GetVtkPointSet(renderer, this->GetTimestep()); assert(m_VtkPointSet); m_VtkPointSet->Register(0); if (m_ScalarVisibility->GetValue()) { mitk::DataNode::ConstPointer node = this->GetDataNode(); mitk::TransferFunctionProperty::Pointer transferFuncProp; node->GetProperty(transferFuncProp, "TransferFunction", renderer); if (transferFuncProp.IsNotNull()) { mitk::TransferFunction::Pointer tf = transferFuncProp->GetValue(); if (m_ScalarsToColors) m_ScalarsToColors->UnRegister(0); m_ScalarsToColors = static_cast(tf->GetColorTransferFunction()); m_ScalarsToColors->Register(0); if (m_ScalarsToOpacity) m_ScalarsToOpacity->UnRegister(0); m_ScalarsToOpacity = tf->GetScalarOpacityFunction(); m_ScalarsToOpacity->Register(0); } else { if (m_ScalarsToColors) m_ScalarsToColors->UnRegister(0); m_ScalarsToColors = this->GetVtkLUT(renderer); assert(m_ScalarsToColors); m_ScalarsToColors->Register(0); float opacity; node->GetOpacity(opacity, renderer); if (m_ScalarsToOpacity) m_ScalarsToOpacity->UnRegister(0); m_ScalarsToOpacity = vtkPiecewiseFunction::New(); double range[2]; m_VtkPointSet->GetScalarRange(range); m_ScalarsToOpacity->AddSegment(range[0], opacity, range[1], opacity); } } } void mitk::UnstructuredGridMapper2D::Paint( mitk::BaseRenderer* renderer ) { bool visible = true; GetDataNode()->GetVisibility(visible, renderer, "visible"); if(!visible) return; vtkLinearTransform * vtktransform = GetDataNode()->GetVtkTransform(); vtkLinearTransform * inversetransform = vtktransform->GetLinearInverse(); PlaneGeometry::ConstPointer worldGeometry = renderer->GetCurrentWorldPlaneGeometry(); PlaneGeometry::ConstPointer worldPlaneGeometry = dynamic_cast( worldGeometry.GetPointer() ); Point3D point; Vector3D normal; if(worldPlaneGeometry.IsNotNull()) { // set up vtkPlane according to worldGeometry point=worldPlaneGeometry->GetOrigin(); normal=worldPlaneGeometry->GetNormal(); normal.Normalize(); m_Plane->SetTransform((vtkAbstractTransform*)NULL); } else { //@FIXME: does not work correctly. Does m_Plane->SetTransform really transforms a "plane plane" into a "curved plane"? return; AbstractTransformGeometry::ConstPointer worldAbstractGeometry = dynamic_cast(renderer->GetCurrentWorldPlaneGeometry()); if(worldAbstractGeometry.IsNotNull()) { // set up vtkPlane according to worldGeometry point=const_cast(worldAbstractGeometry->GetParametricBoundingBox())->GetMinimum(); FillVector3D(normal, 0, 0, 1); m_Plane->SetTransform(worldAbstractGeometry->GetVtkAbstractTransform()->GetInverse()); } else return; } double vp[ 3 ], vnormal[ 3 ]; vnl2vtk(point.GetVnlVector(), vp); vnl2vtk(normal.GetVnlVector(), vnormal); //normally, we would need to transform the surface and cut the transformed surface with the cutter. //This might be quite slow. Thus, the idea is, to perform an inverse transform of the plane instead. //@todo It probably does not work for scaling operations yet:scaling operations have to be //dealed with after the cut is performed by scaling the contour. inversetransform->TransformPoint( vp, vp ); inversetransform->TransformNormalAtPoint( vp, vnormal, vnormal ); m_Plane->SetOrigin( vp ); m_Plane->SetNormal( vnormal ); // set data into cutter m_Slicer->SetInputData( m_VtkPointSet ); // m_Cutter->GenerateCutScalarsOff(); // m_Cutter->SetSortByToSortByCell(); // calculate the cut m_Slicer->Update(); // fetch geometry mitk::DisplayGeometry::Pointer displayGeometry = renderer->GetDisplayGeometry(); assert( displayGeometry ); // float toGL=displayGeometry->GetSizeInDisplayUnits()[1]; //apply color and opacity read from the PropertyList ApplyColorAndOpacityProperties( renderer ); // traverse the cut contour vtkPolyData * contour = m_Slicer->GetOutput(); vtkPoints *vpoints = contour->GetPoints(); vtkCellArray *vlines = contour->GetLines(); vtkCellArray *vpolys = contour->GetPolys(); vtkPointData *vpointdata = contour->GetPointData(); vtkDataArray* vscalars = vpointdata->GetScalars(); vtkCellData *vcelldata = contour->GetCellData(); vtkDataArray* vcellscalars = vcelldata->GetScalars(); const int numberOfLines = contour->GetNumberOfLines(); const int numberOfPolys = contour->GetNumberOfPolys(); const bool useCellData = m_ScalarMode->GetVtkScalarMode() == VTK_SCALAR_MODE_DEFAULT || m_ScalarMode->GetVtkScalarMode() == VTK_SCALAR_MODE_USE_CELL_DATA; const bool usePointData = m_ScalarMode->GetVtkScalarMode() == VTK_SCALAR_MODE_USE_POINT_DATA; Point3D p; Point2D p2d; vlines->InitTraversal(); vpolys->InitTraversal(); mitk::Color outlineColor = m_Color->GetColor(); glLineWidth((float)m_LineWidth->GetValue()); for (int i = 0;i < numberOfLines;++i ) { vtkIdType *cell(0); vtkIdType cellSize(0); vlines->GetNextCell( cellSize, cell ); float rgba[4] = {outlineColor[0], outlineColor[1], outlineColor[2], 1.0f}; if (m_ScalarVisibility->GetValue() && vcellscalars) { if ( useCellData ) { // color each cell according to cell data double scalar = vcellscalars->GetComponent( i, 0 ); double rgb[3] = { 1.0f, 1.0f, 1.0f }; m_ScalarsToColors->GetColor(scalar, rgb); rgba[0] = (float)rgb[0]; rgba[1] = (float)rgb[1]; rgba[2] = (float)rgb[2]; rgba[3] = (float)m_ScalarsToOpacity->GetValue(scalar); } else if ( usePointData ) { double scalar = vscalars->GetComponent( i, 0 ); double rgb[3] = { 1.0f, 1.0f, 1.0f }; m_ScalarsToColors->GetColor(scalar, rgb); rgba[0] = (float)rgb[0]; rgba[1] = (float)rgb[1]; rgba[2] = (float)rgb[2]; rgba[3] = (float)m_ScalarsToOpacity->GetValue(scalar); } } glColor4fv( rgba ); glBegin ( GL_LINE_LOOP ); for ( int j = 0;j < cellSize;++j ) { vpoints->GetPoint( cell[ j ], vp ); //take transformation via vtktransform into account vtktransform->TransformPoint( vp, vp ); vtk2itk( vp, p ); //convert 3D point (in mm) to 2D point on slice (also in mm) worldGeometry->Map( p, p2d ); //convert point (until now mm and in worldcoordinates) to display coordinates (units ) displayGeometry->WorldToDisplay( p2d, p2d ); //convert display coordinates ( (0,0) is top-left ) in GL coordinates ( (0,0) is bottom-left ) //p2d[1]=toGL-p2d[1]; //add the current vertex to the line glVertex2f( p2d[0], p2d[1] ); } glEnd (); } bool polyOutline = m_Outline->GetValue(); bool scalarVisibility = m_ScalarVisibility->GetValue(); // cache the transformed points // a fixed size array is way faster than 'new' // slices through 3d cells usually do not generated // polygons with more than 6 vertices const int maxPolySize = 10; Point2D* cachedPoints = new Point2D[maxPolySize*numberOfPolys]; glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // only draw polygons if there are cell scalars // or the outline property is set to true if (scalarVisibility && vcellscalars) { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); for (int i = 0;i < numberOfPolys;++i ) { vtkIdType *cell(0); vtkIdType cellSize(0); vpolys->GetNextCell( cellSize, cell ); float rgba[4] = {1.0f, 1.0f, 1.0f, 0}; if (scalarVisibility && vcellscalars) { if ( useCellData ) { // color each cell according to cell data double scalar = vcellscalars->GetComponent( i+numberOfLines, 0 ); double rgb[3] = { 1.0f, 1.0f, 1.0f }; m_ScalarsToColors->GetColor(scalar, rgb); rgba[0] = (float)rgb[0]; rgba[1] = (float)rgb[1]; rgba[2] = (float)rgb[2]; rgba[3] = (float)m_ScalarsToOpacity->GetValue(scalar); } else if ( usePointData ) { double scalar = vscalars->GetComponent( i, 0 ); double rgb[3] = { 1.0f, 1.0f, 1.0f }; m_ScalarsToColors->GetColor(scalar, rgb); rgba[0] = (float)rgb[0]; rgba[1] = (float)rgb[1]; rgba[2] = (float)rgb[2]; rgba[3] = (float)m_ScalarsToOpacity->GetValue(scalar); } } glColor4fv( rgba ); glBegin( GL_POLYGON ); for (int j = 0; j < cellSize; ++j) { vpoints->GetPoint( cell[ j ], vp ); //take transformation via vtktransform into account vtktransform->TransformPoint( vp, vp ); vtk2itk( vp, p ); //convert 3D point (in mm) to 2D point on slice (also in mm) worldGeometry->Map( p, p2d ); //convert point (until now mm and in worldcoordinates) to display coordinates (units ) displayGeometry->WorldToDisplay( p2d, p2d ); //convert display coordinates ( (0,0) is top-left ) in GL coordinates ( (0,0) is bottom-left ) //p2d[1]=toGL-p2d[1]; cachedPoints[i*10+j][0] = p2d[0]; cachedPoints[i*10+j][1] = p2d[1]; //add the current vertex to the line glVertex2f( p2d[0], p2d[1] ); } glEnd(); } if (polyOutline) { vpolys->InitTraversal(); glColor4f(outlineColor[0], outlineColor[1], outlineColor[2], 1.0f); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); for (int i = 0;i < numberOfPolys;++i) { vtkIdType *cell(0); vtkIdType cellSize(0); vpolys->GetNextCell( cellSize, cell ); glBegin( GL_POLYGON ); //glPolygonOffset(1.0, 1.0); for (int j = 0; j < cellSize; ++j) { //add the current vertex to the line glVertex2f( cachedPoints[i*10+j][0], cachedPoints[i*10+j][1] ); } glEnd(); } } } glDisable(GL_BLEND); delete cachedPoints; } vtkAbstractMapper3D* mitk::UnstructuredGridMapper2D ::GetVtkAbstractMapper3D(mitk::BaseRenderer * renderer) { //MITK_INFO << "GETVTKABSTRACTMAPPER3D\n"; mitk::DataNode::ConstPointer node = this->GetDataNode(); if ( node.IsNull() ) return 0; mitk::VtkMapper::Pointer mitkMapper = dynamic_cast< mitk::VtkMapper* > ( node->GetMapper( 2 ) ); if ( mitkMapper.IsNull() ) { return 0; } mitkMapper->Update(renderer); vtkAssembly* assembly = dynamic_cast(mitkMapper->GetVtkProp(renderer)); if (assembly) { vtkProp3DCollection* collection = assembly->GetParts(); collection->InitTraversal(); vtkProp3D* prop3d = 0; do { prop3d = collection->GetNextProp3D(); vtkActor* actor = dynamic_cast( prop3d ); if (actor) { return dynamic_cast( actor->GetMapper() ); } vtkVolume* volume = dynamic_cast( prop3d ); if (volume) { return dynamic_cast( volume->GetMapper() ); } } while (prop3d != collection->GetLastProp3D()); } else { vtkActor* actor = dynamic_cast( mitkMapper->GetVtkProp(renderer) ); if (actor) { return dynamic_cast( actor->GetMapper() ); } vtkVolume* volume = dynamic_cast( mitkMapper->GetVtkProp(renderer) ); if (volume) { return dynamic_cast( volume->GetMapper() ); } } return 0; } vtkPointSet* mitk::UnstructuredGridMapper2D -::GetVtkPointSet(mitk::BaseRenderer* renderer) +::GetVtkPointSet(mitk::BaseRenderer* renderer, int time) { //MITK_INFO << "GETVTKPOINTSET\n"; vtkAbstractMapper3D * abstractMapper = GetVtkAbstractMapper3D(renderer); if ( abstractMapper == 0 ) { // try to get data from the node mitk::DataNode::ConstPointer node = this->GetDataNode(); if ( node.IsNull() ) return 0; mitk::BaseData::Pointer data = node->GetData(); mitk::UnstructuredGrid::Pointer grid = dynamic_cast(data.GetPointer()); if (!grid.IsNull()) - return static_cast(grid->GetVtkUnstructuredGrid()); + return static_cast(grid->GetVtkUnstructuredGrid(time)); return 0; } else { vtkMapper* mapper = dynamic_cast(abstractMapper); if (mapper) { return dynamic_cast(mapper->GetInput()); } vtkAbstractVolumeMapper* volMapper = dynamic_cast(abstractMapper); if (volMapper) { return dynamic_cast(volMapper->GetDataSetInput()); } } return 0; } vtkScalarsToColors* mitk::UnstructuredGridMapper2D::GetVtkLUT(mitk::BaseRenderer* renderer) { //MITK_INFO << "GETVTKLUT\n"; vtkMapper * mapper = dynamic_cast(GetVtkAbstractMapper3D(renderer)); if (mapper) return mapper->GetLookupTable(); else { mitk::DataNode::ConstPointer node = this->GetDataNode(); if ( node.IsNull() ) return 0; mitk::VtkMapper::Pointer mitkMapper = dynamic_cast< mitk::VtkMapper* > ( node->GetMapper( 2 ) ); if ( mitkMapper.IsNull() ) { //MITK_INFO << "mitkMapper is null\n"; return 0; } mitkMapper->Update(renderer); vtkVolume* volume = dynamic_cast( mitkMapper->GetVtkProp(renderer) ); if (volume) { //MITK_INFO << "found volume prop\n"; return static_cast(volume->GetProperty()->GetRGBTransferFunction()); } vtkAssembly* assembly = dynamic_cast(mitkMapper->GetVtkProp(renderer)); if (assembly) { //MITK_INFO << "found assembly prop\n"; mitk::TransferFunctionProperty::Pointer transferFuncProp; node->GetProperty(transferFuncProp, "TransferFunction", 0); if (transferFuncProp.IsNotNull()) { MITK_INFO << "return colortransferfunction\n"; return static_cast(transferFuncProp->GetValue()->GetColorTransferFunction()); } } return 0; } } bool mitk::UnstructuredGridMapper2D::IsConvertibleToVtkPointSet(mitk::BaseRenderer * renderer) { - return ( GetVtkPointSet(renderer) != 0 ); + return ( GetVtkPointSet(renderer,this->GetTimestep()) != 0); } mitk::UnstructuredGridMapper2D::UnstructuredGridMapper2D() { m_Plane = vtkPlane::New(); m_Slicer = vtkPointSetSlicer::New(); m_Slicer->SetSlicePlane( m_Plane ); m_ScalarsToColors = 0; m_ScalarsToOpacity = 0; m_VtkPointSet = 0; //m_LUT = vtkLookupTable::New(); //m_LUT->SetTableRange( 0, 255 ); //m_LUT->SetNumberOfColors( 255 ); //m_LUT->SetRampToLinear (); //m_LUT->Build(); } mitk::UnstructuredGridMapper2D::~UnstructuredGridMapper2D() { m_Slicer->Delete(); m_Plane->Delete(); if (m_ScalarsToOpacity != 0) m_ScalarsToOpacity->UnRegister(0); if (m_ScalarsToColors != 0) m_ScalarsToColors->UnRegister(0); if (m_VtkPointSet != 0) m_VtkPointSet->UnRegister(0); } diff --git a/Modules/Overlays/mitkLogoOverlay.cpp b/Modules/Overlays/mitkLogoOverlay.cpp index 24eb89ecbf..869ea8da8f 100644 --- a/Modules/Overlays/mitkLogoOverlay.cpp +++ b/Modules/Overlays/mitkLogoOverlay.cpp @@ -1,196 +1,193 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkLogoOverlay.h" #include #include "vtkUnicodeString.h" #include #include #include #include #include #include #include #include #include #include -#include #include #include #include mitk::LogoOverlay::LogoOverlay() { m_readerFactory = vtkSmartPointer::New(); mitk::Point2D offset; offset.Fill(0.03); SetOffsetVector(offset); SetRelativeSize(0.2); - SetCornerPosition(4); + SetCornerPosition(3); m_VtkImageImport = vtkSmartPointer::New(); } mitk::LogoOverlay::~LogoOverlay() { } mitk::LogoOverlay::LocalStorage::~LocalStorage() { } mitk::LogoOverlay::LocalStorage::LocalStorage() { m_LogoRep = vtkSmartPointer::New(); - m_LogoWidget = vtkSmartPointer::New(); - m_LogoWidget->SetRepresentation(m_LogoRep); } void mitk::LogoOverlay::UpdateVtkOverlay(mitk::BaseRenderer *renderer) { LocalStorage* ls = this->m_LSH.GetLocalStorage(renderer); if(ls->IsGenerateDataRequired(renderer,this)) { vtkImageReader2* imageReader = m_readerFactory->CreateImageReader2(GetLogoImagePath().c_str()); if(imageReader) { imageReader->SetFileName(GetLogoImagePath().c_str()); imageReader->Update(); ls->m_LogoImage = imageReader->GetOutput(); imageReader->Delete(); } else { ls->m_LogoImage = CreateMbiLogo(); } ls->m_LogoRep->SetImage(ls->m_LogoImage); ls->m_LogoRep->SetDragable(false); ls->m_LogoRep->SetMoving(false); ls->m_LogoRep->SetPickable(false); ls->m_LogoRep->SetShowBorder(true); ls->m_LogoRep->SetRenderer(renderer->GetVtkRenderer()); float size = GetRelativeSize(renderer); ls->m_LogoRep->SetPosition2(size,size); int corner = GetCornerPosition(renderer); ls->m_LogoRep->SetCornerPosition(corner); mitk::Point2D offset = GetOffsetVector(renderer); ls->m_LogoRep->SetPosition(offset[0],offset[1]); float opacity = 1.0; GetOpacity(opacity,renderer); ls->m_LogoRep->GetImageProperty()->SetOpacity(opacity); ls->m_LogoRep->BuildRepresentation(); ls->UpdateGenerateDataTime(); } } vtkImageData *mitk::LogoOverlay::CreateMbiLogo() { m_VtkImageImport->SetDataScalarTypeToUnsignedChar(); m_VtkImageImport->SetNumberOfScalarComponents(mbiLogo_NumberOfScalars); m_VtkImageImport->SetWholeExtent(0,mbiLogo_Width-1,0,mbiLogo_Height-1,0,1-1); m_VtkImageImport->SetDataExtentToWholeExtent(); char * ImageData; // flip mbi logo around y axis and change color order ImageData = new char[mbiLogo_Height*mbiLogo_Width*mbiLogo_NumberOfScalars]; unsigned int column, row; char * dest = ImageData; char * source = (char*) &mbiLogo_Data[0];; char r, g, b, a; for (column = 0; column < mbiLogo_Height; column++) for (row = 0; row < mbiLogo_Width; row++) { //change r with b b = *source++; g = *source++; r = *source++; a = *source++; *dest++ = r; *dest++ = g; *dest++ = b; *dest++ = a; } m_VtkImageImport->SetImportVoidPointer(ImageData); m_VtkImageImport->Modified(); m_VtkImageImport->Update(); return m_VtkImageImport->GetOutput(); } void mitk::LogoOverlay::SetLogoImagePath(std::string path) { SetStringProperty("Overlay.LogoImagePath", path.c_str()); Modified(); } std::string mitk::LogoOverlay::GetLogoImagePath() const { std::string path; GetPropertyList()->GetStringProperty("Overlay.LogoImagePath", path); return path; } void mitk::LogoOverlay::SetOffsetVector(const Point2D& OffsetVector, mitk::BaseRenderer *renderer) { mitk::Point2dProperty::Pointer OffsetVectorProperty = mitk::Point2dProperty::New(OffsetVector); SetProperty("Overlay.OffsetVector", OffsetVectorProperty.GetPointer(),renderer); Modified(); } mitk::Point2D mitk::LogoOverlay::GetOffsetVector(mitk::BaseRenderer *renderer) const { mitk::Point2D OffsetVector; OffsetVector.Fill(0); GetPropertyValue("Overlay.OffsetVector", OffsetVector, renderer); return OffsetVector; } void mitk::LogoOverlay::SetCornerPosition(const int &corner, mitk::BaseRenderer *renderer) { SetIntProperty("Overlay.CornerPosition", corner, renderer); Modified(); } int mitk::LogoOverlay::GetCornerPosition(mitk::BaseRenderer *renderer) const { int corner = 0; GetIntProperty("Overlay.CornerPosition",corner,renderer); return corner; } void mitk::LogoOverlay::SetRelativeSize(const float &size, mitk::BaseRenderer *renderer) { SetFloatProperty("Overlay.RelativeSize", size, renderer); Modified(); } float mitk::LogoOverlay::GetRelativeSize(mitk::BaseRenderer *renderer) const { float size = 0; GetFloatProperty("Overlay.RelativeSize",size,renderer); return size; } vtkProp* mitk::LogoOverlay::GetVtkProp(BaseRenderer *renderer) const { LocalStorage* ls = this->m_LSH.GetLocalStorage(renderer); return ls->m_LogoRep; } diff --git a/Modules/Overlays/mitkLogoOverlay.h b/Modules/Overlays/mitkLogoOverlay.h index 4c591d67ba..aeafe22842 100644 --- a/Modules/Overlays/mitkLogoOverlay.h +++ b/Modules/Overlays/mitkLogoOverlay.h @@ -1,108 +1,107 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef LOGOOVERLAY_H #define LOGOOVERLAY_H #include #include #include #include "MitkOverlaysExports.h" class mitkVtkLogoRepresentation; -class vtkLogoWidget; class vtkImageData; class vtkImageReader2Factory; class vtkImageImport; namespace mitk { /** \brief Displays a logo on the renderwindow */ class MITKOVERLAYS_EXPORT LogoOverlay : public mitk::VtkOverlay { public: class LocalStorage : public mitk::Overlay::BaseLocalStorage { public: /** \brief Actor of a 2D render window. */ vtkSmartPointer m_LogoImage; vtkSmartPointer m_LogoRep; - vtkSmartPointer m_LogoWidget; /** \brief Timestamp of last update of stored data. */ itk::TimeStamp m_LastUpdateTime; /** \brief Default constructor of the local storage. */ LocalStorage(); /** \brief Default deconstructor of the local storage. */ ~LocalStorage(); }; mitkClassMacro(LogoOverlay, mitk::VtkOverlay); itkFactorylessNewMacro(Self) itkCloneMacro(Self) vtkSmartPointer m_readerFactory; void SetLogoImagePath(std::string text); std::string GetLogoImagePath() const; /** \brief The relative offset to the corner position */ void SetOffsetVector(const Point2D& OffsetVector, BaseRenderer* renderer = NULL); Point2D GetOffsetVector(mitk::BaseRenderer* renderer = NULL) const; /** \brief The corner where the logo is displayed. 0 = Bottom left 1 = Bottom right 2 = Top right - 3 = Top left*/ + 3 = Top left + 4 = Center*/ void SetCornerPosition(const int& corner, BaseRenderer* renderer = NULL); int GetCornerPosition(mitk::BaseRenderer* renderer = NULL) const; void SetRelativeSize(const float &size, BaseRenderer* renderer = NULL); float GetRelativeSize(mitk::BaseRenderer* renderer = NULL) const; protected: /** \brief The LocalStorageHandler holds all LocalStorages for the render windows. */ mutable mitk::LocalStorageHandler m_LSH; virtual vtkProp *GetVtkProp(BaseRenderer *renderer) const; void UpdateVtkOverlay(mitk::BaseRenderer *renderer); vtkImageData* CreateMbiLogo(); /** \brief explicit constructor which disallows implicit conversions */ explicit LogoOverlay(); /** \brief virtual destructor in order to derive from this class */ virtual ~LogoOverlay(); private: vtkSmartPointer m_VtkImageImport; /** \brief copy constructor */ LogoOverlay( const LogoOverlay &); /** \brief assignment operator */ LogoOverlay &operator=(const LogoOverlay &); }; } // namespace mitk #endif // LOGOOVERLAY_H diff --git a/Modules/Overlays/mitkVtkLogoRepresentation.cxx b/Modules/Overlays/mitkVtkLogoRepresentation.cxx index 105e4dd3ff..131142c62b 100644 --- a/Modules/Overlays/mitkVtkLogoRepresentation.cxx +++ b/Modules/Overlays/mitkVtkLogoRepresentation.cxx @@ -1,185 +1,200 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkVtkLogoRepresentation.h" #include "vtkCallbackCommand.h" #include "vtkObjectFactory.h" #include "vtkPoints.h" #include "vtkCellArray.h" #include "vtkPolyData.h" #include "vtkPolyDataMapper2D.h" #include "vtkProperty2D.h" #include "vtkActor2D.h" #include "vtkPolyData.h" #include "vtkTexture.h" #include "vtkPolyDataMapper2D.h" #include "vtkFloatArray.h" #include "vtkPointData.h" #include "vtkImageData.h" #include "vtkPropCollection.h" #include "vtkRenderer.h" #include "vtkWindow.h" vtkStandardNewMacro(mitkVtkLogoRepresentation); //---------------------------------------------------------------------- inline void mitkVtkLogoRepresentation::AdjustImageSize(double /*o*/[2], double borderSize[2], double imageSize[2]) { // Scale the image to fit with in the border. // Also update the origin so the image is centered. double r0 = borderSize[0]/imageSize[0]; double r1 = borderSize[1]/imageSize[1]; if ( r0 > r1 ) { imageSize[0] *= r1; imageSize[1] *= r1; } else { imageSize[0] *= r0; imageSize[1] *= r0; } } //------------------------------------------------------------------------- void mitkVtkLogoRepresentation::BuildRepresentation() { if ( this->GetMTime() > this->BuildTime || (this->Renderer && this->Renderer->GetVTKWindow() && this->Renderer->GetVTKWindow()->GetMTime() > this->BuildTime) ) { // Determine and adjust the size of the image if ( this->Image ) { double imageSize[2], borderSize[2], o[2]; imageSize[0] = 0.0; imageSize[1] = 0.0; //this->Image->Update(); if ( this->Image->GetDataDimension() == 2 ) { int dims[3]; this->Image->GetDimensions(dims); imageSize[0] = static_cast(dims[0]); imageSize[1] = static_cast(dims[1]); } int *p1 = this->PositionCoordinate-> GetComputedDisplayValue(this->Renderer); int *p2 = this->Position2Coordinate-> GetComputedDisplayValue(this->Renderer); borderSize[0] = p2[0]; borderSize[1] = p2[1]; o[0] = static_cast(p1[0]); o[1] = static_cast(p1[1]); // this preserves the image aspect ratio. The image is // centered around the center of the bordered ragion. this->AdjustImageSize(o,borderSize,imageSize); // Update the points this->Texture->SetInputData(this->Image); int* size = this->Renderer->GetSize(); switch(this->cornerPosition) { case 0: { this->TexturePoints->SetPoint(0, o[0],o[1],0.0); this->TexturePoints->SetPoint(1, o[0]+imageSize[0],o[1],0.0); this->TexturePoints->SetPoint(2, o[0]+imageSize[0],o[1]+imageSize[1],0.0); this->TexturePoints->SetPoint(3, o[0],o[1]+imageSize[1],0.0); break; } case 1: { o[0] = size[0]-o[0]; this->TexturePoints->SetPoint(0, o[0]-imageSize[0],o[1],0.0); this->TexturePoints->SetPoint(1, o[0],o[1],0.0); this->TexturePoints->SetPoint(2, o[0],o[1]+imageSize[1],0.0); this->TexturePoints->SetPoint(3, o[0]-imageSize[0],o[1]+imageSize[1],0.0); break; } case 2: { o[0] = size[0]-o[0]; o[1] = size[1]-o[1]; this->TexturePoints->SetPoint(0, o[0]-imageSize[0],o[1]-imageSize[1],0.0); this->TexturePoints->SetPoint(1, o[0],o[1]-imageSize[1],0.0); this->TexturePoints->SetPoint(2, o[0],o[1],0.0); this->TexturePoints->SetPoint(3, o[0]-imageSize[0],o[1],0.0); break; } case 3: { o[1] = size[1]-o[1]; this->TexturePoints->SetPoint(0, o[0],o[1]-imageSize[1],0.0); this->TexturePoints->SetPoint(1, o[0]+imageSize[0],o[1]-imageSize[1],0.0); this->TexturePoints->SetPoint(2, o[0]+imageSize[0],o[1],0.0); this->TexturePoints->SetPoint(3, o[0],o[1],0.0); break; } + case 4: + { + double ish[2]; + //ish = middle of the image + ish[0] = imageSize[0]/2.0; + ish[1] = imageSize[1]/2.0; + //o = middle of the window + o[0] = (size[0])/2.0; + o[1] = (size[1])/2.0; + this->TexturePoints->SetPoint(0, o[0]-ish[0],o[1]-ish[1],0.0); + this->TexturePoints->SetPoint(1, o[0]+ish[0],o[1]-ish[1],0.0); + this->TexturePoints->SetPoint(2, o[0]+ish[0],o[1]+ish[1],0.0); + this->TexturePoints->SetPoint(3, o[0]-ish[0],o[1]+ish[1],0.0); + break; + } default: { this->TexturePoints->SetPoint(0, o[0],o[1],0.0); this->TexturePoints->SetPoint(1, o[0]+imageSize[0],o[1],0.0); this->TexturePoints->SetPoint(2, o[0]+imageSize[0],o[1]+imageSize[1],0.0); this->TexturePoints->SetPoint(3, o[0],o[1]+imageSize[1],0.0); } } } } } mitkVtkLogoRepresentation::mitkVtkLogoRepresentation() : cornerPosition(0) { } mitkVtkLogoRepresentation::~mitkVtkLogoRepresentation() { } //------------------------------------------------------------------------- void mitkVtkLogoRepresentation::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); if ( this->Image ) { os << indent << "Image:\n"; this->Image->PrintSelf(os,indent.GetNextIndent()); } else { os << indent << "Image: (none)\n"; } if ( this->ImageProperty ) { os << indent << "Image Property:\n"; this->ImageProperty->PrintSelf(os,indent.GetNextIndent()); } else { os << indent << "Image Property: (none)\n"; } } diff --git a/Modules/QtWidgets/include/QmitkStdMultiWidget.h b/Modules/QtWidgets/include/QmitkStdMultiWidget.h index dd64bbe803..6763383df7 100644 --- a/Modules/QtWidgets/include/QmitkStdMultiWidget.h +++ b/Modules/QtWidgets/include/QmitkStdMultiWidget.h @@ -1,443 +1,445 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef QmitkStdMultiWidget_h #define QmitkStdMultiWidget_h #include "MitkQtWidgetsExports.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include class QHBoxLayout; class QVBoxLayout; class QGridLayout; class QSpacerItem; class QmitkLevelWindowWidget; class QmitkRenderWindow; namespace mitk { class RenderingManager; } /// \ingroup QmitkModule class MITKQTWIDGETS_EXPORT QmitkStdMultiWidget : public QWidget { Q_OBJECT public: QmitkStdMultiWidget(QWidget* parent = 0, Qt::WindowFlags f = 0, mitk::RenderingManager* renderingManager = 0, mitk::BaseRenderer::RenderingMode::Type renderingMode = mitk::BaseRenderer::RenderingMode::Standard, const QString& name = "stdmulti"); virtual ~QmitkStdMultiWidget(); mitk::SliceNavigationController* GetTimeNavigationController(); void RequestUpdate(); void ForceImmediateUpdate(); mitk::MouseModeSwitcher* GetMouseModeSwitcher(); QmitkRenderWindow* GetRenderWindow1() const; QmitkRenderWindow* GetRenderWindow2() const; QmitkRenderWindow* GetRenderWindow3() const; QmitkRenderWindow* GetRenderWindow4() const; const mitk::Point3D & GetLastLeftClickPosition() const; const mitk::Point3D GetCrossPosition() const; void EnablePositionTracking(); void DisablePositionTracking(); int GetLayout() const; mitk::SlicesRotator * GetSlicesRotator() const; mitk::SlicesSwiveller * GetSlicesSwiveller() const; bool GetGradientBackgroundFlag() const; /*! \brief Access node of widget plane 1 \return DataNode holding widget plane 1 */ mitk::DataNode::Pointer GetWidgetPlane1(); /*! \brief Access node of widget plane 2 \return DataNode holding widget plane 2 */ mitk::DataNode::Pointer GetWidgetPlane2(); /*! \brief Access node of widget plane 3 \return DataNode holding widget plane 3 */ mitk::DataNode::Pointer GetWidgetPlane3(); /*! \brief Convenience method to access node of widget planes \param id number of widget plane to be returned \return DataNode holding widget plane 3 */ mitk::DataNode::Pointer GetWidgetPlane(int id); bool IsColoredRectanglesEnabled() const; bool IsDepartmentLogoEnabled() const; bool IsCrosshairNavigationEnabled() const; void InitializeWidget(); /// called when the StdMultiWidget is closed to remove the 3 widget planes and the helper node from the DataStorage void RemovePlanesFromDataStorage(); void AddPlanesToDataStorage(); void SetDataStorage( mitk::DataStorage* ds ); /** \brief Listener to the CrosshairPositionEvent Ensures the CrosshairPositionEvent is handled only once and at the end of the Qt-Event loop */ void HandleCrosshairPositionEvent(); /// activate Menu Widget. true: activated, false: deactivated void ActivateMenuWidget( bool state ); bool IsMenuWidgetEnabled() const; + void SetCornerAnnotationVisibility(bool visibility); + protected: void UpdateAllWidgets(); void HideAllWidgetToolbars(); mitk::DataNode::Pointer GetTopLayerNode(mitk::DataStorage::SetOfObjects::ConstPointer nodes); public slots: /// Receives the signal from HandleCrosshairPositionEvent, executes the StatusBar update void HandleCrosshairPositionEventDelayed(); void changeLayoutTo2DImagesUp(); void changeLayoutTo2DImagesLeft(); void changeLayoutToDefault(); void changeLayoutToBig3D(); void changeLayoutToWidget1(); void changeLayoutToWidget2(); void changeLayoutToWidget3(); void changeLayoutToRowWidget3And4(); void changeLayoutToColumnWidget3And4(); void changeLayoutToRowWidgetSmall3andBig4(); void changeLayoutToSmallUpperWidget2Big3and4(); void changeLayoutTo2x2Dand3DWidget(); void changeLayoutToLeft2Dand3DRight2D(); void changeLayoutTo2DUpAnd3DDown(); void Fit(); void InitPositionTracking(); void AddDisplayPlaneSubTree(); void EnableStandardLevelWindow(); void DisableStandardLevelWindow(); bool InitializeStandardViews( const mitk::Geometry3D * geometry ); void wheelEvent( QWheelEvent * e ); void mousePressEvent(QMouseEvent * e); void moveEvent( QMoveEvent* e ); void leaveEvent ( QEvent * e ); void EnsureDisplayContainsPoint( mitk::DisplayGeometry* displayGeometry, const mitk::Point3D& p); void MoveCrossToPosition(const mitk::Point3D& newPosition); void EnableNavigationControllerEventListening(); void DisableNavigationControllerEventListening(); void EnableGradientBackground(); void DisableGradientBackground(); void EnableDepartmentLogo(); void DisableDepartmentLogo(); void EnableColoredRectangles(); void DisableColoredRectangles(); void SetWidgetPlaneVisibility(const char* widgetName, bool visible, mitk::BaseRenderer *renderer=NULL); void SetWidgetPlanesVisibility(bool visible, mitk::BaseRenderer *renderer=NULL); void SetWidgetPlanesLocked(bool locked); void SetWidgetPlanesRotationLocked(bool locked); void SetWidgetPlanesRotationLinked( bool link ); void SetWidgetPlaneMode( int mode ); void SetGradientBackgroundColors( const mitk::Color & upper, const mitk::Color & lower ); void SetDepartmentLogoPath( const char * path ); void SetWidgetPlaneModeToSlicing( bool activate ); void SetWidgetPlaneModeToRotation( bool activate ); void SetWidgetPlaneModeToSwivel( bool activate ); void OnLayoutDesignChanged( int layoutDesignIndex ); void ResetCrosshair(); void MouseModeSelected( mitk::MouseModeSwitcher::MouseMode mouseMode ); signals: void LeftMouseClicked(mitk::Point3D pointValue); void WheelMoved(QWheelEvent*); void WidgetPlanesRotationLinked(bool); void WidgetPlanesRotationEnabled(bool); void ViewsInitialized(); void WidgetPlaneModeSlicing(bool); void WidgetPlaneModeRotation(bool); void WidgetPlaneModeSwivel(bool); void WidgetPlaneModeChange(int); void WidgetNotifyNewCrossHairMode(int); void Moved(); public: /** Define RenderWindow (public)*/ QmitkRenderWindow* mitkWidget1; QmitkRenderWindow* mitkWidget2; QmitkRenderWindow* mitkWidget3; QmitkRenderWindow* mitkWidget4; QmitkLevelWindowWidget* levelWindowWidget; /********************************/ enum { PLANE_MODE_SLICING = 0, PLANE_MODE_ROTATION, PLANE_MODE_SWIVEL }; enum { LAYOUT_DEFAULT = 0, LAYOUT_2D_IMAGES_UP, LAYOUT_2D_IMAGES_LEFT, LAYOUT_BIG_3D, LAYOUT_WIDGET1, LAYOUT_WIDGET2, LAYOUT_WIDGET3, LAYOUT_2X_2D_AND_3D_WIDGET, LAYOUT_ROW_WIDGET_3_AND_4, LAYOUT_COLUMN_WIDGET_3_AND_4, LAYOUT_ROW_WIDGET_SMALL3_AND_BIG4 , LAYOUT_SMALL_UPPER_WIDGET2_BIG3_AND4,LAYOUT_2D_AND_3D_LEFT_2D_RIGHT_WIDGET, LAYOUT_2D_UP_AND_3D_DOWN}; enum { AXIAL, SAGITTAL, CORONAL, THREE_D }; /** * @brief SetCornerAnnotation Create a corner annotation for a widget. * @param text The text of the annotation. * @param color The color. * @param widgetNumber The widget (0-3). */ void SetCornerAnnotation(std::string text, mitk::Color color, int widgetNumber); /** * @brief GetRenderWindow convinience method to get a widget. * @param number of the widget (0-3) * @return The renderwindow widget. */ QmitkRenderWindow *GetRenderWindow(unsigned int number); /** * @brief SetGradientBackgroundColorForRenderWindow background for a widget. * * If two different input colors are, a gradient background is generated. * * @param upper Upper color of the gradient background. * @param lower Lower color of the gradient background. * @param widgetNumber The widget (0-3). */ void SetGradientBackgroundColorForRenderWindow(const mitk::Color &upper, const mitk::Color &lower, unsigned int widgetNumber); /** * @brief GetDecorationColorForWidget Get the color for annotation, crosshair and rectangle. * @param widgetNumber Number of the renderwindow (0-3). * @return Color in mitk format. */ mitk::Color GetDecorationColor(unsigned int widgetNumber); /** * @brief SetDecorationColor Set the color of the decoration of the 4 widgets. * * This is used to color the frame of the renderwindow and the corner annatation. * For the first 3 widgets, this color is a property of the helper object nodes * which contain the respective plane geometry. For widget 4, this is a member, * since there is no data node for this widget. */ void SetDecorationColor(unsigned int widgetNumber, mitk::Color color); /** * @brief GetCornerAnnotationText Getter for corner annotation text. * @param widgetNumber the widget number (0-3). * @return The text in the corner annotation. */ std::string GetCornerAnnotationText(unsigned int widgetNumber); /** * @brief GetGradientColors Getter for gradientbackground colors. * @param widgetNumber the widget number (0-3). * @return A pair of colors. First: upper, second: lower. */ std::pair GetGradientColors(unsigned int widgetNumber); protected: QHBoxLayout* QmitkStdMultiWidgetLayout; int m_Layout; int m_PlaneMode; mitk::RenderingManager* m_RenderingManager; /** * @brief m_RectangleRendering1 the 4 frames of the renderwindow. */ mitk::RenderWindowFrame::Pointer m_RectangleRendering[4]; mitk::LogoOverlay::Pointer m_LogoRendering; mitk::GradientBackground::Pointer m_GradientBackground[4]; bool m_GradientBackgroundFlag; mitk::MouseModeSwitcher::Pointer m_MouseModeSwitcher; mitk::CoordinateSupplier::Pointer m_LastLeftClickPositionSupplier; mitk::PositionTracker::Pointer m_PositionTracker; mitk::SliceNavigationController* m_TimeNavigationController; mitk::SlicesRotator::Pointer m_SlicesRotator; mitk::SlicesSwiveller::Pointer m_SlicesSwiveller; mitk::DataNode::Pointer m_PositionTrackerNode; mitk::DataStorage::Pointer m_DataStorage; /** * @brief m_PlaneNode1 the 3 helper objects which contain the plane geometry. */ mitk::DataNode::Pointer m_PlaneNode1; mitk::DataNode::Pointer m_PlaneNode2; mitk::DataNode::Pointer m_PlaneNode3; /** * @brief m_ParentNodeForGeometryPlanes This helper object is added to the datastorage * and contains the 3 planes for displaying the image geometry (crosshair and 3D planes). */ mitk::DataNode::Pointer m_ParentNodeForGeometryPlanes; /** * @brief m_DecorationColorWidget4 color for annotation and rectangle of widget 4. * * For other widgets1-3, the color is a property of the respective data node. * There is no node for widget 4, hence, we need an extra member. */ mitk::Color m_DecorationColorWidget4; /** * @brief m_GradientBackgroundColors Contains the colors of the gradient background. * */ std::pair m_GradientBackgroundColors[4]; QSplitter *m_MainSplit; QSplitter *m_LayoutSplit; QSplitter *m_SubSplit1; QSplitter *m_SubSplit2; QWidget *mitkWidget1Container; QWidget *mitkWidget2Container; QWidget *mitkWidget3Container; QWidget *mitkWidget4Container; /** * @brief The CornerAnnotation struct to hold the 4 corner annotations. */ struct CornerAnnotation { vtkSmartPointer cornerText; vtkSmartPointer textProp; vtkSmartPointer ren; } m_CornerAnnotations[4]; bool m_PendingCrosshairPositionEvent; bool m_CrosshairNavigationEnabled; /** * @brief CreateCornerAnnotation helper method to create a corner annotation. * @param text of the annotation. * @param color of the annotation. * @return the complete struct. */ CornerAnnotation CreateCornerAnnotation(std::string text, mitk::Color color); /** * @brief FillGradientBackgroundWithBlack Internal helper method to initialize the * gradient background colors with black. */ void FillGradientBackgroundWithBlack(); }; #endif /*QmitkStdMultiWidget_h*/ diff --git a/Modules/QtWidgets/src/QmitkStdMultiWidget.cpp b/Modules/QtWidgets/src/QmitkStdMultiWidget.cpp index 470344fce3..f1ba3aa589 100644 --- a/Modules/QtWidgets/src/QmitkStdMultiWidget.cpp +++ b/Modules/QtWidgets/src/QmitkStdMultiWidget.cpp @@ -1,2284 +1,2293 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #define SMW_INFO MITK_INFO("widget.stdmulti") #include "QmitkStdMultiWidget.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include QmitkStdMultiWidget::QmitkStdMultiWidget(QWidget* parent, Qt::WindowFlags f, mitk::RenderingManager* renderingManager, mitk::BaseRenderer::RenderingMode::Type renderingMode, const QString& name) : QWidget(parent, f), mitkWidget1(NULL), mitkWidget2(NULL), mitkWidget3(NULL), mitkWidget4(NULL), levelWindowWidget(NULL), QmitkStdMultiWidgetLayout(NULL), m_Layout(LAYOUT_DEFAULT), m_PlaneMode(PLANE_MODE_SLICING), m_RenderingManager(renderingManager), m_GradientBackgroundFlag(true), m_TimeNavigationController(NULL), m_MainSplit(NULL), m_LayoutSplit(NULL), m_SubSplit1(NULL), m_SubSplit2(NULL), mitkWidget1Container(NULL), mitkWidget2Container(NULL), mitkWidget3Container(NULL), mitkWidget4Container(NULL), m_PendingCrosshairPositionEvent(false), m_CrosshairNavigationEnabled(false) { /****************************************************** * Use the global RenderingManager if none was specified * ****************************************************/ if (m_RenderingManager == NULL) { m_RenderingManager = mitk::RenderingManager::GetInstance(); } m_TimeNavigationController = m_RenderingManager->GetTimeNavigationController(); /*******************************/ //Create Widget manually /*******************************/ //create Layouts QmitkStdMultiWidgetLayout = new QHBoxLayout( this ); QmitkStdMultiWidgetLayout->setContentsMargins(0,0,0,0); //Set Layout to widget this->setLayout(QmitkStdMultiWidgetLayout); //create main splitter m_MainSplit = new QSplitter( this ); QmitkStdMultiWidgetLayout->addWidget( m_MainSplit ); //create m_LayoutSplit and add to the mainSplit m_LayoutSplit = new QSplitter( Qt::Vertical, m_MainSplit ); m_MainSplit->addWidget( m_LayoutSplit ); //create m_SubSplit1 and m_SubSplit2 m_SubSplit1 = new QSplitter( m_LayoutSplit ); m_SubSplit2 = new QSplitter( m_LayoutSplit ); //creae Widget Container mitkWidget1Container = new QWidget(m_SubSplit1); mitkWidget2Container = new QWidget(m_SubSplit1); mitkWidget3Container = new QWidget(m_SubSplit2); mitkWidget4Container = new QWidget(m_SubSplit2); mitkWidget1Container->setContentsMargins(0,0,0,0); mitkWidget2Container->setContentsMargins(0,0,0,0); mitkWidget3Container->setContentsMargins(0,0,0,0); mitkWidget4Container->setContentsMargins(0,0,0,0); //create Widget Layout QHBoxLayout *mitkWidgetLayout1 = new QHBoxLayout(mitkWidget1Container); QHBoxLayout *mitkWidgetLayout2 = new QHBoxLayout(mitkWidget2Container); QHBoxLayout *mitkWidgetLayout3 = new QHBoxLayout(mitkWidget3Container); QHBoxLayout *mitkWidgetLayout4 = new QHBoxLayout(mitkWidget4Container); mitkWidgetLayout1->setMargin(0); mitkWidgetLayout2->setMargin(0); mitkWidgetLayout3->setMargin(0); mitkWidgetLayout4->setMargin(0); //set Layout to Widget Container mitkWidget1Container->setLayout(mitkWidgetLayout1); mitkWidget2Container->setLayout(mitkWidgetLayout2); mitkWidget3Container->setLayout(mitkWidgetLayout3); mitkWidget4Container->setLayout(mitkWidgetLayout4); //set SizePolicy mitkWidget1Container->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding); mitkWidget2Container->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding); mitkWidget3Container->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding); mitkWidget4Container->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding); //insert Widget Container into the splitters m_SubSplit1->addWidget( mitkWidget1Container ); m_SubSplit1->addWidget( mitkWidget2Container ); m_SubSplit2->addWidget( mitkWidget3Container ); m_SubSplit2->addWidget( mitkWidget4Container ); // m_RenderingManager->SetGlobalInteraction( mitk::GlobalInteraction::GetInstance() ); //Create RenderWindows 1 mitkWidget1 = new QmitkRenderWindow(mitkWidget1Container, name + ".widget1", NULL, m_RenderingManager,renderingMode); mitkWidget1->setMaximumSize(2000,2000); mitkWidget1->SetLayoutIndex( AXIAL ); mitkWidgetLayout1->addWidget(mitkWidget1); //Create RenderWindows 2 mitkWidget2 = new QmitkRenderWindow(mitkWidget2Container, name + ".widget2", NULL, m_RenderingManager,renderingMode); mitkWidget2->setMaximumSize(2000,2000); mitkWidget2->setEnabled( true ); mitkWidget2->SetLayoutIndex( SAGITTAL ); mitkWidgetLayout2->addWidget(mitkWidget2); //Create RenderWindows 3 mitkWidget3 = new QmitkRenderWindow(mitkWidget3Container, name + ".widget3", NULL, m_RenderingManager,renderingMode); mitkWidget3->setMaximumSize(2000,2000); mitkWidget3->SetLayoutIndex( CORONAL ); mitkWidgetLayout3->addWidget(mitkWidget3); //Create RenderWindows 4 mitkWidget4 = new QmitkRenderWindow(mitkWidget4Container, name + ".widget4", NULL, m_RenderingManager,renderingMode); mitkWidget4->setMaximumSize(2000,2000); mitkWidget4->SetLayoutIndex( THREE_D ); mitkWidgetLayout4->addWidget(mitkWidget4); //create SignalSlot Connection connect( mitkWidget1, SIGNAL( SignalLayoutDesignChanged(int) ), this, SLOT( OnLayoutDesignChanged(int) ) ); connect( mitkWidget1, SIGNAL( ResetView() ), this, SLOT( ResetCrosshair() ) ); connect( mitkWidget1, SIGNAL( ChangeCrosshairRotationMode(int) ), this, SLOT( SetWidgetPlaneMode(int) ) ); connect( this, SIGNAL(WidgetNotifyNewCrossHairMode(int)), mitkWidget1, SLOT(OnWidgetPlaneModeChanged(int)) ); connect( mitkWidget2, SIGNAL( SignalLayoutDesignChanged(int) ), this, SLOT( OnLayoutDesignChanged(int) ) ); connect( mitkWidget2, SIGNAL( ResetView() ), this, SLOT( ResetCrosshair() ) ); connect( mitkWidget2, SIGNAL( ChangeCrosshairRotationMode(int) ), this, SLOT( SetWidgetPlaneMode(int) ) ); connect( this, SIGNAL(WidgetNotifyNewCrossHairMode(int)), mitkWidget2, SLOT(OnWidgetPlaneModeChanged(int)) ); connect( mitkWidget3, SIGNAL( SignalLayoutDesignChanged(int) ), this, SLOT( OnLayoutDesignChanged(int) ) ); connect( mitkWidget3, SIGNAL( ResetView() ), this, SLOT( ResetCrosshair() ) ); connect( mitkWidget3, SIGNAL( ChangeCrosshairRotationMode(int) ), this, SLOT( SetWidgetPlaneMode(int) ) ); connect( this, SIGNAL(WidgetNotifyNewCrossHairMode(int)), mitkWidget3, SLOT(OnWidgetPlaneModeChanged(int)) ); connect( mitkWidget4, SIGNAL( SignalLayoutDesignChanged(int) ), this, SLOT( OnLayoutDesignChanged(int) ) ); connect( mitkWidget4, SIGNAL( ResetView() ), this, SLOT( ResetCrosshair() ) ); connect( mitkWidget4, SIGNAL( ChangeCrosshairRotationMode(int) ), this, SLOT( SetWidgetPlaneMode(int) ) ); connect( this, SIGNAL(WidgetNotifyNewCrossHairMode(int)), mitkWidget4, SLOT(OnWidgetPlaneModeChanged(int)) ); //Create Level Window Widget levelWindowWidget = new QmitkLevelWindowWidget( m_MainSplit ); //this levelWindowWidget->setObjectName(QString::fromUtf8("levelWindowWidget")); QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); sizePolicy.setHorizontalStretch(0); sizePolicy.setVerticalStretch(0); sizePolicy.setHeightForWidth(levelWindowWidget->sizePolicy().hasHeightForWidth()); levelWindowWidget->setSizePolicy(sizePolicy); levelWindowWidget->setMaximumSize(QSize(50, 2000)); //add LevelWindow Widget to mainSplitter m_MainSplit->addWidget( levelWindowWidget ); //show mainSplitt and add to Layout m_MainSplit->show(); //resize Image. this->resize( QSize(364, 477).expandedTo(minimumSizeHint()) ); //Initialize the widgets. this->InitializeWidget(); //Activate Widget Menu this->ActivateMenuWidget( true ); } void QmitkStdMultiWidget::InitializeWidget() { m_PositionTracker = NULL; //Make all black and overwrite renderwindow 4 this->FillGradientBackgroundWithBlack(); //This is #191919 in hex float tmp1[3] = { 0.098f, 0.098f, 0.098f}; //This is #7F7F7F in hex float tmp2[3] = { 0.498f, 0.498f, 0.498f}; m_GradientBackgroundColors[3] = std::make_pair(mitk::Color(tmp1), mitk::Color(tmp2)); //Yellow is default color for widget4 m_DecorationColorWidget4[0] = 1.0f; m_DecorationColorWidget4[1] = 1.0f; m_DecorationColorWidget4[2] = 0.0f; // transfer colors in WorldGeometry-Nodes of the associated Renderer mitk::IntProperty::Pointer layer; // of widget 1 m_PlaneNode1 = mitk::BaseRenderer::GetInstance(mitkWidget1->GetRenderWindow())->GetCurrentWorldPlaneGeometryNode(); m_PlaneNode1->SetColor(GetDecorationColor(0)); layer = mitk::IntProperty::New(1000); m_PlaneNode1->SetProperty("layer",layer); // ... of widget 2 m_PlaneNode2 = mitk::BaseRenderer::GetInstance(mitkWidget2->GetRenderWindow())->GetCurrentWorldPlaneGeometryNode(); m_PlaneNode2->SetColor(GetDecorationColor(1)); layer = mitk::IntProperty::New(1000); m_PlaneNode2->SetProperty("layer",layer); // ... of widget 3 m_PlaneNode3 = mitk::BaseRenderer::GetInstance(mitkWidget3->GetRenderWindow())->GetCurrentWorldPlaneGeometryNode(); m_PlaneNode3->SetColor(GetDecorationColor(2)); layer = mitk::IntProperty::New(1000); m_PlaneNode3->SetProperty("layer",layer); //The parent node m_ParentNodeForGeometryPlanes = mitk::BaseRenderer::GetInstance(mitkWidget4->GetRenderWindow())->GetCurrentWorldPlaneGeometryNode(); layer = mitk::IntProperty::New(1000); m_ParentNodeForGeometryPlanes->SetProperty("layer",layer); mitk::OverlayManager::Pointer OverlayManager = mitk::OverlayManager::New(); mitk::BaseRenderer::GetInstance(mitkWidget1->GetRenderWindow())->SetOverlayManager(OverlayManager); mitk::BaseRenderer::GetInstance(mitkWidget2->GetRenderWindow())->SetOverlayManager(OverlayManager); mitk::BaseRenderer::GetInstance(mitkWidget3->GetRenderWindow())->SetOverlayManager(OverlayManager); mitk::BaseRenderer::GetInstance(mitkWidget4->GetRenderWindow())->SetOverlayManager(OverlayManager); mitk::BaseRenderer::GetInstance(mitkWidget4->GetRenderWindow())->SetMapperID(mitk::BaseRenderer::Standard3D); // Set plane mode (slicing/rotation behavior) to slicing (default) m_PlaneMode = PLANE_MODE_SLICING; // Set default view directions for SNCs mitkWidget1->GetSliceNavigationController()->SetDefaultViewDirection( mitk::SliceNavigationController::Axial ); mitkWidget2->GetSliceNavigationController()->SetDefaultViewDirection( mitk::SliceNavigationController::Sagittal ); mitkWidget3->GetSliceNavigationController()->SetDefaultViewDirection( mitk::SliceNavigationController::Frontal ); mitkWidget4->GetSliceNavigationController()->SetDefaultViewDirection( mitk::SliceNavigationController::Original ); SetCornerAnnotation("Axial", GetDecorationColor(0), 0); SetCornerAnnotation("Sagittal", GetDecorationColor(1), 1); SetCornerAnnotation("Coronal", GetDecorationColor(2), 2); SetCornerAnnotation("3D", GetDecorationColor(3), 3); // create a slice rotator m_SlicesRotator = mitk::SlicesRotator::New("slices-rotator"); m_SlicesRotator->AddSliceController( mitkWidget1->GetSliceNavigationController() ); m_SlicesRotator->AddSliceController( mitkWidget2->GetSliceNavigationController() ); m_SlicesRotator->AddSliceController( mitkWidget3->GetSliceNavigationController() ); // create a slice swiveller (using the same state-machine as SlicesRotator) m_SlicesSwiveller = mitk::SlicesSwiveller::New("slices-rotator"); m_SlicesSwiveller->AddSliceController( mitkWidget1->GetSliceNavigationController() ); m_SlicesSwiveller->AddSliceController( mitkWidget2->GetSliceNavigationController() ); m_SlicesSwiveller->AddSliceController( mitkWidget3->GetSliceNavigationController() ); //connect to the "time navigation controller": send time via sliceNavigationControllers m_TimeNavigationController->ConnectGeometryTimeEvent( mitkWidget1->GetSliceNavigationController() , false); m_TimeNavigationController->ConnectGeometryTimeEvent( mitkWidget2->GetSliceNavigationController() , false); m_TimeNavigationController->ConnectGeometryTimeEvent( mitkWidget3->GetSliceNavigationController() , false); m_TimeNavigationController->ConnectGeometryTimeEvent( mitkWidget4->GetSliceNavigationController() , false); mitkWidget1->GetSliceNavigationController() ->ConnectGeometrySendEvent(mitk::BaseRenderer::GetInstance(mitkWidget4->GetRenderWindow())); //reverse connection between sliceNavigationControllers and m_TimeNavigationController mitkWidget1->GetSliceNavigationController() ->ConnectGeometryTimeEvent(m_TimeNavigationController, false); mitkWidget2->GetSliceNavigationController() ->ConnectGeometryTimeEvent(m_TimeNavigationController, false); mitkWidget3->GetSliceNavigationController() ->ConnectGeometryTimeEvent(m_TimeNavigationController, false); mitkWidget4->GetSliceNavigationController() ->ConnectGeometryTimeEvent(m_TimeNavigationController, false); m_MouseModeSwitcher = mitk::MouseModeSwitcher::New(); m_LastLeftClickPositionSupplier = mitk::CoordinateSupplier::New("navigation", NULL); mitk::GlobalInteraction::GetInstance()->AddListener( m_LastLeftClickPositionSupplier ); // setup the department logo rendering m_LogoRendering = mitk::LogoOverlay::New(); mitk::BaseRenderer::Pointer renderer4 = mitk::BaseRenderer::GetInstance(mitkWidget4->GetRenderWindow()); m_LogoRendering->SetOpacity(0.5); mitk::Point2D offset; offset.Fill(0.03); m_LogoRendering->SetOffsetVector(offset); m_LogoRendering->SetRelativeSize(0.15); m_LogoRendering->SetCornerPosition(1); renderer4->GetOverlayManager()->AddOverlay(m_LogoRendering.GetPointer(),renderer4); // setup gradient background and renderwindow rectangle frame for(unsigned int i = 0; i < 4; ++i) { m_GradientBackground[i] = mitk::GradientBackground::New(); m_GradientBackground[i]->SetRenderWindow(GetRenderWindow(i)->GetVtkRenderWindow()); m_GradientBackground[i]->Enable(); m_RectangleRendering[i] = mitk::RenderWindowFrame::New(); m_RectangleRendering[i]->SetRenderWindow(GetRenderWindow(i)->GetVtkRenderWindow()); m_RectangleRendering[i]->Enable(GetDecorationColor(i)[0], GetDecorationColor(i)[1], GetDecorationColor(i)[2]); } } void QmitkStdMultiWidget::FillGradientBackgroundWithBlack() { //We have 4 widgets and ... for(unsigned int i = 0; i < 4; ++i) { float black[3] = {0.0f, 0.0f, 0.0f}; m_GradientBackgroundColors[i] = std::make_pair(mitk::Color(black), mitk::Color(black)); } } std::pair QmitkStdMultiWidget::GetGradientColors(unsigned int widgetNumber) { if(widgetNumber > 3) { MITK_ERROR << "Decoration color for unknown widget!"; float black[3] = { 0.0f, 0.0f, 0.0f}; return std::make_pair(mitk::Color(black), mitk::Color(black)); } return m_GradientBackgroundColors[widgetNumber]; } mitk::Color QmitkStdMultiWidget::GetDecorationColor(unsigned int widgetNumber) { //The implementation looks a bit messy here, but it avoids //synchronization of the color of the geometry nodes and an //internal member here. //Default colors were chosen for decent visibitliy. //Feel free to change your preferences in the workbench. float tmp[3] = {0.0f,0.0f,0.0f}; switch (widgetNumber) { case 0: { if(m_PlaneNode1.IsNotNull()) { if(m_PlaneNode1->GetColor(tmp)) { return dynamic_cast( m_PlaneNode1->GetProperty("color"))->GetColor(); } } float red[3] = { 0.753f, 0.0f, 0.0f};//This is #C00000 in hex return mitk::Color(red); } case 1: { if(m_PlaneNode2.IsNotNull()) { if(m_PlaneNode2->GetColor(tmp)) { return dynamic_cast( m_PlaneNode2->GetProperty("color"))->GetColor(); } } float green[3] = { 0.0f, 0.69f, 0.0f};//This is #00B000 in hex return mitk::Color(green); } case 2: { if(m_PlaneNode3.IsNotNull()) { if(m_PlaneNode3->GetColor(tmp)) { return dynamic_cast( m_PlaneNode3->GetProperty("color"))->GetColor(); } } float blue[3] = { 0.0, 0.502f, 1.0f};//This is #0080FF in hex return mitk::Color(blue); } case 3: { return m_DecorationColorWidget4; } default: MITK_ERROR << "Decoration color for unknown widget!"; float black[3] = { 0.0f, 0.0f, 0.0f}; return mitk::Color(black); } } std::string QmitkStdMultiWidget::GetCornerAnnotationText(unsigned int widgetNumber) { if(widgetNumber > 3) { MITK_ERROR << "Decoration color for unknown widget!"; return std::string(""); } return std::string(m_CornerAnnotations[widgetNumber].cornerText->GetText(0)); } QmitkStdMultiWidget::~QmitkStdMultiWidget() { DisablePositionTracking(); DisableNavigationControllerEventListening(); m_TimeNavigationController->Disconnect(mitkWidget1->GetSliceNavigationController()); m_TimeNavigationController->Disconnect(mitkWidget2->GetSliceNavigationController()); m_TimeNavigationController->Disconnect(mitkWidget3->GetSliceNavigationController()); m_TimeNavigationController->Disconnect(mitkWidget4->GetSliceNavigationController()); } QmitkStdMultiWidget::CornerAnnotation QmitkStdMultiWidget::CreateCornerAnnotation(std::string text, mitk::Color color) { CornerAnnotation annotation; annotation.cornerText = vtkSmartPointer::New(); annotation.cornerText->SetText(0, text.c_str()); annotation.cornerText->SetMaximumFontSize(12); annotation.textProp = vtkSmartPointer::New(); annotation.textProp->SetColor( color[0],color[1],color[2] ); annotation.cornerText->SetTextProperty( annotation.textProp ); annotation.ren = vtkSmartPointer::New(); annotation.ren->AddActor(annotation.cornerText); annotation.ren->InteractiveOff(); return annotation; } void QmitkStdMultiWidget::RemovePlanesFromDataStorage() { if (m_PlaneNode1.IsNotNull() && m_PlaneNode2.IsNotNull() && m_PlaneNode3.IsNotNull() && m_ParentNodeForGeometryPlanes.IsNotNull()) { if(m_DataStorage.IsNotNull()) { m_DataStorage->Remove(m_PlaneNode1); m_DataStorage->Remove(m_PlaneNode2); m_DataStorage->Remove(m_PlaneNode3); m_DataStorage->Remove(m_ParentNodeForGeometryPlanes); } } } void QmitkStdMultiWidget::AddPlanesToDataStorage() { if (m_PlaneNode1.IsNotNull() && m_PlaneNode2.IsNotNull() && m_PlaneNode3.IsNotNull() && m_ParentNodeForGeometryPlanes.IsNotNull()) { if (m_DataStorage.IsNotNull()) { m_DataStorage->Add(m_ParentNodeForGeometryPlanes); m_DataStorage->Add(m_PlaneNode1, m_ParentNodeForGeometryPlanes); m_DataStorage->Add(m_PlaneNode2, m_ParentNodeForGeometryPlanes); m_DataStorage->Add(m_PlaneNode3, m_ParentNodeForGeometryPlanes); } } } void QmitkStdMultiWidget::changeLayoutTo2DImagesUp() { SMW_INFO << "changing layout to 2D images up... " << std::endl; //Hide all Menu Widgets this->HideAllWidgetToolbars(); delete QmitkStdMultiWidgetLayout ; //create Main Layout QmitkStdMultiWidgetLayout = new QHBoxLayout( this ); //Set Layout to widget this->setLayout(QmitkStdMultiWidgetLayout); //create main splitter m_MainSplit = new QSplitter( this ); QmitkStdMultiWidgetLayout->addWidget( m_MainSplit ); //create m_LayoutSplit and add to the mainSplit m_LayoutSplit = new QSplitter( Qt::Vertical, m_MainSplit ); m_MainSplit->addWidget( m_LayoutSplit ); //add LevelWindow Widget to mainSplitter m_MainSplit->addWidget( levelWindowWidget ); //create m_SubSplit1 and m_SubSplit2 m_SubSplit1 = new QSplitter( m_LayoutSplit ); m_SubSplit2 = new QSplitter( m_LayoutSplit ); //insert Widget Container into splitter top m_SubSplit1->addWidget( mitkWidget1Container ); m_SubSplit1->addWidget( mitkWidget2Container ); m_SubSplit1->addWidget( mitkWidget3Container ); //set SplitterSize for splitter top QList splitterSize; splitterSize.push_back(1000); splitterSize.push_back(1000); splitterSize.push_back(1000); m_SubSplit1->setSizes( splitterSize ); //insert Widget Container into splitter bottom m_SubSplit2->addWidget( mitkWidget4Container ); //set SplitterSize for splitter m_LayoutSplit splitterSize.clear(); splitterSize.push_back(400); splitterSize.push_back(1000); m_LayoutSplit->setSizes( splitterSize ); //show mainSplitt m_MainSplit->show(); //show Widget if hidden if ( mitkWidget1->isHidden() ) mitkWidget1->show(); if ( mitkWidget2->isHidden() ) mitkWidget2->show(); if ( mitkWidget3->isHidden() ) mitkWidget3->show(); if ( mitkWidget4->isHidden() ) mitkWidget4->show(); //Change Layout Name m_Layout = LAYOUT_2D_IMAGES_UP; //update Layout Design List mitkWidget1->LayoutDesignListChanged( LAYOUT_2D_IMAGES_UP ); mitkWidget2->LayoutDesignListChanged( LAYOUT_2D_IMAGES_UP ); mitkWidget3->LayoutDesignListChanged( LAYOUT_2D_IMAGES_UP ); mitkWidget4->LayoutDesignListChanged( LAYOUT_2D_IMAGES_UP ); //update Alle Widgets this->UpdateAllWidgets(); } void QmitkStdMultiWidget::changeLayoutTo2DImagesLeft() { SMW_INFO << "changing layout to 2D images left... " << std::endl; //Hide all Menu Widgets this->HideAllWidgetToolbars(); delete QmitkStdMultiWidgetLayout ; //create Main Layout QmitkStdMultiWidgetLayout = new QHBoxLayout( this ); //create main splitter m_MainSplit = new QSplitter( this ); QmitkStdMultiWidgetLayout->addWidget( m_MainSplit ); //create m_LayoutSplit and add to the mainSplit m_LayoutSplit = new QSplitter( m_MainSplit ); m_MainSplit->addWidget( m_LayoutSplit ); //add LevelWindow Widget to mainSplitter m_MainSplit->addWidget( levelWindowWidget ); //create m_SubSplit1 and m_SubSplit2 m_SubSplit1 = new QSplitter( Qt::Vertical, m_LayoutSplit ); m_SubSplit2 = new QSplitter( m_LayoutSplit ); //insert Widget into the splitters m_SubSplit1->addWidget( mitkWidget1Container ); m_SubSplit1->addWidget( mitkWidget2Container ); m_SubSplit1->addWidget( mitkWidget3Container ); //set splitterSize of SubSplit1 QList splitterSize; splitterSize.push_back(1000); splitterSize.push_back(1000); splitterSize.push_back(1000); m_SubSplit1->setSizes( splitterSize ); m_SubSplit2->addWidget( mitkWidget4Container ); //set splitterSize of Layout Split splitterSize.clear(); splitterSize.push_back(400); splitterSize.push_back(1000); m_LayoutSplit->setSizes( splitterSize ); //show mainSplitt and add to Layout m_MainSplit->show(); //show Widget if hidden if ( mitkWidget1->isHidden() ) mitkWidget1->show(); if ( mitkWidget2->isHidden() ) mitkWidget2->show(); if ( mitkWidget3->isHidden() ) mitkWidget3->show(); if ( mitkWidget4->isHidden() ) mitkWidget4->show(); //update Layout Name m_Layout = LAYOUT_2D_IMAGES_LEFT; //update Layout Design List mitkWidget1->LayoutDesignListChanged( LAYOUT_2D_IMAGES_LEFT ); mitkWidget2->LayoutDesignListChanged( LAYOUT_2D_IMAGES_LEFT ); mitkWidget3->LayoutDesignListChanged( LAYOUT_2D_IMAGES_LEFT ); mitkWidget4->LayoutDesignListChanged( LAYOUT_2D_IMAGES_LEFT ); //update Alle Widgets this->UpdateAllWidgets(); } void QmitkStdMultiWidget::SetCornerAnnotation( std::string text, mitk::Color color, int widgetNumber) { if( widgetNumber > 3) { MITK_ERROR << "Unknown render window for annotation."; return; } mitk::VtkLayerController* layercontroller = mitk::VtkLayerController::GetInstance(this->GetRenderWindow(widgetNumber)->GetRenderWindow()); //remove the old renderer, because the layercontroller holds a list (vector) of all renderes //which needs to be updated if(m_CornerAnnotations[widgetNumber].ren != NULL) { layercontroller->RemoveRenderer(m_CornerAnnotations[widgetNumber].ren); } //make a new one m_CornerAnnotations[widgetNumber] = this->CreateCornerAnnotation(text, color); //add it to the list layercontroller->InsertForegroundRenderer(m_CornerAnnotations[widgetNumber].ren,true); } +void QmitkStdMultiWidget::SetCornerAnnotationVisibility(bool visibility) +{ + for(int i = 0 ; i<4 ; ++i) + { + CornerAnnotation ca = m_CornerAnnotations[i]; + if(ca.ren) ca.ren->SetDraw(visibility); + } +} + QmitkRenderWindow* QmitkStdMultiWidget::GetRenderWindow(unsigned int number) { switch (number) { case 0: return this->GetRenderWindow1(); case 1: return this->GetRenderWindow2(); case 2: return this->GetRenderWindow3(); case 3: return this->GetRenderWindow4(); default: MITK_ERROR << "Requested unknown render window"; break; } return NULL; } void QmitkStdMultiWidget::changeLayoutToDefault() { SMW_INFO << "changing layout to default... " << std::endl; //Hide all Menu Widgets this->HideAllWidgetToolbars(); delete QmitkStdMultiWidgetLayout ; //create Main Layout QmitkStdMultiWidgetLayout = new QHBoxLayout( this ); //create main splitter m_MainSplit = new QSplitter( this ); QmitkStdMultiWidgetLayout->addWidget( m_MainSplit ); //create m_LayoutSplit and add to the mainSplit m_LayoutSplit = new QSplitter( Qt::Vertical, m_MainSplit ); m_MainSplit->addWidget( m_LayoutSplit ); //add LevelWindow Widget to mainSplitter m_MainSplit->addWidget( levelWindowWidget ); //create m_SubSplit1 and m_SubSplit2 m_SubSplit1 = new QSplitter( m_LayoutSplit ); m_SubSplit2 = new QSplitter( m_LayoutSplit ); //insert Widget container into the splitters m_SubSplit1->addWidget( mitkWidget1Container ); m_SubSplit1->addWidget( mitkWidget2Container ); m_SubSplit2->addWidget( mitkWidget3Container ); m_SubSplit2->addWidget( mitkWidget4Container ); //set splitter Size QList splitterSize; splitterSize.push_back(1000); splitterSize.push_back(1000); m_SubSplit1->setSizes( splitterSize ); m_SubSplit2->setSizes( splitterSize ); m_LayoutSplit->setSizes( splitterSize ); //show mainSplitt and add to Layout m_MainSplit->show(); //show Widget if hidden if ( mitkWidget1->isHidden() ) mitkWidget1->show(); if ( mitkWidget2->isHidden() ) mitkWidget2->show(); if ( mitkWidget3->isHidden() ) mitkWidget3->show(); if ( mitkWidget4->isHidden() ) mitkWidget4->show(); m_Layout = LAYOUT_DEFAULT; //update Layout Design List mitkWidget1->LayoutDesignListChanged( LAYOUT_DEFAULT ); mitkWidget2->LayoutDesignListChanged( LAYOUT_DEFAULT ); mitkWidget3->LayoutDesignListChanged( LAYOUT_DEFAULT ); mitkWidget4->LayoutDesignListChanged( LAYOUT_DEFAULT ); //update Alle Widgets this->UpdateAllWidgets(); } void QmitkStdMultiWidget::changeLayoutToBig3D() { SMW_INFO << "changing layout to big 3D ..." << std::endl; //Hide all Menu Widgets this->HideAllWidgetToolbars(); delete QmitkStdMultiWidgetLayout ; //create Main Layout QmitkStdMultiWidgetLayout = new QHBoxLayout( this ); //create main splitter m_MainSplit = new QSplitter( this ); QmitkStdMultiWidgetLayout->addWidget( m_MainSplit ); //add widget Splitter to main Splitter m_MainSplit->addWidget( mitkWidget4Container ); //add LevelWindow Widget to mainSplitter m_MainSplit->addWidget( levelWindowWidget ); //show mainSplitt and add to Layout m_MainSplit->show(); //show/hide Widgets mitkWidget1->hide(); mitkWidget2->hide(); mitkWidget3->hide(); if ( mitkWidget4->isHidden() ) mitkWidget4->show(); m_Layout = LAYOUT_BIG_3D; //update Layout Design List mitkWidget1->LayoutDesignListChanged( LAYOUT_BIG_3D ); mitkWidget2->LayoutDesignListChanged( LAYOUT_BIG_3D ); mitkWidget3->LayoutDesignListChanged( LAYOUT_BIG_3D ); mitkWidget4->LayoutDesignListChanged( LAYOUT_BIG_3D ); //update Alle Widgets this->UpdateAllWidgets(); } void QmitkStdMultiWidget::changeLayoutToWidget1() { SMW_INFO << "changing layout to big Widget1 ..." << std::endl; //Hide all Menu Widgets this->HideAllWidgetToolbars(); delete QmitkStdMultiWidgetLayout ; //create Main Layout QmitkStdMultiWidgetLayout = new QHBoxLayout( this ); //create main splitter m_MainSplit = new QSplitter( this ); QmitkStdMultiWidgetLayout->addWidget( m_MainSplit ); //add widget Splitter to main Splitter m_MainSplit->addWidget( mitkWidget1Container ); //add LevelWindow Widget to mainSplitter m_MainSplit->addWidget( levelWindowWidget ); //show mainSplitt and add to Layout m_MainSplit->show(); //show/hide Widgets if ( mitkWidget1->isHidden() ) mitkWidget1->show(); mitkWidget2->hide(); mitkWidget3->hide(); mitkWidget4->hide(); m_Layout = LAYOUT_WIDGET1; //update Layout Design List mitkWidget1->LayoutDesignListChanged( LAYOUT_WIDGET1 ); mitkWidget2->LayoutDesignListChanged( LAYOUT_WIDGET1 ); mitkWidget3->LayoutDesignListChanged( LAYOUT_WIDGET1 ); mitkWidget4->LayoutDesignListChanged( LAYOUT_WIDGET1 ); //update Alle Widgets this->UpdateAllWidgets(); } void QmitkStdMultiWidget::changeLayoutToWidget2() { SMW_INFO << "changing layout to big Widget2 ..." << std::endl; //Hide all Menu Widgets this->HideAllWidgetToolbars(); delete QmitkStdMultiWidgetLayout ; //create Main Layout QmitkStdMultiWidgetLayout = new QHBoxLayout( this ); //create main splitter m_MainSplit = new QSplitter( this ); QmitkStdMultiWidgetLayout->addWidget( m_MainSplit ); //add widget Splitter to main Splitter m_MainSplit->addWidget( mitkWidget2Container ); //add LevelWindow Widget to mainSplitter m_MainSplit->addWidget( levelWindowWidget ); //show mainSplitt and add to Layout m_MainSplit->show(); //show/hide Widgets mitkWidget1->hide(); if ( mitkWidget2->isHidden() ) mitkWidget2->show(); mitkWidget3->hide(); mitkWidget4->hide(); m_Layout = LAYOUT_WIDGET2; //update Layout Design List mitkWidget1->LayoutDesignListChanged( LAYOUT_WIDGET2 ); mitkWidget2->LayoutDesignListChanged( LAYOUT_WIDGET2 ); mitkWidget3->LayoutDesignListChanged( LAYOUT_WIDGET2 ); mitkWidget4->LayoutDesignListChanged( LAYOUT_WIDGET2 ); //update Alle Widgets this->UpdateAllWidgets(); } void QmitkStdMultiWidget::changeLayoutToWidget3() { SMW_INFO << "changing layout to big Widget3 ..." << std::endl; //Hide all Menu Widgets this->HideAllWidgetToolbars(); delete QmitkStdMultiWidgetLayout ; //create Main Layout QmitkStdMultiWidgetLayout = new QHBoxLayout( this ); //create main splitter m_MainSplit = new QSplitter( this ); QmitkStdMultiWidgetLayout->addWidget( m_MainSplit ); //add widget Splitter to main Splitter m_MainSplit->addWidget( mitkWidget3Container ); //add LevelWindow Widget to mainSplitter m_MainSplit->addWidget( levelWindowWidget ); //show mainSplitt and add to Layout m_MainSplit->show(); //show/hide Widgets mitkWidget1->hide(); mitkWidget2->hide(); if ( mitkWidget3->isHidden() ) mitkWidget3->show(); mitkWidget4->hide(); m_Layout = LAYOUT_WIDGET3; //update Layout Design List mitkWidget1->LayoutDesignListChanged( LAYOUT_WIDGET3 ); mitkWidget2->LayoutDesignListChanged( LAYOUT_WIDGET3 ); mitkWidget3->LayoutDesignListChanged( LAYOUT_WIDGET3 ); mitkWidget4->LayoutDesignListChanged( LAYOUT_WIDGET3 ); //update Alle Widgets this->UpdateAllWidgets(); } void QmitkStdMultiWidget::changeLayoutToRowWidget3And4() { SMW_INFO << "changing layout to Widget3 and 4 in a Row..." << std::endl; //Hide all Menu Widgets this->HideAllWidgetToolbars(); delete QmitkStdMultiWidgetLayout ; //create Main Layout QmitkStdMultiWidgetLayout = new QHBoxLayout( this ); //create main splitter m_MainSplit = new QSplitter( this ); QmitkStdMultiWidgetLayout->addWidget( m_MainSplit ); //create m_LayoutSplit and add to the mainSplit m_LayoutSplit = new QSplitter( Qt::Vertical, m_MainSplit ); m_MainSplit->addWidget( m_LayoutSplit ); //add LevelWindow Widget to mainSplitter m_MainSplit->addWidget( levelWindowWidget ); //add Widgets to splitter m_LayoutSplit->addWidget( mitkWidget3Container ); m_LayoutSplit->addWidget( mitkWidget4Container ); //set Splitter Size QList splitterSize; splitterSize.push_back(1000); splitterSize.push_back(1000); m_LayoutSplit->setSizes( splitterSize ); //show mainSplitt and add to Layout m_MainSplit->show(); //show/hide Widgets mitkWidget1->hide(); mitkWidget2->hide(); if ( mitkWidget3->isHidden() ) mitkWidget3->show(); if ( mitkWidget4->isHidden() ) mitkWidget4->show(); m_Layout = LAYOUT_ROW_WIDGET_3_AND_4; //update Layout Design List mitkWidget1->LayoutDesignListChanged( LAYOUT_ROW_WIDGET_3_AND_4 ); mitkWidget2->LayoutDesignListChanged( LAYOUT_ROW_WIDGET_3_AND_4 ); mitkWidget3->LayoutDesignListChanged( LAYOUT_ROW_WIDGET_3_AND_4 ); mitkWidget4->LayoutDesignListChanged( LAYOUT_ROW_WIDGET_3_AND_4 ); //update Alle Widgets this->UpdateAllWidgets(); } void QmitkStdMultiWidget::changeLayoutToColumnWidget3And4() { SMW_INFO << "changing layout to Widget3 and 4 in one Column..." << std::endl; //Hide all Menu Widgets this->HideAllWidgetToolbars(); delete QmitkStdMultiWidgetLayout ; //create Main Layout QmitkStdMultiWidgetLayout = new QHBoxLayout( this ); //create main splitter m_MainSplit = new QSplitter( this ); QmitkStdMultiWidgetLayout->addWidget( m_MainSplit ); //create m_LayoutSplit and add to the mainSplit m_LayoutSplit = new QSplitter( m_MainSplit ); m_MainSplit->addWidget( m_LayoutSplit ); //add LevelWindow Widget to mainSplitter m_MainSplit->addWidget( levelWindowWidget ); //add Widgets to splitter m_LayoutSplit->addWidget( mitkWidget3Container ); m_LayoutSplit->addWidget( mitkWidget4Container ); //set SplitterSize QList splitterSize; splitterSize.push_back(1000); splitterSize.push_back(1000); m_LayoutSplit->setSizes( splitterSize ); //show mainSplitt and add to Layout m_MainSplit->show(); //show/hide Widgets mitkWidget1->hide(); mitkWidget2->hide(); if ( mitkWidget3->isHidden() ) mitkWidget3->show(); if ( mitkWidget4->isHidden() ) mitkWidget4->show(); m_Layout = LAYOUT_COLUMN_WIDGET_3_AND_4; //update Layout Design List mitkWidget1->LayoutDesignListChanged( LAYOUT_COLUMN_WIDGET_3_AND_4 ); mitkWidget2->LayoutDesignListChanged( LAYOUT_COLUMN_WIDGET_3_AND_4 ); mitkWidget3->LayoutDesignListChanged( LAYOUT_COLUMN_WIDGET_3_AND_4 ); mitkWidget4->LayoutDesignListChanged( LAYOUT_COLUMN_WIDGET_3_AND_4 ); //update Alle Widgets this->UpdateAllWidgets(); } void QmitkStdMultiWidget::changeLayoutToRowWidgetSmall3andBig4() { SMW_INFO << "changing layout to Widget3 and 4 in a Row..." << std::endl; this->changeLayoutToRowWidget3And4(); m_Layout = LAYOUT_ROW_WIDGET_SMALL3_AND_BIG4; } void QmitkStdMultiWidget::changeLayoutToSmallUpperWidget2Big3and4() { SMW_INFO << "changing layout to Widget3 and 4 in a Row..." << std::endl; //Hide all Menu Widgets this->HideAllWidgetToolbars(); delete QmitkStdMultiWidgetLayout ; //create Main Layout QmitkStdMultiWidgetLayout = new QHBoxLayout( this ); //create main splitter m_MainSplit = new QSplitter( this ); QmitkStdMultiWidgetLayout->addWidget( m_MainSplit ); //create m_LayoutSplit and add to the mainSplit m_LayoutSplit = new QSplitter( Qt::Vertical, m_MainSplit ); m_MainSplit->addWidget( m_LayoutSplit ); //add LevelWindow Widget to mainSplitter m_MainSplit->addWidget( levelWindowWidget ); //create m_SubSplit1 and m_SubSplit2 m_SubSplit1 = new QSplitter( Qt::Vertical, m_LayoutSplit ); m_SubSplit2 = new QSplitter( m_LayoutSplit ); //insert Widget into the splitters m_SubSplit1->addWidget( mitkWidget2Container ); m_SubSplit2->addWidget( mitkWidget3Container ); m_SubSplit2->addWidget( mitkWidget4Container ); //set Splitter Size QList splitterSize; splitterSize.push_back(1000); splitterSize.push_back(1000); m_SubSplit2->setSizes( splitterSize ); splitterSize.clear(); splitterSize.push_back(500); splitterSize.push_back(1000); m_LayoutSplit->setSizes( splitterSize ); //show mainSplitt m_MainSplit->show(); //show Widget if hidden mitkWidget1->hide(); if ( mitkWidget2->isHidden() ) mitkWidget2->show(); if ( mitkWidget3->isHidden() ) mitkWidget3->show(); if ( mitkWidget4->isHidden() ) mitkWidget4->show(); m_Layout = LAYOUT_SMALL_UPPER_WIDGET2_BIG3_AND4; //update Layout Design List mitkWidget1->LayoutDesignListChanged( LAYOUT_SMALL_UPPER_WIDGET2_BIG3_AND4 ); mitkWidget2->LayoutDesignListChanged( LAYOUT_SMALL_UPPER_WIDGET2_BIG3_AND4 ); mitkWidget3->LayoutDesignListChanged( LAYOUT_SMALL_UPPER_WIDGET2_BIG3_AND4 ); mitkWidget4->LayoutDesignListChanged( LAYOUT_SMALL_UPPER_WIDGET2_BIG3_AND4 ); //update Alle Widgets this->UpdateAllWidgets(); } void QmitkStdMultiWidget::changeLayoutTo2x2Dand3DWidget() { SMW_INFO << "changing layout to 2 x 2D and 3D Widget" << std::endl; //Hide all Menu Widgets this->HideAllWidgetToolbars(); delete QmitkStdMultiWidgetLayout ; //create Main Layout QmitkStdMultiWidgetLayout = new QHBoxLayout( this ); //create main splitter m_MainSplit = new QSplitter( this ); QmitkStdMultiWidgetLayout->addWidget( m_MainSplit ); //create m_LayoutSplit and add to the mainSplit m_LayoutSplit = new QSplitter( m_MainSplit ); m_MainSplit->addWidget( m_LayoutSplit ); //add LevelWindow Widget to mainSplitter m_MainSplit->addWidget( levelWindowWidget ); //create m_SubSplit1 and m_SubSplit2 m_SubSplit1 = new QSplitter( Qt::Vertical, m_LayoutSplit ); m_SubSplit2 = new QSplitter( m_LayoutSplit ); //add Widgets to splitter m_SubSplit1->addWidget( mitkWidget1Container ); m_SubSplit1->addWidget( mitkWidget2Container ); m_SubSplit2->addWidget( mitkWidget4Container ); //set Splitter Size QList splitterSize; splitterSize.push_back(1000); splitterSize.push_back(1000); m_SubSplit1->setSizes( splitterSize ); m_LayoutSplit->setSizes( splitterSize ); //show mainSplitt and add to Layout m_MainSplit->show(); //show/hide Widgets if ( mitkWidget1->isHidden() ) mitkWidget1->show(); if ( mitkWidget2->isHidden() ) mitkWidget2->show(); mitkWidget3->hide(); if ( mitkWidget4->isHidden() ) mitkWidget4->show(); m_Layout = LAYOUT_2X_2D_AND_3D_WIDGET; //update Layout Design List mitkWidget1->LayoutDesignListChanged( LAYOUT_2X_2D_AND_3D_WIDGET ); mitkWidget2->LayoutDesignListChanged( LAYOUT_2X_2D_AND_3D_WIDGET ); mitkWidget3->LayoutDesignListChanged( LAYOUT_2X_2D_AND_3D_WIDGET ); mitkWidget4->LayoutDesignListChanged( LAYOUT_2X_2D_AND_3D_WIDGET ); //update Alle Widgets this->UpdateAllWidgets(); } void QmitkStdMultiWidget::changeLayoutToLeft2Dand3DRight2D() { SMW_INFO << "changing layout to 2D and 3D left, 2D right Widget" << std::endl; //Hide all Menu Widgets this->HideAllWidgetToolbars(); delete QmitkStdMultiWidgetLayout ; //create Main Layout QmitkStdMultiWidgetLayout = new QHBoxLayout( this ); //create main splitter m_MainSplit = new QSplitter( this ); QmitkStdMultiWidgetLayout->addWidget( m_MainSplit ); //create m_LayoutSplit and add to the mainSplit m_LayoutSplit = new QSplitter( m_MainSplit ); m_MainSplit->addWidget( m_LayoutSplit ); //add LevelWindow Widget to mainSplitter m_MainSplit->addWidget( levelWindowWidget ); //create m_SubSplit1 and m_SubSplit2 m_SubSplit1 = new QSplitter( Qt::Vertical, m_LayoutSplit ); m_SubSplit2 = new QSplitter( m_LayoutSplit ); //add Widgets to splitter m_SubSplit1->addWidget( mitkWidget1Container ); m_SubSplit1->addWidget( mitkWidget4Container ); m_SubSplit2->addWidget( mitkWidget2Container ); //set Splitter Size QList splitterSize; splitterSize.push_back(1000); splitterSize.push_back(1000); m_SubSplit1->setSizes( splitterSize ); m_LayoutSplit->setSizes( splitterSize ); //show mainSplitt and add to Layout m_MainSplit->show(); //show/hide Widgets if ( mitkWidget1->isHidden() ) mitkWidget1->show(); if ( mitkWidget2->isHidden() ) mitkWidget2->show(); mitkWidget3->hide(); if ( mitkWidget4->isHidden() ) mitkWidget4->show(); m_Layout = LAYOUT_2D_AND_3D_LEFT_2D_RIGHT_WIDGET; //update Layout Design List mitkWidget1->LayoutDesignListChanged( LAYOUT_2D_AND_3D_LEFT_2D_RIGHT_WIDGET ); mitkWidget2->LayoutDesignListChanged( LAYOUT_2D_AND_3D_LEFT_2D_RIGHT_WIDGET ); mitkWidget3->LayoutDesignListChanged( LAYOUT_2D_AND_3D_LEFT_2D_RIGHT_WIDGET ); mitkWidget4->LayoutDesignListChanged( LAYOUT_2D_AND_3D_LEFT_2D_RIGHT_WIDGET ); //update Alle Widgets this->UpdateAllWidgets(); } void QmitkStdMultiWidget::changeLayoutTo2DUpAnd3DDown() { SMW_INFO << "changing layout to 2D up and 3D down" << std::endl; //Hide all Menu Widgets this->HideAllWidgetToolbars(); delete QmitkStdMultiWidgetLayout ; //create Main Layout QmitkStdMultiWidgetLayout = new QHBoxLayout( this ); //Set Layout to widget this->setLayout(QmitkStdMultiWidgetLayout); //create main splitter m_MainSplit = new QSplitter( this ); QmitkStdMultiWidgetLayout->addWidget( m_MainSplit ); //create m_LayoutSplit and add to the mainSplit m_LayoutSplit = new QSplitter( Qt::Vertical, m_MainSplit ); m_MainSplit->addWidget( m_LayoutSplit ); //add LevelWindow Widget to mainSplitter m_MainSplit->addWidget( levelWindowWidget ); //create m_SubSplit1 and m_SubSplit2 m_SubSplit1 = new QSplitter( m_LayoutSplit ); m_SubSplit2 = new QSplitter( m_LayoutSplit ); //insert Widget Container into splitter top m_SubSplit1->addWidget( mitkWidget1Container ); //set SplitterSize for splitter top QList splitterSize; //insert Widget Container into splitter bottom m_SubSplit2->addWidget( mitkWidget4Container ); //set SplitterSize for splitter m_LayoutSplit splitterSize.clear(); splitterSize.push_back(700); splitterSize.push_back(700); m_LayoutSplit->setSizes( splitterSize ); //show mainSplitt m_MainSplit->show(); //show/hide Widgets if ( mitkWidget1->isHidden() ) mitkWidget1->show(); mitkWidget2->hide(); mitkWidget3->hide(); if ( mitkWidget4->isHidden() ) mitkWidget4->show(); m_Layout = LAYOUT_2D_UP_AND_3D_DOWN; //update Layout Design List mitkWidget1->LayoutDesignListChanged( LAYOUT_2D_UP_AND_3D_DOWN ); mitkWidget2->LayoutDesignListChanged( LAYOUT_2D_UP_AND_3D_DOWN ); mitkWidget3->LayoutDesignListChanged( LAYOUT_2D_UP_AND_3D_DOWN ); mitkWidget4->LayoutDesignListChanged( LAYOUT_2D_UP_AND_3D_DOWN ); //update all Widgets this->UpdateAllWidgets(); } void QmitkStdMultiWidget::SetDataStorage( mitk::DataStorage* ds ) { mitk::BaseRenderer::GetInstance(mitkWidget1->GetRenderWindow())->SetDataStorage(ds); mitk::BaseRenderer::GetInstance(mitkWidget2->GetRenderWindow())->SetDataStorage(ds); mitk::BaseRenderer::GetInstance(mitkWidget3->GetRenderWindow())->SetDataStorage(ds); mitk::BaseRenderer::GetInstance(mitkWidget4->GetRenderWindow())->SetDataStorage(ds); m_DataStorage = ds; } void QmitkStdMultiWidget::Fit() { vtkSmartPointer vtkrenderer; mitk::BaseRenderer::GetInstance(mitkWidget1->GetRenderWindow())->GetDisplayGeometry()->Fit(); mitk::BaseRenderer::GetInstance(mitkWidget2->GetRenderWindow())->GetDisplayGeometry()->Fit(); mitk::BaseRenderer::GetInstance(mitkWidget3->GetRenderWindow())->GetDisplayGeometry()->Fit(); mitk::BaseRenderer::GetInstance(mitkWidget4->GetRenderWindow())->GetDisplayGeometry()->Fit(); int w = vtkObject::GetGlobalWarningDisplay(); vtkObject::GlobalWarningDisplayOff(); vtkrenderer = mitk::BaseRenderer::GetInstance(mitkWidget1->GetRenderWindow())->GetVtkRenderer(); if ( vtkrenderer!= NULL ) vtkrenderer->ResetCamera(); vtkrenderer = mitk::BaseRenderer::GetInstance(mitkWidget2->GetRenderWindow())->GetVtkRenderer(); if ( vtkrenderer!= NULL ) vtkrenderer->ResetCamera(); vtkrenderer = mitk::BaseRenderer::GetInstance(mitkWidget3->GetRenderWindow())->GetVtkRenderer(); if ( vtkrenderer!= NULL ) vtkrenderer->ResetCamera(); vtkrenderer = mitk::BaseRenderer::GetInstance(mitkWidget4->GetRenderWindow())->GetVtkRenderer(); if ( vtkrenderer!= NULL ) vtkrenderer->ResetCamera(); vtkObject::SetGlobalWarningDisplay(w); } void QmitkStdMultiWidget::InitPositionTracking() { //PoinSetNode for MouseOrientation m_PositionTrackerNode = mitk::DataNode::New(); m_PositionTrackerNode->SetProperty("name", mitk::StringProperty::New("Mouse Position")); m_PositionTrackerNode->SetData( mitk::PointSet::New() ); m_PositionTrackerNode->SetColor(1.0,0.33,0.0); m_PositionTrackerNode->SetProperty("layer", mitk::IntProperty::New(1001)); m_PositionTrackerNode->SetVisibility(true); m_PositionTrackerNode->SetProperty("inputdevice", mitk::BoolProperty::New(true) ); m_PositionTrackerNode->SetProperty("BaseRendererMapperID", mitk::IntProperty::New(0) );//point position 2D mouse m_PositionTrackerNode->SetProperty("baserenderer", mitk::StringProperty::New("N/A")); } void QmitkStdMultiWidget::AddDisplayPlaneSubTree() { // add the displayed planes of the multiwidget to a node to which the subtree // @a planesSubTree points ... mitk::PlaneGeometryDataMapper2D::Pointer mapper; // ... of widget 1 mitk::BaseRenderer* renderer1 = mitk::BaseRenderer::GetInstance(mitkWidget1->GetRenderWindow()); m_PlaneNode1 = renderer1->GetCurrentWorldPlaneGeometryNode(); m_PlaneNode1->SetProperty("visible", mitk::BoolProperty::New(true)); m_PlaneNode1->SetProperty("name", mitk::StringProperty::New(std::string(renderer1->GetName()) + ".plane")); m_PlaneNode1->SetProperty("includeInBoundingBox", mitk::BoolProperty::New(false)); m_PlaneNode1->SetProperty("helper object", mitk::BoolProperty::New(true)); mapper = mitk::PlaneGeometryDataMapper2D::New(); m_PlaneNode1->SetMapper(mitk::BaseRenderer::Standard2D, mapper); // ... of widget 2 mitk::BaseRenderer* renderer2 = mitk::BaseRenderer::GetInstance(mitkWidget2->GetRenderWindow()); m_PlaneNode2 = renderer2->GetCurrentWorldPlaneGeometryNode(); m_PlaneNode2->SetProperty("visible", mitk::BoolProperty::New(true)); m_PlaneNode2->SetProperty("name", mitk::StringProperty::New(std::string(renderer2->GetName()) + ".plane")); m_PlaneNode2->SetProperty("includeInBoundingBox", mitk::BoolProperty::New(false)); m_PlaneNode2->SetProperty("helper object", mitk::BoolProperty::New(true)); mapper = mitk::PlaneGeometryDataMapper2D::New(); m_PlaneNode2->SetMapper(mitk::BaseRenderer::Standard2D, mapper); // ... of widget 3 mitk::BaseRenderer* renderer3 = mitk::BaseRenderer::GetInstance(mitkWidget3->GetRenderWindow()); m_PlaneNode3 = renderer3->GetCurrentWorldPlaneGeometryNode(); m_PlaneNode3->SetProperty("visible", mitk::BoolProperty::New(true)); m_PlaneNode3->SetProperty("name", mitk::StringProperty::New(std::string(renderer3->GetName()) + ".plane")); m_PlaneNode3->SetProperty("includeInBoundingBox", mitk::BoolProperty::New(false)); m_PlaneNode3->SetProperty("helper object", mitk::BoolProperty::New(true)); mapper = mitk::PlaneGeometryDataMapper2D::New(); m_PlaneNode3->SetMapper(mitk::BaseRenderer::Standard2D, mapper); m_ParentNodeForGeometryPlanes = mitk::DataNode::New(); m_ParentNodeForGeometryPlanes->SetProperty("name", mitk::StringProperty::New("Widgets")); m_ParentNodeForGeometryPlanes->SetProperty("helper object", mitk::BoolProperty::New(true)); } mitk::SliceNavigationController* QmitkStdMultiWidget::GetTimeNavigationController() { return m_TimeNavigationController; } void QmitkStdMultiWidget::EnableStandardLevelWindow() { levelWindowWidget->disconnect(this); levelWindowWidget->SetDataStorage(mitk::BaseRenderer::GetInstance(mitkWidget1->GetRenderWindow())->GetDataStorage()); levelWindowWidget->show(); } void QmitkStdMultiWidget::DisableStandardLevelWindow() { levelWindowWidget->disconnect(this); levelWindowWidget->hide(); } // CAUTION: Legacy code for enabling Qt-signal-controlled view initialization. // Use RenderingManager::InitializeViews() instead. bool QmitkStdMultiWidget::InitializeStandardViews( const mitk::Geometry3D * geometry ) { return m_RenderingManager->InitializeViews( geometry ); } void QmitkStdMultiWidget::RequestUpdate() { m_RenderingManager->RequestUpdate(mitkWidget1->GetRenderWindow()); m_RenderingManager->RequestUpdate(mitkWidget2->GetRenderWindow()); m_RenderingManager->RequestUpdate(mitkWidget3->GetRenderWindow()); m_RenderingManager->RequestUpdate(mitkWidget4->GetRenderWindow()); } void QmitkStdMultiWidget::ForceImmediateUpdate() { m_RenderingManager->ForceImmediateUpdate(mitkWidget1->GetRenderWindow()); m_RenderingManager->ForceImmediateUpdate(mitkWidget2->GetRenderWindow()); m_RenderingManager->ForceImmediateUpdate(mitkWidget3->GetRenderWindow()); m_RenderingManager->ForceImmediateUpdate(mitkWidget4->GetRenderWindow()); } void QmitkStdMultiWidget::wheelEvent( QWheelEvent * e ) { emit WheelMoved( e ); } void QmitkStdMultiWidget::mousePressEvent(QMouseEvent * e) { if (e->button() == Qt::LeftButton) { mitk::Point3D pointValue = this->GetLastLeftClickPosition(); emit LeftMouseClicked(pointValue); } } void QmitkStdMultiWidget::moveEvent( QMoveEvent* e ) { QWidget::moveEvent( e ); // it is necessary to readjust the position of the overlays as the StdMultiWidget has moved // unfortunately it's not done by QmitkRenderWindow::moveEvent -> must be done here emit Moved(); } void QmitkStdMultiWidget::leaveEvent ( QEvent * /*e*/ ) { //set cursor back to initial state m_SlicesRotator->ResetMouseCursor(); } QmitkRenderWindow* QmitkStdMultiWidget::GetRenderWindow1() const { return mitkWidget1; } QmitkRenderWindow* QmitkStdMultiWidget::GetRenderWindow2() const { return mitkWidget2; } QmitkRenderWindow* QmitkStdMultiWidget::GetRenderWindow3() const { return mitkWidget3; } QmitkRenderWindow* QmitkStdMultiWidget::GetRenderWindow4() const { return mitkWidget4; } const mitk::Point3D& QmitkStdMultiWidget::GetLastLeftClickPosition() const { return m_LastLeftClickPositionSupplier->GetCurrentPoint(); } const mitk::Point3D QmitkStdMultiWidget::GetCrossPosition() const { const mitk::PlaneGeometry *plane1 = mitkWidget1->GetSliceNavigationController()->GetCurrentPlaneGeometry(); const mitk::PlaneGeometry *plane2 = mitkWidget2->GetSliceNavigationController()->GetCurrentPlaneGeometry(); const mitk::PlaneGeometry *plane3 = mitkWidget3->GetSliceNavigationController()->GetCurrentPlaneGeometry(); mitk::Line3D line; if ( (plane1 != NULL) && (plane2 != NULL) && (plane1->IntersectionLine( plane2, line )) ) { mitk::Point3D point; if ( (plane3 != NULL) && (plane3->IntersectionPoint( line, point )) ) { return point; } } return m_LastLeftClickPositionSupplier->GetCurrentPoint(); } void QmitkStdMultiWidget::EnablePositionTracking() { if (!m_PositionTracker) { m_PositionTracker = mitk::PositionTracker::New("PositionTracker", NULL); } mitk::GlobalInteraction* globalInteraction = mitk::GlobalInteraction::GetInstance(); if (globalInteraction) { if(m_DataStorage.IsNotNull()) m_DataStorage->Add(m_PositionTrackerNode); globalInteraction->AddListener(m_PositionTracker); } } void QmitkStdMultiWidget::DisablePositionTracking() { mitk::GlobalInteraction* globalInteraction = mitk::GlobalInteraction::GetInstance(); if(globalInteraction) { if (m_DataStorage.IsNotNull()) m_DataStorage->Remove(m_PositionTrackerNode); globalInteraction->RemoveListener(m_PositionTracker); } } void QmitkStdMultiWidget::EnsureDisplayContainsPoint( mitk::DisplayGeometry* displayGeometry, const mitk::Point3D& p) { mitk::Point2D pointOnPlane; displayGeometry->Map( p, pointOnPlane ); // point minus origin < width or height ==> outside ? mitk::Vector2D pointOnRenderWindow_MM; pointOnRenderWindow_MM = pointOnPlane.GetVectorFromOrigin() - displayGeometry->GetOriginInMM(); mitk::Vector2D sizeOfDisplay( displayGeometry->GetSizeInMM() ); if ( sizeOfDisplay[0] < pointOnRenderWindow_MM[0] || 0 > pointOnRenderWindow_MM[0] || sizeOfDisplay[1] < pointOnRenderWindow_MM[1] || 0 > pointOnRenderWindow_MM[1] ) { // point is not visible -> move geometry mitk::Vector2D offset( (pointOnRenderWindow_MM - sizeOfDisplay / 2.0) / displayGeometry->GetScaleFactorMMPerDisplayUnit() ); displayGeometry->MoveBy( offset ); } } void QmitkStdMultiWidget::MoveCrossToPosition(const mitk::Point3D& newPosition) { // create a PositionEvent with the given position and // tell the slice navigation controllers to move there mitk::Point2D p2d; mitk::PositionEvent event( mitk::BaseRenderer::GetInstance(mitkWidget1->GetRenderWindow()), 0, 0, 0, mitk::Key_unknown, p2d, newPosition ); mitk::StateEvent stateEvent(mitk::EIDLEFTMOUSEBTN, &event); mitk::StateEvent stateEvent2(mitk::EIDLEFTMOUSERELEASE, &event); switch ( m_PlaneMode ) { default: case PLANE_MODE_SLICING: mitkWidget1->GetSliceNavigationController()->HandleEvent( &stateEvent ); mitkWidget2->GetSliceNavigationController()->HandleEvent( &stateEvent ); mitkWidget3->GetSliceNavigationController()->HandleEvent( &stateEvent ); // just in case SNCs will develop something that depends on the mouse // button being released again mitkWidget1->GetSliceNavigationController()->HandleEvent( &stateEvent2 ); mitkWidget2->GetSliceNavigationController()->HandleEvent( &stateEvent2 ); mitkWidget3->GetSliceNavigationController()->HandleEvent( &stateEvent2 ); break; case PLANE_MODE_ROTATION: m_SlicesRotator->HandleEvent( &stateEvent ); // just in case SNCs will develop something that depends on the mouse // button being released again m_SlicesRotator->HandleEvent( &stateEvent2 ); break; case PLANE_MODE_SWIVEL: m_SlicesSwiveller->HandleEvent( &stateEvent ); // just in case SNCs will develop something that depends on the mouse // button being released again m_SlicesSwiveller->HandleEvent( &stateEvent2 ); break; } // determine if cross is now out of display // if so, move the display window EnsureDisplayContainsPoint( mitk::BaseRenderer::GetInstance(mitkWidget1->GetRenderWindow()) ->GetDisplayGeometry(), newPosition ); EnsureDisplayContainsPoint( mitk::BaseRenderer::GetInstance(mitkWidget2->GetRenderWindow()) ->GetDisplayGeometry(), newPosition ); EnsureDisplayContainsPoint( mitk::BaseRenderer::GetInstance(mitkWidget3->GetRenderWindow()) ->GetDisplayGeometry(), newPosition ); // update displays m_RenderingManager->RequestUpdateAll(); } void QmitkStdMultiWidget::HandleCrosshairPositionEvent() { if(!m_PendingCrosshairPositionEvent) { m_PendingCrosshairPositionEvent=true; QTimer::singleShot(0,this,SLOT( HandleCrosshairPositionEventDelayed() ) ); } } mitk::DataNode::Pointer QmitkStdMultiWidget::GetTopLayerNode(mitk::DataStorage::SetOfObjects::ConstPointer nodes) { mitk::Point3D crosshairPos = this->GetCrossPosition(); mitk::DataNode::Pointer node; int maxlayer = -32768; if(nodes.IsNotNull()) { mitk::BaseRenderer* baseRenderer = this->mitkWidget1->GetSliceNavigationController()->GetRenderer(); // find node with largest layer, that is the node shown on top in the render window for (unsigned int x = 0; x < nodes->size(); x++) { if ( (nodes->at(x)->GetData()->GetGeometry() != NULL) && nodes->at(x)->GetData()->GetGeometry()->IsInside(crosshairPos) ) { int layer = 0; if(!(nodes->at(x)->GetIntProperty("layer", layer))) continue; if(layer > maxlayer) { if( static_cast(nodes->at(x))->IsVisible( baseRenderer ) ) { node = nodes->at(x); maxlayer = layer; } } } } } return node; } void QmitkStdMultiWidget::HandleCrosshairPositionEventDelayed() { m_PendingCrosshairPositionEvent = false; // find image with highest layer mitk::TNodePredicateDataType::Pointer isImageData = mitk::TNodePredicateDataType::New(); mitk::DataStorage::SetOfObjects::ConstPointer nodes = this->m_DataStorage->GetSubset(isImageData).GetPointer(); mitk::DataNode::Pointer node; mitk::DataNode::Pointer topSourceNode; mitk::Image::Pointer image; bool isBinary = false; node = this->GetTopLayerNode(nodes); int component = 0; if(node.IsNotNull()) { node->GetBoolProperty("binary",isBinary); if(isBinary) { mitk::DataStorage::SetOfObjects::ConstPointer sourcenodes = m_DataStorage->GetSources(node, NULL, true); if(!sourcenodes->empty()) { topSourceNode = this->GetTopLayerNode(sourcenodes); } if(topSourceNode.IsNotNull()) { image = dynamic_cast(topSourceNode->GetData()); topSourceNode->GetIntProperty("Image.Displayed Component", component); } else { image = dynamic_cast(node->GetData()); node->GetIntProperty("Image.Displayed Component", component); } } else { image = dynamic_cast(node->GetData()); node->GetIntProperty("Image.Displayed Component", component); } } mitk::Point3D crosshairPos = this->GetCrossPosition(); std::string statusText; std::stringstream stream; itk::Index<3> p; mitk::BaseRenderer* baseRenderer = this->mitkWidget1->GetSliceNavigationController()->GetRenderer(); unsigned int timestep = baseRenderer->GetTimeStep(); if(image.IsNotNull() && (image->GetTimeSteps() > timestep )) { image->GetGeometry()->WorldToIndex(crosshairPos, p); stream.precision(2); stream<<"Position: <" << std::fixed < mm"; stream<<"; Index: <"< "; mitk::ScalarType pixelValue = image->GetPixelValueByIndex(p, timestep, component); if (fabs(pixelValue)>1000000 || fabs(pixelValue) < 0.01) { stream<<"; Time: " << baseRenderer->GetTime() << " ms; Pixelvalue: "<< std::scientific<< pixelValue <<" "; } else { stream<<"; Time: " << baseRenderer->GetTime() << " ms; Pixelvalue: "<< pixelValue <<" "; } } else { stream << "No image information at this position!"; } statusText = stream.str(); mitk::StatusBar::GetInstance()->DisplayGreyValueText(statusText.c_str()); } void QmitkStdMultiWidget::EnableNavigationControllerEventListening() { // Let NavigationControllers listen to GlobalInteraction mitk::GlobalInteraction *gi = mitk::GlobalInteraction::GetInstance(); //// Listen for SliceNavigationController //TODO 18735 can this be deleted ?? //mitkWidget1->GetSliceNavigationController()->crosshairPositionEvent.AddListener( mitk::MessageDelegate( this, &QmitkStdMultiWidget::HandleCrosshairPositionEvent ) ); //mitkWidget2->GetSliceNavigationController()->crosshairPositionEvent.AddListener( mitk::MessageDelegate( this, &QmitkStdMultiWidget::HandleCrosshairPositionEvent ) ); //mitkWidget3->GetSliceNavigationController()->crosshairPositionEvent.AddListener( mitk::MessageDelegate( this, &QmitkStdMultiWidget::HandleCrosshairPositionEvent ) ); switch ( m_PlaneMode ) { default: case PLANE_MODE_SLICING: gi->AddListener( mitkWidget1->GetSliceNavigationController() ); gi->AddListener( mitkWidget2->GetSliceNavigationController() ); gi->AddListener( mitkWidget3->GetSliceNavigationController() ); gi->AddListener( mitkWidget4->GetSliceNavigationController() ); break; case PLANE_MODE_ROTATION: gi->AddListener( m_SlicesRotator ); break; case PLANE_MODE_SWIVEL: gi->AddListener( m_SlicesSwiveller ); break; } gi->AddListener( m_TimeNavigationController ); m_CrosshairNavigationEnabled = true; } void QmitkStdMultiWidget::DisableNavigationControllerEventListening() { // Do not let NavigationControllers listen to GlobalInteraction mitk::GlobalInteraction *gi = mitk::GlobalInteraction::GetInstance(); switch ( m_PlaneMode ) { default: case PLANE_MODE_SLICING: gi->RemoveListener( mitkWidget1->GetSliceNavigationController() ); gi->RemoveListener( mitkWidget2->GetSliceNavigationController() ); gi->RemoveListener( mitkWidget3->GetSliceNavigationController() ); gi->RemoveListener( mitkWidget4->GetSliceNavigationController() ); break; case PLANE_MODE_ROTATION: m_SlicesRotator->ResetMouseCursor(); gi->RemoveListener( m_SlicesRotator ); break; case PLANE_MODE_SWIVEL: m_SlicesSwiveller->ResetMouseCursor(); gi->RemoveListener( m_SlicesSwiveller ); break; } gi->RemoveListener( m_TimeNavigationController ); m_CrosshairNavigationEnabled = false; } int QmitkStdMultiWidget::GetLayout() const { return m_Layout; } bool QmitkStdMultiWidget::GetGradientBackgroundFlag() const { return m_GradientBackgroundFlag; } void QmitkStdMultiWidget::EnableGradientBackground() { // gradient background is by default only in widget 4, otherwise // interferences between 2D rendering and VTK rendering may occur. for(unsigned int i = 0; i < 4; ++i) { m_GradientBackground[i]->Enable(); } m_GradientBackgroundFlag = true; } void QmitkStdMultiWidget::DisableGradientBackground() { for(unsigned int i = 0; i < 4; ++i) { m_GradientBackground[i]->Disable(); } m_GradientBackgroundFlag = false; } void QmitkStdMultiWidget::EnableDepartmentLogo() { m_LogoRendering->SetVisibility(true); } void QmitkStdMultiWidget::DisableDepartmentLogo() { m_LogoRendering->SetVisibility(false); } bool QmitkStdMultiWidget::IsDepartmentLogoEnabled() const { return m_LogoRendering->IsVisible(mitk::BaseRenderer::GetInstance(mitkWidget4->GetRenderWindow())); } bool QmitkStdMultiWidget::IsCrosshairNavigationEnabled() const { return m_CrosshairNavigationEnabled; } mitk::SlicesRotator * QmitkStdMultiWidget::GetSlicesRotator() const { return m_SlicesRotator; } mitk::SlicesSwiveller * QmitkStdMultiWidget::GetSlicesSwiveller() const { return m_SlicesSwiveller; } void QmitkStdMultiWidget::SetWidgetPlaneVisibility(const char* widgetName, bool visible, mitk::BaseRenderer *renderer) { if (m_DataStorage.IsNotNull()) { mitk::DataNode* n = m_DataStorage->GetNamedNode(widgetName); if (n != NULL) n->SetVisibility(visible, renderer); } } void QmitkStdMultiWidget::SetWidgetPlanesVisibility(bool visible, mitk::BaseRenderer *renderer) { if (m_PlaneNode1.IsNotNull()) { m_PlaneNode1->SetVisibility(visible, renderer); } if (m_PlaneNode2.IsNotNull()) { m_PlaneNode2->SetVisibility(visible, renderer); } if (m_PlaneNode3.IsNotNull()) { m_PlaneNode3->SetVisibility(visible, renderer); } m_RenderingManager->RequestUpdateAll(); } void QmitkStdMultiWidget::SetWidgetPlanesLocked(bool locked) { //do your job and lock or unlock slices. GetRenderWindow1()->GetSliceNavigationController()->SetSliceLocked(locked); GetRenderWindow2()->GetSliceNavigationController()->SetSliceLocked(locked); GetRenderWindow3()->GetSliceNavigationController()->SetSliceLocked(locked); } void QmitkStdMultiWidget::SetWidgetPlanesRotationLocked(bool locked) { //do your job and lock or unlock slices. GetRenderWindow1()->GetSliceNavigationController()->SetSliceRotationLocked(locked); GetRenderWindow2()->GetSliceNavigationController()->SetSliceRotationLocked(locked); GetRenderWindow3()->GetSliceNavigationController()->SetSliceRotationLocked(locked); } void QmitkStdMultiWidget::SetWidgetPlanesRotationLinked( bool link ) { m_SlicesRotator->SetLinkPlanes( link ); m_SlicesSwiveller->SetLinkPlanes( link ); emit WidgetPlanesRotationLinked( link ); } void QmitkStdMultiWidget::SetWidgetPlaneMode( int userMode ) { MITK_DEBUG << "Changing crosshair mode to " << userMode; // first of all reset left mouse button interaction to default if PACS interaction style is active m_MouseModeSwitcher->SelectMouseMode( mitk::MouseModeSwitcher::MousePointer ); emit WidgetNotifyNewCrossHairMode( userMode ); int mode = m_PlaneMode; bool link = false; // Convert user interface mode to actual mode { switch(userMode) { case 0: mode = PLANE_MODE_SLICING; link = false; break; case 1: mode = PLANE_MODE_ROTATION; link = false; break; case 2: mode = PLANE_MODE_ROTATION; link = true; break; case 3: mode = PLANE_MODE_SWIVEL; link = false; break; } } // Slice rotation linked m_SlicesRotator->SetLinkPlanes( link ); m_SlicesSwiveller->SetLinkPlanes( link ); // Do nothing if mode didn't change if ( m_PlaneMode == mode ) { return; } mitk::GlobalInteraction *gi = mitk::GlobalInteraction::GetInstance(); // Remove listeners of previous mode switch ( m_PlaneMode ) { default: case PLANE_MODE_SLICING: // Notify MainTemplate GUI that this mode has been deselected emit WidgetPlaneModeSlicing( false ); gi->RemoveListener( mitkWidget1->GetSliceNavigationController() ); gi->RemoveListener( mitkWidget2->GetSliceNavigationController() ); gi->RemoveListener( mitkWidget3->GetSliceNavigationController() ); gi->RemoveListener( mitkWidget4->GetSliceNavigationController() ); break; case PLANE_MODE_ROTATION: // Notify MainTemplate GUI that this mode has been deselected emit WidgetPlaneModeRotation( false ); m_SlicesRotator->ResetMouseCursor(); gi->RemoveListener( m_SlicesRotator ); break; case PLANE_MODE_SWIVEL: // Notify MainTemplate GUI that this mode has been deselected emit WidgetPlaneModeSwivel( false ); m_SlicesSwiveller->ResetMouseCursor(); gi->RemoveListener( m_SlicesSwiveller ); break; } // Set new mode and add corresponding listener to GlobalInteraction m_PlaneMode = mode; switch ( m_PlaneMode ) { default: case PLANE_MODE_SLICING: // Notify MainTemplate GUI that this mode has been selected emit WidgetPlaneModeSlicing( true ); // Add listeners gi->AddListener( mitkWidget1->GetSliceNavigationController() ); gi->AddListener( mitkWidget2->GetSliceNavigationController() ); gi->AddListener( mitkWidget3->GetSliceNavigationController() ); gi->AddListener( mitkWidget4->GetSliceNavigationController() ); m_RenderingManager->InitializeViews(); break; case PLANE_MODE_ROTATION: // Notify MainTemplate GUI that this mode has been selected emit WidgetPlaneModeRotation( true ); // Add listener gi->AddListener( m_SlicesRotator ); break; case PLANE_MODE_SWIVEL: // Notify MainTemplate GUI that this mode has been selected emit WidgetPlaneModeSwivel( true ); // Add listener gi->AddListener( m_SlicesSwiveller ); break; } // Notify MainTemplate GUI that mode has changed emit WidgetPlaneModeChange(m_PlaneMode); } void QmitkStdMultiWidget::SetGradientBackgroundColorForRenderWindow( const mitk::Color & upper, const mitk::Color & lower, unsigned int widgetNumber ) { if(widgetNumber > 3) { MITK_ERROR << "Gradientbackground for unknown widget!"; return; } m_GradientBackgroundColors[widgetNumber].first = upper; m_GradientBackgroundColors[widgetNumber].second = lower; m_GradientBackground[widgetNumber]->SetGradientColors(upper, lower); m_GradientBackgroundFlag = true; } void QmitkStdMultiWidget::SetGradientBackgroundColors( const mitk::Color & upper, const mitk::Color & lower ) { for(unsigned int i = 0; i < 4; ++i) { m_GradientBackground[i]->SetGradientColors(upper, lower); } m_GradientBackgroundFlag = true; } void QmitkStdMultiWidget::SetDepartmentLogoPath( const char * path ) { m_LogoRendering->SetLogoImagePath(path); mitk::BaseRenderer* renderer = mitk::BaseRenderer::GetInstance(mitkWidget4->GetRenderWindow()); m_LogoRendering->Update(renderer); RequestUpdate(); } void QmitkStdMultiWidget::SetWidgetPlaneModeToSlicing( bool activate ) { if ( activate ) { this->SetWidgetPlaneMode( PLANE_MODE_SLICING ); } } void QmitkStdMultiWidget::SetWidgetPlaneModeToRotation( bool activate ) { if ( activate ) { this->SetWidgetPlaneMode( PLANE_MODE_ROTATION ); } } void QmitkStdMultiWidget::SetWidgetPlaneModeToSwivel( bool activate ) { if ( activate ) { this->SetWidgetPlaneMode( PLANE_MODE_SWIVEL ); } } void QmitkStdMultiWidget::OnLayoutDesignChanged( int layoutDesignIndex ) { switch( layoutDesignIndex ) { case LAYOUT_DEFAULT: { this->changeLayoutToDefault(); break; } case LAYOUT_2D_IMAGES_UP: { this->changeLayoutTo2DImagesUp(); break; } case LAYOUT_2D_IMAGES_LEFT: { this->changeLayoutTo2DImagesLeft(); break; } case LAYOUT_BIG_3D: { this->changeLayoutToBig3D(); break; } case LAYOUT_WIDGET1: { this->changeLayoutToWidget1(); break; } case LAYOUT_WIDGET2: { this->changeLayoutToWidget2(); break; } case LAYOUT_WIDGET3: { this->changeLayoutToWidget3(); break; } case LAYOUT_2X_2D_AND_3D_WIDGET: { this->changeLayoutTo2x2Dand3DWidget(); break; } case LAYOUT_ROW_WIDGET_3_AND_4: { this->changeLayoutToRowWidget3And4(); break; } case LAYOUT_COLUMN_WIDGET_3_AND_4: { this->changeLayoutToColumnWidget3And4(); break; } case LAYOUT_ROW_WIDGET_SMALL3_AND_BIG4: { this->changeLayoutToRowWidgetSmall3andBig4(); break; } case LAYOUT_SMALL_UPPER_WIDGET2_BIG3_AND4: { this->changeLayoutToSmallUpperWidget2Big3and4(); break; } case LAYOUT_2D_AND_3D_LEFT_2D_RIGHT_WIDGET: { this->changeLayoutToLeft2Dand3DRight2D(); break; } }; } void QmitkStdMultiWidget::UpdateAllWidgets() { mitkWidget1->resize( mitkWidget1Container->frameSize().width()-1, mitkWidget1Container->frameSize().height() ); mitkWidget1->resize( mitkWidget1Container->frameSize().width(), mitkWidget1Container->frameSize().height() ); mitkWidget2->resize( mitkWidget2Container->frameSize().width()-1, mitkWidget2Container->frameSize().height() ); mitkWidget2->resize( mitkWidget2Container->frameSize().width(), mitkWidget2Container->frameSize().height() ); mitkWidget3->resize( mitkWidget3Container->frameSize().width()-1, mitkWidget3Container->frameSize().height() ); mitkWidget3->resize( mitkWidget3Container->frameSize().width(), mitkWidget3Container->frameSize().height() ); mitkWidget4->resize( mitkWidget4Container->frameSize().width()-1, mitkWidget4Container->frameSize().height() ); mitkWidget4->resize( mitkWidget4Container->frameSize().width(), mitkWidget4Container->frameSize().height() ); } void QmitkStdMultiWidget::HideAllWidgetToolbars() { mitkWidget1->HideRenderWindowMenu(); mitkWidget2->HideRenderWindowMenu(); mitkWidget3->HideRenderWindowMenu(); mitkWidget4->HideRenderWindowMenu(); } void QmitkStdMultiWidget::ActivateMenuWidget( bool state ) { mitkWidget1->ActivateMenuWidget( state, this ); mitkWidget2->ActivateMenuWidget( state, this ); mitkWidget3->ActivateMenuWidget( state, this ); mitkWidget4->ActivateMenuWidget( state, this ); } bool QmitkStdMultiWidget::IsMenuWidgetEnabled() const { return mitkWidget1->GetActivateMenuWidgetFlag(); } void QmitkStdMultiWidget::SetDecorationColor(unsigned int widgetNumber, mitk::Color color) { switch (widgetNumber) { case 0: if(m_PlaneNode1.IsNotNull()) { m_PlaneNode1->SetColor(color); } break; case 1: if(m_PlaneNode2.IsNotNull()) { m_PlaneNode2->SetColor(color); } break; case 2: if(m_PlaneNode3.IsNotNull()) { m_PlaneNode3->SetColor(color); } break; case 3: m_DecorationColorWidget4 = color; break; default: MITK_ERROR << "Decoration color for unknown widget!"; break; } } void QmitkStdMultiWidget::ResetCrosshair() { if (m_DataStorage.IsNotNull()) { m_RenderingManager->InitializeViewsByBoundingObjects(m_DataStorage); //m_RenderingManager->InitializeViews( m_DataStorage->ComputeVisibleBoundingGeometry3D() ); // reset interactor to normal slicing this->SetWidgetPlaneMode(PLANE_MODE_SLICING); } } void QmitkStdMultiWidget::EnableColoredRectangles() { for(unsigned int i = 0; i < 4; ++i) { m_RectangleRendering[i]->Enable( GetDecorationColor(i)[0], GetDecorationColor(i)[1], GetDecorationColor(i)[2]); } } void QmitkStdMultiWidget::DisableColoredRectangles() { m_RectangleRendering[0]->Disable(); m_RectangleRendering[1]->Disable(); m_RectangleRendering[2]->Disable(); m_RectangleRendering[3]->Disable(); } bool QmitkStdMultiWidget::IsColoredRectanglesEnabled() const { return m_RectangleRendering[0]->IsEnabled(); } mitk::MouseModeSwitcher* QmitkStdMultiWidget::GetMouseModeSwitcher() { return m_MouseModeSwitcher; } void QmitkStdMultiWidget::MouseModeSelected( mitk::MouseModeSwitcher::MouseMode mouseMode ) { if ( mouseMode == 0 ) { this->EnableNavigationControllerEventListening(); } else { this->DisableNavigationControllerEventListening(); } } mitk::DataNode::Pointer QmitkStdMultiWidget::GetWidgetPlane1() { return this->m_PlaneNode1; } mitk::DataNode::Pointer QmitkStdMultiWidget::GetWidgetPlane2() { return this->m_PlaneNode2; } mitk::DataNode::Pointer QmitkStdMultiWidget::GetWidgetPlane3() { return this->m_PlaneNode3; } mitk::DataNode::Pointer QmitkStdMultiWidget::GetWidgetPlane(int id) { switch(id) { case 1: return this->m_PlaneNode1; break; case 2: return this->m_PlaneNode2; break; case 3: return this->m_PlaneNode3; break; default: return NULL; } } diff --git a/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/QmitkCmdLineModuleRunner.cpp b/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/QmitkCmdLineModuleRunner.cpp index 7168720ff5..b169038141 100644 --- a/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/QmitkCmdLineModuleRunner.cpp +++ b/Plugins/org.mitk.gui.qt.cmdlinemodules/src/internal/QmitkCmdLineModuleRunner.cpp @@ -1,655 +1,666 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) University College London (UCL). All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkCmdLineModuleRunner.h" #include "ui_QmitkCmdLineModuleProgressWidget.h" // Qt #include #include #include #include #include #include #include #include #include #include // CTK #include #include #include #include #include #include // MITK #include #include #include +#include #include #include "QmitkCmdLineModuleGui.h" //----------------------------------------------------------------------------- QmitkCmdLineModuleRunner::QmitkCmdLineModuleRunner(QWidget *parent) : QWidget(parent) , m_ModuleManager(NULL) , m_DataStorage(NULL) , m_UI(new Ui::QmitkCmdLineModuleProgressWidget) , m_Layout(NULL) , m_ModuleFrontEnd(NULL) , m_FutureWatcher(NULL) { m_UI->setupUi(this); m_UI->m_RemoveButton->setIcon(QApplication::style()->standardIcon(QStyle::SP_TitleBarCloseButton)); m_Layout = new QVBoxLayout(); m_Layout->setContentsMargins(0,0,0,0); m_Layout->setSpacing(0); m_UI->m_ParametersGroupBox->setLayout(m_Layout); qRegisterMetaType(); connect(m_UI->m_RemoveButton, SIGNAL(clicked()), this, SLOT(OnRemoveButtonClicked())); // Due to Qt bug 12152, we cannot listen to the "paused" signal because it is // not emitted directly when the QFuture is paused. Instead, it is emitted after // resuming the future, after the "resume" signal has been emitted... we use // a polling approach instead. connect(&m_PollPauseTimer, SIGNAL(timeout()), SLOT(OnCheckModulePaused())); m_PollPauseTimer.setInterval(300); m_PollPauseTimer.start(); } //----------------------------------------------------------------------------- QmitkCmdLineModuleRunner::~QmitkCmdLineModuleRunner() { if (m_ModuleFrontEnd != NULL) { delete m_ModuleFrontEnd; } this->ClearUpTemporaryFiles(); delete m_UI; } //----------------------------------------------------------------------------- void QmitkCmdLineModuleRunner::SetManager(ctkCmdLineModuleManager* manager) { this->m_ModuleManager = manager; } //----------------------------------------------------------------------------- void QmitkCmdLineModuleRunner::SetDataStorage(mitk::DataStorage* dataStorage) { this->m_DataStorage = dataStorage; } //----------------------------------------------------------------------------- void QmitkCmdLineModuleRunner::SetOutputDirectory(const QString& directoryName) { this->m_OutputDirectoryName = directoryName; } //----------------------------------------------------------------------------- QString QmitkCmdLineModuleRunner::GetTitle() { assert(m_ModuleFrontEnd); ctkCmdLineModuleReference reference = m_ModuleFrontEnd->moduleReference(); ctkCmdLineModuleDescription description = reference.description(); return description.title(); } //----------------------------------------------------------------------------- QString QmitkCmdLineModuleRunner::GetFullName() const { assert(m_ModuleFrontEnd); ctkCmdLineModuleReference reference = m_ModuleFrontEnd->moduleReference(); ctkCmdLineModuleDescription description = reference.description(); return description.categoryDotTitle(); } //----------------------------------------------------------------------------- QString QmitkCmdLineModuleRunner::GetValidNodeName(const QString& nodeName) const { QString outputName = nodeName; // We will allow A-Z, a-z, 0-9, period, hyphen and underscore in the output file name. // This method is parsing a node name, and other bits of code add on a file extension .nii. // So, in the output string from this function, we should not allow period, so that // the second recommendation on this page: // http://www.boost.org/doc/libs/1_43_0/libs/filesystem/doc/portability_guide.htm // is still true. QRegExp rx("[A-Z|a-z|0-9|-|_]{1,1}"); QString singleLetter; for (int i = 0; i < outputName.size(); i++) { if (i == 0 && outputName[i] == '-') { outputName[i] = '_'; } singleLetter = outputName[i]; if (!rx.exactMatch(singleLetter)) { outputName[i] = '-'; } } return outputName; } //----------------------------------------------------------------------------- bool QmitkCmdLineModuleRunner::IsStarted() const { bool isStarted = false; if (m_FutureWatcher != NULL && m_FutureWatcher->isStarted()) { isStarted = true; } return isStarted; } //----------------------------------------------------------------------------- void QmitkCmdLineModuleRunner::OnCheckModulePaused() { if (!this->IsStarted()) { return; } if (this->m_FutureWatcher->future().isPaused()) { if (!m_UI->m_PauseButton->isChecked()) { m_UI->m_PauseButton->setChecked(true); } } else { if (m_UI->m_PauseButton->isChecked()) { m_UI->m_PauseButton->setChecked(false); } } } //----------------------------------------------------------------------------- void QmitkCmdLineModuleRunner::OnPauseButtonToggled(bool toggled) { this->m_FutureWatcher->setPaused(toggled); if (toggled) { this->m_UI->m_ProgressTitle->setText(this->GetTitle() + ": paused"); } else { this->m_UI->m_ProgressTitle->setText(this->GetTitle() + ": resumed"); } } //----------------------------------------------------------------------------- void QmitkCmdLineModuleRunner::OnRemoveButtonClicked() { this->deleteLater(); } //----------------------------------------------------------------------------- void QmitkCmdLineModuleRunner::OnModuleStarted() { this->m_UI->m_ProgressBar->setMaximum(0); QString message = "started."; this->PublishMessage(message); emit started(); } //----------------------------------------------------------------------------- void QmitkCmdLineModuleRunner::OnModuleCanceled() { QString message = "cancelling."; this->PublishMessage(message); this->m_UI->m_PauseButton->setEnabled(false); this->m_UI->m_PauseButton->setChecked(false); this->m_UI->m_CancelButton->setEnabled(false); this->m_UI->m_RemoveButton->setEnabled(true); this->m_UI->m_ParametersGroupBox->setCollapsed(true); this->m_UI->m_ConsoleGroupBox->setCollapsed(true); this->m_UI->m_ProgressTitle->setText(this->GetTitle() + ": cancelled"); message = "cancelled."; this->PublishMessage(message); } //----------------------------------------------------------------------------- void QmitkCmdLineModuleRunner::OnModuleFinished() { this->m_UI->m_PauseButton->setEnabled(false); this->m_UI->m_PauseButton->setChecked(false); this->m_UI->m_CancelButton->setEnabled(false); this->m_UI->m_RemoveButton->setEnabled(true); if (!this->m_FutureWatcher->isCanceled()) { QString message = "finishing."; this->PublishMessage(message); // If no incremental results from stdout, try getting hold of the whole buffer and printing it. if (m_OutputCount == 0) { message = "Output channel is:"; this->PublishMessage(message); this->PublishByteArray(this->m_FutureWatcher->readAllOutputData()); } // If no incremental results from stderr, try getting hold of the whole buffer and printing it. if (m_ErrorCount == 0) { message = "Error channel is:"; this->PublishMessage(message); this->PublishByteArray(this->m_FutureWatcher->readAllErrorData()); } this->m_UI->m_ProgressTitle->setText(this->GetTitle() + ": finished"); this->LoadOutputData(); this->ClearUpTemporaryFiles(); message = "finished."; this->PublishMessage(message); } emit finished(); } //----------------------------------------------------------------------------- void QmitkCmdLineModuleRunner::OnModuleResumed() { this->m_UI->m_PauseButton->setChecked(false); } //----------------------------------------------------------------------------- void QmitkCmdLineModuleRunner::OnModuleProgressRangeChanged(int progressMin, int progressMax) { this->m_UI->m_ProgressBar->setMinimum(progressMin); this->m_UI->m_ProgressBar->setMaximum(progressMax); } //----------------------------------------------------------------------------- void QmitkCmdLineModuleRunner::OnModuleProgressTextChanged(const QString& progressText) { this->m_UI->m_Console->appendPlainText(progressText); } //----------------------------------------------------------------------------- void QmitkCmdLineModuleRunner::OnModuleProgressValueChanged(int progressValue) { this->m_UI->m_ProgressBar->setValue(progressValue); } //----------------------------------------------------------------------------- void QmitkCmdLineModuleRunner::OnOutputDataReady() { m_OutputCount++; this->PublishByteArray(this->m_FutureWatcher->readPendingOutputData()); } //----------------------------------------------------------------------------- void QmitkCmdLineModuleRunner::OnErrorDataReady() { m_ErrorCount++; this->PublishByteArray(this->m_FutureWatcher->readPendingErrorData()); } //----------------------------------------------------------------------------- void QmitkCmdLineModuleRunner::PublishMessage(const QString& message) { QString prefix = ""; // Can put additional prefix here if needed. QString outputMessage = prefix + message; qDebug() << outputMessage; this->m_UI->m_Console->appendPlainText(outputMessage); } //----------------------------------------------------------------------------- void QmitkCmdLineModuleRunner::PublishByteArray(const QByteArray& array) { QString message = array.data(); this->PublishMessage(message); } //----------------------------------------------------------------------------- void QmitkCmdLineModuleRunner::ClearUpTemporaryFiles() { QString message; QString fileName; foreach (QTemporaryFile* file, m_TemporaryFiles) { assert(file != NULL); fileName = file->fileName(); message = QObject::tr("removing %1").arg(fileName); this->PublishMessage(message); delete file; } m_TemporaryFiles.clear(); } //----------------------------------------------------------------------------- void QmitkCmdLineModuleRunner::LoadOutputData() { assert(m_DataStorage); - std::vector fileNames; - QString fileName; foreach (fileName, m_OutputDataToLoad) { - QString message = QObject::tr("loading %1").arg(fileName); - this->PublishMessage(message); + QString message; - fileNames.push_back(fileName.toStdString()); - } + try + { - if (fileNames.size() > 0) - { - int numberLoaded = mitk::IOUtil::LoadFiles(fileNames, *(m_DataStorage)); + mitk::IOUtil::LoadInfo info(fileName.toStdString()); + std::vector readers = info.m_ReaderSelector.Get(); + if (readers.size() > 0) + { + mitk::IOUtil::Load(fileName.toStdString(), *(m_DataStorage)); + message = QObject::tr("Loaded %1").arg(fileName); + } + else + { + message = QObject::tr("Not loading %1, as no IFileReader is available.").arg(fileName); + } + } + catch (const mitk::Exception& e) + { + message = QObject::tr("Failed to load %1, due to %2\n").arg(fileName).arg(e.what()); + MITK_ERROR << message.toStdString(); + } - QString message = QObject::tr("loaded %1 files").arg(numberLoaded); this->PublishMessage(message); } } //----------------------------------------------------------------------------- void QmitkCmdLineModuleRunner::SetFrontend(QmitkCmdLineModuleGui* frontEnd) { assert(frontEnd); assert(m_ModuleManager); assert(m_DataStorage); // We are assuming that this method is ONLY EVER CALLED ONCE. assert(!m_ModuleFrontEnd); // Assign the frontEnd to the member variable. m_ModuleFrontEnd = frontEnd; // We put the new GUI into the layout. m_Layout->insertWidget(0, m_ModuleFrontEnd->getGui()); // And configure a few other niceties. m_UI->m_ProgressTitle->setText(this->GetTitle()); m_UI->m_ConsoleGroupBox->setCollapsed(true); // We basically call SetFrontend then Run m_UI->m_ParametersGroupBox->setCollapsed(true); // so in practice the user will only want the progress bar. } //----------------------------------------------------------------------------- void QmitkCmdLineModuleRunner::Run() { assert(m_ModuleManager); assert(m_DataStorage); assert(m_ModuleFrontEnd); m_OutputDataToLoad.clear(); QString parameterName; QString message; QList parameters; ctkCmdLineModuleReference reference = m_ModuleFrontEnd->moduleReference(); ctkCmdLineModuleDescription description = reference.description(); // Check we have valid output. If at all possible, they should be somewhere writable. parameters = m_ModuleFrontEnd->parameters("image", ctkCmdLineModuleFrontend::Output); parameters << m_ModuleFrontEnd->parameters("file", ctkCmdLineModuleFrontend::Output); parameters << m_ModuleFrontEnd->parameters("geometry", ctkCmdLineModuleFrontend::Output); foreach (ctkCmdLineModuleParameter parameter, parameters) { parameterName = parameter.name(); QString outputFileName = m_ModuleFrontEnd->value(parameterName, ctkCmdLineModuleFrontend::DisplayRole).toString(); // Try to make sure we are not running in the application installation folder, // as more likely than not, it should not have write access, and you certainly // don't want users output files dumped there. // // eg. C:/Program Files (Windows), /Applications (Mac), /usr/local (Linux) etc. QFileInfo outputFileInfo(outputFileName); QString applicationDir = QApplication::applicationDirPath(); QString outputDir = outputFileInfo.dir().absolutePath(); if (applicationDir == outputDir) { qDebug() << "QmitkCmdLineModuleRunner::Run(), output folder = application folder, so will swap to defaultOutputDir, specified in CLI module preferences"; QFileInfo newOutputFileInfo(m_OutputDirectoryName, outputFileInfo.fileName()); QString newOutputFileAbsolutePath = newOutputFileInfo.absoluteFilePath(); qDebug() << "QmitkCmdLineModuleRunner::Run(), swapping " << outputFileName << " to " << newOutputFileAbsolutePath; QMessageBox msgBox; msgBox.setText("The output directory is the same as the application installation directory"); msgBox.setInformativeText(tr("Output file:\n%1\n\nwill be swapped to\n%2").arg(outputFileName).arg(newOutputFileAbsolutePath)); msgBox.setStandardButtons(QMessageBox::Ok); msgBox.setIcon(QMessageBox::Warning); msgBox.exec(); m_ModuleFrontEnd->setValue(parameterName, newOutputFileAbsolutePath, ctkCmdLineModuleFrontend::DisplayRole); } } // For each output image or file, store the filename, so we can auto-load it once the process finishes. foreach (ctkCmdLineModuleParameter parameter, parameters) { parameterName = parameter.name(); QString outputFileName = m_ModuleFrontEnd->value(parameterName, ctkCmdLineModuleFrontend::DisplayRole).toString(); if (!outputFileName.isEmpty()) { m_OutputDataToLoad.push_back(outputFileName); message = "Registered " + outputFileName + " to auto load upon completion."; this->PublishMessage(message); } } // For each input image, write a temporary file as a Nifti image (TODO - iterate through list of file formats). // and then save the full path name back on the parameter. message = "Saving image data to temporary storage..."; this->PublishMessage(message); parameters = m_ModuleFrontEnd->parameters("image", ctkCmdLineModuleFrontend::Input); foreach (ctkCmdLineModuleParameter parameter, parameters) { parameterName = parameter.name(); QVariant tmp = m_ModuleFrontEnd->value(parameterName, ctkCmdLineModuleFrontend::UserRole); mitk::DataNode::Pointer node = tmp.value(); if (node.IsNotNull()) { mitk::Image* image = dynamic_cast(node->GetData()); if (image != NULL) { QString errorMessage; QTemporaryFile* tempFile = this->SaveTemporaryImage(parameter, node.GetPointer(), errorMessage); if(tempFile == NULL) { QMessageBox::warning(this, "Saving temporary file failed", errorMessage); return; } m_TemporaryFiles.push_back(tempFile); m_ModuleFrontEnd->setValue(parameterName, tempFile->fileName()); message = "Saved " + tempFile->fileName(); this->PublishMessage(message); } // end if image } // end if node } // end foreach input image m_OutputCount = 0; m_ErrorCount = 0; // Now we run stuff. message = "starting."; this->PublishMessage(message); if (m_FutureWatcher == NULL) { m_FutureWatcher = new ctkCmdLineModuleFutureWatcher(); connect(m_FutureWatcher, SIGNAL(started()), SLOT(OnModuleStarted())); connect(m_FutureWatcher, SIGNAL(canceled()), SLOT(OnModuleCanceled())); connect(m_FutureWatcher, SIGNAL(finished()), SLOT(OnModuleFinished())); connect(m_FutureWatcher, SIGNAL(resumed()), SLOT(OnModuleResumed())); connect(m_FutureWatcher, SIGNAL(progressRangeChanged(int,int)), SLOT(OnModuleProgressRangeChanged(int,int))); connect(m_FutureWatcher, SIGNAL(progressTextChanged(QString)), SLOT(OnModuleProgressTextChanged(QString))); connect(m_FutureWatcher, SIGNAL(progressValueChanged(int)), SLOT(OnModuleProgressValueChanged(int))); connect(m_FutureWatcher, SIGNAL(outputDataReady()), SLOT(OnOutputDataReady())); connect(m_FutureWatcher, SIGNAL(errorDataReady()), SLOT(OnErrorDataReady())); connect(m_UI->m_CancelButton, SIGNAL(clicked()), m_FutureWatcher, SLOT(cancel())); connect(m_UI->m_PauseButton, SIGNAL(toggled(bool)), this, SLOT(OnPauseButtonToggled(bool))); } ctkCmdLineModuleFuture future = m_ModuleManager->run(m_ModuleFrontEnd); m_FutureWatcher->setFuture(future); m_UI->m_PauseButton->setEnabled(future.canPause()); m_UI->m_CancelButton->setEnabled(future.canCancel()); m_UI->m_RemoveButton->setEnabled(!future.isRunning()); // Give some immediate indication that we are running. m_UI->m_ProgressTitle->setText(description.title() + ": running"); } //----------------------------------------------------------------------------- QTemporaryFile* QmitkCmdLineModuleRunner::SaveTemporaryImage(const ctkCmdLineModuleParameter ¶meter, mitk::DataNode::ConstPointer node, QString& errorMessage) const { // Don't call this if node is null or node is not an image. assert(node.GetPointer()); mitk::Image* image = dynamic_cast(node->GetData()); assert(image); QString intermediateError; QString intermediateErrors; QTemporaryFile *returnedFile = NULL; QString name = this->GetValidNodeName(QString::fromStdString(node->GetName())); QString fileNameTemplate = name + "_XXXXXX"; // If no file extensions are specified, we default to .nii QStringList fileExts = parameter.fileExtensions(); if (fileExts.isEmpty()) { fileExts.push_back(".nii"); } // Try each extension until we get a good one. foreach (QString extension, fileExts) { // File extensions may or may not include the leading dot, so add one if necessary. if (!extension.startsWith(".")) { extension.prepend("."); } fileNameTemplate = fileNameTemplate + extension; try { QTemporaryFile *tempFile = new QTemporaryFile(QDir::tempPath() + QDir::separator() + fileNameTemplate); if (tempFile->open()) { tempFile->close(); if (mitk::IOUtil::SaveBaseData( image, tempFile->fileName().toStdString() )) { returnedFile = tempFile; break; } else { intermediateError = QObject::tr("Tried %1, failed to save image:\n%2\n").arg(extension).arg(tempFile->fileName()); } } else { intermediateError = QObject::tr("Tried %1, failed to open file:\n%2\n").arg(extension).arg(tempFile->fileName()); } } catch(const mitk::Exception &e) { intermediateError = QObject::tr("Tried %1, caught MITK Exception:\nDescription: %2\nFilename: %3\nLine: %4\n") .arg(extension).arg(e.GetDescription()).arg(e.GetFile()).arg(e.GetLine()); } catch(const std::exception& e) { intermediateError = QObject::tr("Tried %1, caught exception:\nDescription: %2\n") .arg(extension).arg(e.what()); } intermediateErrors += intermediateError; } errorMessage = intermediateErrors; return returnedFile; } diff --git a/Plugins/org.mitk.gui.qt.moviemaker/src/internal/QmitkScreenshotMaker.cpp b/Plugins/org.mitk.gui.qt.moviemaker/src/internal/QmitkScreenshotMaker.cpp index c70142c083..10942caf51 100644 --- a/Plugins/org.mitk.gui.qt.moviemaker/src/internal/QmitkScreenshotMaker.cpp +++ b/Plugins/org.mitk.gui.qt.moviemaker/src/internal/QmitkScreenshotMaker.cpp @@ -1,430 +1,437 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkScreenshotMaker.h" //#include "QmitkMovieMakerControls.h" #include "QmitkStepperAdapter.h" #include "QmitkStdMultiWidget.h" #include "mitkVtkPropRenderer.h" #include "mitkGlobalInteraction.h" #include #include #include #include #include #include #include #include #include #include #include #include "qapplication.h" #include "vtkImageWriter.h" #include "vtkJPEGWriter.h" #include "vtkPNGWriter.h" #include "vtkRenderLargeImage.h" #include "vtkRenderWindowInteractor.h" #include "vtkRenderer.h" #include "vtkTestUtilities.h" #include #include "vtkMitkRenderProp.h" #include #include #include "vtkRenderWindowInteractor.h" #include #include "mitkSliceNavigationController.h" #include "mitkPlanarFigure.h" QmitkScreenshotMaker::QmitkScreenshotMaker(QObject *parent, const char * /*name*/) : QmitkFunctionality(), m_Controls(NULL), m_SelectedNode(0), m_BackgroundColor(QColor(0,0,0)) { parentWidget = parent; } QmitkScreenshotMaker::~QmitkScreenshotMaker() { } void QmitkScreenshotMaker::CreateConnections() { if (m_Controls) { connect((QObject*) m_Controls->m_AllViews, SIGNAL(clicked()), (QObject*) this, SLOT(GenerateMultiplanar3DHighresScreenshot())); connect((QObject*) m_Controls->m_View1, SIGNAL(clicked()), (QObject*) this, SLOT(View1())); connect((QObject*) m_Controls->m_View2, SIGNAL(clicked()), (QObject*) this, SLOT(View2())); connect((QObject*) m_Controls->m_View3, SIGNAL(clicked()), (QObject*) this, SLOT(View3())); connect((QObject*) m_Controls->m_Shot, SIGNAL(clicked()), (QObject*) this, SLOT(GenerateMultiplanarScreenshots())); connect((QObject*) m_Controls->m_BackgroundColor, SIGNAL(clicked()), (QObject*) this, SLOT(SelectBackgroundColor())); connect((QObject*) m_Controls->btnScreenshot, SIGNAL(clicked()), this, SLOT(GenerateScreenshot())); connect((QObject*) m_Controls->m_HRScreenshot, SIGNAL(clicked()), this, SLOT(Generate3DHighresScreenshot())); QString styleSheet = "background-color:rgb(0,0,0)"; m_Controls->m_BackgroundColor->setStyleSheet(styleSheet); } } void QmitkScreenshotMaker::Activated() { QmitkFunctionality::Activated(); } void QmitkScreenshotMaker::Deactivated() { QmitkFunctionality::Deactivated(); } void QmitkScreenshotMaker::GenerateScreenshot() { if (m_LastFile.size()==0) m_LastFile = QDir::currentPath()+"/screenshot.png"; QString fileName = QFileDialog::getSaveFileName(NULL, "Save screenshot to...", m_LastFile, "PNG file (*.png);;JPEG file (*.jpg)"); if (fileName.size()>0) m_LastFile = fileName; vtkRenderer* renderer = mitk::GlobalInteraction::GetInstance()->GetFocus()->GetVtkRenderer(); if (renderer == NULL) return; this->TakeScreenshot(renderer, 1, fileName); } void QmitkScreenshotMaker::GenerateMultiplanarScreenshots() { if (m_LastPath.size()==0) m_LastPath = QDir::currentPath(); QString filePath = QFileDialog::getExistingDirectory(NULL, "Save screenshots to...", m_LastPath); if (filePath.size()>0) m_LastPath = filePath; if( filePath.isEmpty() ) { return; } //emit StartBlockControls(); + m_MultiWidget->SetCornerAnnotationVisibility(false); mitk::DataNode* n; QString fileName = "/axial.png"; int c = 1; while (QFile::exists(filePath+fileName)) { fileName = QString("/axial_"); fileName += QString::number(c); fileName += ".png"; c++; } vtkRenderer* renderer = m_MultiWidget->mitkWidget1->GetRenderer()->GetVtkRenderer(); if (renderer != NULL) this->TakeScreenshot(renderer, 1, filePath+fileName); fileName = "/sagittal.png"; c = 1; while (QFile::exists(filePath+fileName)) { fileName = QString("/sagittal_"); fileName += QString::number(c); fileName += ".png"; c++; } renderer = m_MultiWidget->mitkWidget2->GetRenderer()->GetVtkRenderer(); if (renderer != NULL) this->TakeScreenshot(renderer, 1, filePath+fileName); fileName = "/coronal.png"; c = 1; while (QFile::exists(filePath+fileName)) { fileName = QString("/coronal_"); fileName += QString::number(c); fileName += ".png"; c++; } renderer = m_MultiWidget->mitkWidget3->GetRenderer()->GetVtkRenderer(); if (renderer != NULL) this->TakeScreenshot(renderer, 1, filePath+fileName); n = this->m_MultiWidget->GetWidgetPlane1(); if(n) { n->SetProperty( "color", mitk::ColorProperty::New( 1,0,0 ) ); } n = this->m_MultiWidget->GetWidgetPlane2(); if(n) { n->SetProperty( "color", mitk::ColorProperty::New( 0,1,0 ) ); } n = this->m_MultiWidget->GetWidgetPlane3(); if(n) { n->SetProperty( "color", mitk::ColorProperty::New( 0,0,1 ) ); } + + m_MultiWidget->SetCornerAnnotationVisibility(true); } void QmitkScreenshotMaker::Generate3DHighresScreenshot() { if (m_LastFile.size()==0) m_LastFile = QDir::currentPath()+"/3D_screenshot.png"; QString fileName = QFileDialog::getSaveFileName(NULL, "Save screenshot to...", m_LastFile, "PNG file (*.png);;JPEG file (*.jpg)"); if (fileName.size()>0) m_LastFile = fileName; GenerateHR3DAtlasScreenshots(fileName); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkScreenshotMaker::GenerateMultiplanar3DHighresScreenshot() { if (m_LastPath.size()==0) m_LastPath = QDir::currentPath(); QString filePath = QFileDialog::getExistingDirectory( NULL, "Save screenshots to...", m_LastPath); if (filePath.size()>0) m_LastPath = filePath; if( filePath.isEmpty() ) { return; } QString fileName = "/3D_View1.png"; int c = 1; while (QFile::exists(filePath+fileName)) { fileName = QString("/3D_View1_"); fileName += QString::number(c); fileName += ".png"; c++; } GetCam()->Azimuth( -7.5 ); GetCam()->Roll(-4); GenerateHR3DAtlasScreenshots(filePath+fileName); GetCam()->Roll(4); fileName = "/3D_View2.png"; c = 1; while (QFile::exists(filePath+fileName)) { fileName = QString("/3D_View2_"); fileName += QString::number(c); fileName += ".png"; c++; } GetCam()->Azimuth( 90 ); GetCam()->Elevation( 4 ); GenerateHR3DAtlasScreenshots(filePath+fileName); fileName = "/3D_View3.png"; c = 1; while (QFile::exists(filePath+fileName)) { fileName = QString("/3D_View3_"); fileName += QString::number(c); fileName += ".png"; c++; } GetCam()->Elevation( 90 ); GetCam()->Roll( -2.5 ); GenerateHR3DAtlasScreenshots(filePath+fileName); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkScreenshotMaker::GenerateHR3DAtlasScreenshots(QString fileName) { // only works correctly for 3D RenderWindow + m_MultiWidget->SetCornerAnnotationVisibility(false); vtkRenderer* renderer = m_MultiWidget->mitkWidget4->GetRenderer()->GetVtkRenderer(); if (renderer == NULL) return; this->TakeScreenshot(renderer, this->m_Controls->m_MagFactor->text().toFloat(), fileName); + m_MultiWidget->SetCornerAnnotationVisibility(true); } vtkCamera* QmitkScreenshotMaker::GetCam() { mitk::BaseRenderer* renderer = mitk::BaseRenderer::GetInstance(GetActiveStdMultiWidget()->mitkWidget4->GetRenderWindow()); vtkCamera* cam = 0; const mitk::VtkPropRenderer *propRenderer = dynamic_cast( renderer ); if (propRenderer) { // get vtk renderer vtkRenderer* vtkrenderer = propRenderer->GetVtkRenderer(); if (vtkrenderer) { // get vtk camera vtkCamera* vtkcam = vtkrenderer->GetActiveCamera(); if (vtkcam) { // vtk smart pointer handling cam = vtkcam; cam->Register( NULL ); } } } return cam; } void QmitkScreenshotMaker::View1() { GetCam()->Elevation( 45 ); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkScreenshotMaker::View2() { GetCam()->Azimuth(45); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkScreenshotMaker::View3() { GetCam()->Roll(45); mitk::RenderingManager::GetInstance()->RequestUpdateAll(); } void QmitkScreenshotMaker::OnSelectionChanged( std::vector nodes ) { if(nodes.size()) m_SelectedNode = nodes[0]; } void QmitkScreenshotMaker::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { m_Controls = new Ui::QmitkScreenshotMakerControls; m_Controls->setupUi(parent); // Initialize "Selected Window" combo box const mitk::RenderingManager::RenderWindowVector rwv = mitk::RenderingManager::GetInstance()->GetAllRegisteredRenderWindows(); } this->CreateConnections(); } void QmitkScreenshotMaker::StdMultiWidgetAvailable(QmitkStdMultiWidget& stdMultiWidget) { m_MultiWidget = &stdMultiWidget; m_Parent->setEnabled(true); } void QmitkScreenshotMaker::StdMultiWidgetNotAvailable() { m_MultiWidget = NULL; m_Parent->setEnabled(false); } void QmitkScreenshotMaker::TakeScreenshot(vtkRenderer* renderer, unsigned int magnificationFactor, QString fileName) { if ((renderer == NULL) ||(magnificationFactor < 1) || fileName.isEmpty()) return; bool doubleBuffering( renderer->GetRenderWindow()->GetDoubleBuffer() ); renderer->GetRenderWindow()->DoubleBufferOff(); vtkImageWriter* fileWriter; QFileInfo fi(fileName); QString suffix = fi.suffix(); if (suffix.compare("jpg", Qt::CaseInsensitive) == 0) { vtkJPEGWriter* w = vtkJPEGWriter::New(); w->SetQuality(100); w->ProgressiveOff(); fileWriter = w; } else // default is png { fileWriter = vtkPNGWriter::New(); } vtkRenderLargeImage* magnifier = vtkRenderLargeImage::New(); magnifier->SetInput(renderer); magnifier->SetMagnification(magnificationFactor); //magnifier->Update(); fileWriter->SetInputConnection(magnifier->GetOutputPort()); fileWriter->SetFileName(fileName.toLatin1()); // vtkRenderLargeImage has problems with different layers, therefore we have to // temporarily deactivate all other layers. // we set the background to white, because it is nicer than black... double oldBackground[3]; renderer->GetBackground(oldBackground); // QColor color = QColorDialog::getColor(); double bgcolor[] = {m_BackgroundColor.red()/255.0, m_BackgroundColor.green()/255.0, m_BackgroundColor.blue()/255.0}; renderer->SetBackground(bgcolor); m_MultiWidget->DisableColoredRectangles(); m_MultiWidget->DisableDepartmentLogo(); m_MultiWidget->DisableGradientBackground(); + m_MultiWidget->SetCornerAnnotationVisibility(false); m_MultiWidget->mitkWidget1->ActivateMenuWidget( false ); m_MultiWidget->mitkWidget2->ActivateMenuWidget( false ); m_MultiWidget->mitkWidget3->ActivateMenuWidget( false ); m_MultiWidget->mitkWidget4->ActivateMenuWidget( false ); fileWriter->Write(); fileWriter->Delete(); m_MultiWidget->mitkWidget1->ActivateMenuWidget( true, m_MultiWidget ); m_MultiWidget->mitkWidget2->ActivateMenuWidget( true, m_MultiWidget ); m_MultiWidget->mitkWidget3->ActivateMenuWidget( true, m_MultiWidget ); m_MultiWidget->mitkWidget4->ActivateMenuWidget( true, m_MultiWidget ); m_MultiWidget->EnableColoredRectangles(); m_MultiWidget->EnableDepartmentLogo(); m_MultiWidget->EnableGradientBackground(); + m_MultiWidget->SetCornerAnnotationVisibility(true); renderer->SetBackground(oldBackground); renderer->GetRenderWindow()->SetDoubleBuffer(doubleBuffering); } void QmitkScreenshotMaker::SelectBackgroundColor() { m_BackgroundColor = QColorDialog::getColor(); m_Controls->m_BackgroundColor->setAutoFillBackground(true); QString styleSheet = "background-color:rgb("; styleSheet.append(QString::number(m_BackgroundColor.red())); styleSheet.append(","); styleSheet.append(QString::number(m_BackgroundColor.green())); styleSheet.append(","); styleSheet.append(QString::number(m_BackgroundColor.blue())); styleSheet.append(")"); m_Controls->m_BackgroundColor->setStyleSheet(styleSheet); } diff --git a/SuperBuild.cmake b/SuperBuild.cmake index 0f9565369c..2f8868a167 100644 --- a/SuperBuild.cmake +++ b/SuperBuild.cmake @@ -1,432 +1,444 @@ include(mitkFunctionInstallExternalCMakeProject) #----------------------------------------------------------------------------- # Convenient macro allowing to download a file #----------------------------------------------------------------------------- if(NOT MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL) set(MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL http://mitk.org/download/thirdparty) endif() macro(downloadFile url dest) file(DOWNLOAD ${url} ${dest} STATUS status) list(GET status 0 error_code) list(GET status 1 error_msg) if(error_code) message(FATAL_ERROR "error: Failed to download ${url} - ${error_msg}") endif() endmacro() #----------------------------------------------------------------------------- # MITK Prerequisites #----------------------------------------------------------------------------- if(UNIX AND NOT APPLE) include(mitkFunctionCheckPackageHeader) # Check for libxt-dev mitkFunctionCheckPackageHeader(StringDefs.h libxt-dev /usr/include/X11/) # Check for libtiff4-dev mitkFunctionCheckPackageHeader(tiff.h libtiff4-dev) # Check for libwrap0-dev mitkFunctionCheckPackageHeader(tcpd.h libwrap0-dev) endif() # We need a proper patch program. On Linux and MacOS, we assume # that "patch" is available. On Windows, we download patch.exe # if not patch program is found. find_program(PATCH_COMMAND patch) if((NOT PATCH_COMMAND OR NOT EXISTS ${PATCH_COMMAND}) AND WIN32) downloadFile(${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/patch.exe ${CMAKE_CURRENT_BINARY_DIR}/patch.exe) find_program(PATCH_COMMAND patch ${CMAKE_CURRENT_BINARY_DIR}) endif() if(NOT PATCH_COMMAND) message(FATAL_ERROR "No patch program found.") endif() #----------------------------------------------------------------------------- # Qt options for external projects and MITK #----------------------------------------------------------------------------- if(MITK_USE_QT) set(qt_project_args -DDESIRED_QT_VERSION:STRING=${DESIRED_QT_VERSION}) else() set(qt_project_args ) endif() if(MITK_USE_Qt4) list(APPEND qt_project_args -DQT_QMAKE_EXECUTABLE:FILEPATH=${QT_QMAKE_EXECUTABLE} ) endif() #----------------------------------------------------------------------------- # ExternalProjects #----------------------------------------------------------------------------- get_property(external_projects GLOBAL PROPERTY MITK_EXTERNAL_PROJECTS) +if(MITK_CTEST_SCRIPT_MODE) + # Write a file containing the list of enabled external project targets. + # This file can be read by a ctest script to separately build projects. + set(SUPERBUILD_TARGETS ) + foreach(proj ${external_projects}) + if(MITK_USE_${proj}) + list(APPEND SUPERBUILD_TARGETS ${proj}) + endif() + endforeach() + file(WRITE "${CMAKE_BINARY_DIR}/SuperBuildTargets.cmake" "set(SUPERBUILD_TARGETS ${SUPERBUILD_TARGETS})") +endif() + # A list of "nice" external projects, playing well together with CMake set(nice_external_projects ${external_projects}) list(REMOVE_ITEM nice_external_projects Boost Python) foreach(proj ${nice_external_projects}) if(MITK_USE_${proj}) set(EXTERNAL_${proj}_DIR "${${proj}_DIR}" CACHE PATH "Path to ${proj} build directory") mark_as_advanced(EXTERNAL_${proj}_DIR) if(EXTERNAL_${proj}_DIR) set(${proj}_DIR ${EXTERNAL_${proj}_DIR}) endif() endif() endforeach() if(MITK_USE_Boost) set(EXTERNAL_BOOST_ROOT "${BOOST_ROOT}" CACHE PATH "Path to Boost directory") mark_as_advanced(EXTERNAL_BOOST_ROOT) if(EXTERNAL_BOOST_ROOT) set(BOOST_ROOT ${EXTERNAL_BOOST_ROOT}) endif() endif() # Setup file for setting custom ctest vars configure_file( CMake/SuperbuildCTestCustom.cmake.in ${MITK_BINARY_DIR}/CTestCustom.cmake @ONLY ) if(BUILD_TESTING) set(EXTERNAL_MITK_DATA_DIR "${MITK_DATA_DIR}" CACHE PATH "Path to the MITK data directory") mark_as_advanced(EXTERNAL_MITK_DATA_DIR) if(EXTERNAL_MITK_DATA_DIR) set(MITK_DATA_DIR ${EXTERNAL_MITK_DATA_DIR}) endif() endif() # Look for git early on, if needed if((BUILD_TESTING AND NOT EXTERNAL_MITK_DATA_DIR) OR (MITK_USE_CTK AND NOT EXTERNAL_CTK_DIR)) find_package(Git REQUIRED) endif() #----------------------------------------------------------------------------- # External project settings #----------------------------------------------------------------------------- include(ExternalProject) set(ep_prefix "${CMAKE_BINARY_DIR}/ep") set_property(DIRECTORY PROPERTY EP_PREFIX ${ep_prefix}) # Compute -G arg for configuring external projects with the same CMake generator: if(CMAKE_EXTRA_GENERATOR) set(gen "${CMAKE_EXTRA_GENERATOR} - ${CMAKE_GENERATOR}") else() set(gen "${CMAKE_GENERATOR}") endif() # Use this value where semi-colons are needed in ep_add args: set(sep "^^") ## if(MSVC_VERSION) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /bigobj /MP") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /bigobj /MP") endif() # This is a workaround for passing linker flags # actually down to the linker invocation set(_cmake_required_flags_orig ${CMAKE_REQUIRED_FLAGS}) set(CMAKE_REQUIRED_FLAGS "-Wl,-rpath") mitkFunctionCheckCompilerFlags(${CMAKE_REQUIRED_FLAGS} _has_rpath_flag) set(CMAKE_REQUIRED_FLAGS ${_cmake_required_flags_orig}) set(_install_rpath_linkflag ) if(_has_rpath_flag) if(APPLE) set(_install_rpath_linkflag "-Wl,-rpath,@loader_path/../lib") else() set(_install_rpath_linkflag "-Wl,-rpath='$ORIGIN/../lib'") endif() endif() set(_install_rpath) if(APPLE) set(_install_rpath "@loader_path/../lib") elseif(UNIX) # this work for libraries as well as executables set(_install_rpath "\$ORIGIN/../lib") endif() set(ep_common_args -DCMAKE_CXX_EXTENSIONS:STRING=${CMAKE_CXX_EXTENSIONS} -DCMAKE_CXX_STANDARD:STRING=${CMAKE_CXX_STANDARD} -DCMAKE_CXX_STANDARD_REQUIRED:BOOL=${CMAKE_CXX_STANDARD_REQUIRED} -DCMAKE_DEBUG_POSTFIX:STRING=d -DCMAKE_MACOSX_RPATH:BOOL=TRUE "-DCMAKE_INSTALL_RPATH:STRING=${_install_rpath}" -DBUILD_TESTING:BOOL=OFF -DCMAKE_INSTALL_PREFIX:PATH= "-DCMAKE_PREFIX_PATH:PATH=^^${CMAKE_PREFIX_PATH}" -DCMAKE_INCLUDE_PATH:PATH=${CMAKE_INCLUDE_PATH} -DCMAKE_LIBRARY_PATH:PATH=${CMAKE_LIBRARY_PATH} -DBUILD_SHARED_LIBS:BOOL=ON -DCMAKE_BUILD_TYPE:STRING=${CMAKE_BUILD_TYPE} -DCMAKE_C_COMPILER:FILEPATH=${CMAKE_C_COMPILER} -DCMAKE_CXX_COMPILER:FILEPATH=${CMAKE_CXX_COMPILER} -DCMAKE_C_FLAGS:STRING=${CMAKE_C_FLAGS} "-DCMAKE_CXX_FLAGS:STRING=${CMAKE_CXX_FLAGS} ${MITK_CXX11_FLAG}" #debug flags -DCMAKE_CXX_FLAGS_DEBUG:STRING=${CMAKE_CXX_FLAGS_DEBUG} -DCMAKE_C_FLAGS_DEBUG:STRING=${CMAKE_C_FLAGS_DEBUG} #release flags -DCMAKE_CXX_FLAGS_RELEASE:STRING=${CMAKE_CXX_FLAGS_RELEASE} -DCMAKE_C_FLAGS_RELEASE:STRING=${CMAKE_C_FLAGS_RELEASE} #relwithdebinfo -DCMAKE_CXX_FLAGS_RELWITHDEBINFO:STRING=${CMAKE_CXX_FLAGS_RELWITHDEBINFO} -DCMAKE_C_FLAGS_RELWITHDEBINFO:STRING=${CMAKE_C_FLAGS_RELWITHDEBINFO} #link flags -DCMAKE_EXE_LINKER_FLAGS:STRING=${CMAKE_EXE_LINKER_FLAGS} -DCMAKE_SHARED_LINKER_FLAGS:STRING=${CMAKE_SHARED_LINKER_FLAGS} -DCMAKE_MODULE_LINKER_FLAGS:STRING=${CMAKE_MODULE_LINKER_FLAGS} ) # Pass the CMAKE_OSX variables to external projects if(APPLE) set(MAC_OSX_ARCHITECTURE_ARGS -DCMAKE_OSX_ARCHITECTURES:PATH=${CMAKE_OSX_ARCHITECTURES} -DCMAKE_OSX_DEPLOYMENT_TARGET:PATH=${CMAKE_OSX_DEPLOYMENT_TARGET} -DCMAKE_OSX_SYSROOT:PATH=${CMAKE_OSX_SYSROOT} ) set(ep_common_args ${MAC_OSX_ARCHITECTURE_ARGS} ${ep_common_args} ) endif() set(mitk_superbuild_ep_args) set(mitk_depends ) # Include external projects include(CMakeExternals/MITKData.cmake) foreach(p ${external_projects}) include(CMakeExternals/${p}.cmake) list(APPEND mitk_superbuild_ep_args -DMITK_USE_${p}:BOOL=${MITK_USE_${p}} ) get_property(_package GLOBAL PROPERTY MITK_${p}_PACKAGE) if(_package) list(APPEND mitk_superbuild_ep_args -D${p}_DIR:PATH=${${p}_DIR}) endif() list(APPEND mitk_depends ${${p}_DEPENDS}) endforeach() #----------------------------------------------------------------------------- # Set superbuild boolean args #----------------------------------------------------------------------------- set(mitk_cmake_boolean_args BUILD_SHARED_LIBS WITH_COVERAGE BUILD_TESTING MITK_BUILD_ALL_PLUGINS MITK_BUILD_ALL_APPS MITK_BUILD_TUTORIAL # Deprecated. Use MITK_BUILD_EXAMPLES instead MITK_BUILD_EXAMPLES MITK_USE_QT MITK_USE_SYSTEM_Boost MITK_USE_BLUEBERRY MITK_USE_OpenCL MITK_ENABLE_PIC_READER ) #----------------------------------------------------------------------------- # Create the final variable containing superbuild boolean args #----------------------------------------------------------------------------- set(mitk_superbuild_boolean_args) foreach(mitk_cmake_arg ${mitk_cmake_boolean_args}) list(APPEND mitk_superbuild_boolean_args -D${mitk_cmake_arg}:BOOL=${${mitk_cmake_arg}}) endforeach() if(MITK_BUILD_ALL_PLUGINS) list(APPEND mitk_superbuild_boolean_args -DBLUEBERRY_BUILD_ALL_PLUGINS:BOOL=ON) endif() #----------------------------------------------------------------------------- # MITK Utilities #----------------------------------------------------------------------------- set(proj MITK-Utilities) ExternalProject_Add(${proj} DOWNLOAD_COMMAND "" CONFIGURE_COMMAND "" BUILD_COMMAND "" INSTALL_COMMAND "" DEPENDS ${mitk_depends} ) #----------------------------------------------------------------------------- # Additional MITK CXX/C Flags #----------------------------------------------------------------------------- set(MITK_ADDITIONAL_C_FLAGS "" CACHE STRING "Additional C Flags for MITK") set(MITK_ADDITIONAL_C_FLAGS_RELEASE "" CACHE STRING "Additional Release C Flags for MITK") set(MITK_ADDITIONAL_C_FLAGS_DEBUG "" CACHE STRING "Additional Debug C Flags for MITK") mark_as_advanced(MITK_ADDITIONAL_C_FLAGS MITK_ADDITIONAL_C_FLAGS_DEBUG MITK_ADDITIONAL_C_FLAGS_RELEASE) set(MITK_ADDITIONAL_CXX_FLAGS "" CACHE STRING "Additional CXX Flags for MITK") set(MITK_ADDITIONAL_CXX_FLAGS_RELEASE "" CACHE STRING "Additional Release CXX Flags for MITK") set(MITK_ADDITIONAL_CXX_FLAGS_DEBUG "" CACHE STRING "Additional Debug CXX Flags for MITK") mark_as_advanced(MITK_ADDITIONAL_CXX_FLAGS MITK_ADDITIONAL_CXX_FLAGS_DEBUG MITK_ADDITIONAL_CXX_FLAGS_RELEASE) set(MITK_ADDITIONAL_EXE_LINKER_FLAGS "" CACHE STRING "Additional exe linker flags for MITK") set(MITK_ADDITIONAL_SHARED_LINKER_FLAGS "" CACHE STRING "Additional shared linker flags for MITK") set(MITK_ADDITIONAL_MODULE_LINKER_FLAGS "" CACHE STRING "Additional module linker flags for MITK") mark_as_advanced(MITK_ADDITIONAL_EXE_LINKER_FLAGS MITK_ADDITIONAL_SHARED_LINKER_FLAGS MITK_ADDITIONAL_MODULE_LINKER_FLAGS) #----------------------------------------------------------------------------- # MITK Configure #----------------------------------------------------------------------------- if(MITK_INITIAL_CACHE_FILE) set(mitk_initial_cache_arg -C "${MITK_INITIAL_CACHE_FILE}") endif() set(mitk_optional_cache_args ) foreach(type RUNTIME ARCHIVE LIBRARY) if(DEFINED CTK_PLUGIN_${type}_OUTPUT_DIRECTORY) list(APPEND mitk_optional_cache_args -DCTK_PLUGIN_${type}_OUTPUT_DIRECTORY:PATH=${CTK_PLUGIN_${type}_OUTPUT_DIRECTORY}) endif() endforeach() # Optional python variables if(MITK_USE_Python) list(APPEND mitk_optional_cache_args -DMITK_USE_Python:BOOL=${MITK_USE_Python} -DPYTHON_EXECUTABLE:FILEPATH=${PYTHON_EXECUTABLE} -DPYTHON_INCLUDE_DIR:PATH=${PYTHON_INCLUDE_DIR} -DPYTHON_LIBRARY:FILEPATH=${PYTHON_LIBRARY} -DPYTHON_INCLUDE_DIR2:PATH=${PYTHON_INCLUDE_DIR2} -DMITK_USE_SYSTEM_PYTHON:BOOL=${MITK_USE_SYSTEM_PYTHON} ) endif() set(proj MITK-Configure) ExternalProject_Add(${proj} LIST_SEPARATOR ${sep} DOWNLOAD_COMMAND "" CMAKE_GENERATOR ${gen} CMAKE_CACHE_ARGS # --------------- Build options ---------------- -DCMAKE_INSTALL_PREFIX:PATH=${CMAKE_INSTALL_PREFIX} -DCMAKE_BUILD_TYPE:STRING=${CMAKE_BUILD_TYPE} # --------------- Compile options ---------------- -DCMAKE_C_COMPILER:FILEPATH=${CMAKE_C_COMPILER} -DCMAKE_CXX_COMPILER:FILEPATH=${CMAKE_CXX_COMPILER} "-DCMAKE_C_FLAGS:STRING=${CMAKE_C_FLAGS} ${MITK_ADDITIONAL_C_FLAGS}" "-DCMAKE_CXX_FLAGS:STRING=${CMAKE_CXX_FLAGS} ${MITK_ADDITIONAL_CXX_FLAGS}" # debug flags "-DCMAKE_CXX_FLAGS_DEBUG:STRING=${CMAKE_CXX_FLAGS_DEBUG} ${MITK_ADDITIONAL_CXX_FLAGS_DEBUG}" "-DCMAKE_C_FLAGS_DEBUG:STRING=${CMAKE_C_FLAGS_DEBUG} ${MITK_ADDITIONAL_C_FLAGS_DEBUG}" # release flags "-DCMAKE_CXX_FLAGS_RELEASE:STRING=${CMAKE_CXX_FLAGS_RELEASE} ${MITK_ADDITIONAL_CXX_FLAGS_RELEASE}" "-DCMAKE_C_FLAGS_RELEASE:STRING=${CMAKE_C_FLAGS_RELEASE} ${MITK_ADDITIONAL_C_FLAGS_RELEASE}" # relwithdebinfo -DCMAKE_CXX_FLAGS_RELWITHDEBINFO:STRING=${CMAKE_CXX_FLAGS_RELWITHDEBINFO} -DCMAKE_C_FLAGS_RELWITHDEBINFO:STRING=${CMAKE_C_FLAGS_RELWITHDEBINFO} # link flags "-DCMAKE_EXE_LINKER_FLAGS:STRING=${CMAKE_EXE_LINKER_FLAGS} ${MITK_ADDITIONAL_EXE_LINKER_FLAGS}" "-DCMAKE_SHARED_LINKER_FLAGS:STRING=${CMAKE_SHARED_LINKER_FLAGS} ${MITK_ADDITIONAL_SHARED_LINKER_FLAGS}" "-DCMAKE_MODULE_LINKER_FLAGS:STRING=${CMAKE_MODULE_LINKER_FLAGS} ${MITK_ADDITIONAL_MODULE_LINKER_FLAGS}" # Output directories -DMITK_CMAKE_LIBRARY_OUTPUT_DIRECTORY:PATH=${MITK_CMAKE_LIBRARY_OUTPUT_DIRECTORY} -DMITK_CMAKE_RUNTIME_OUTPUT_DIRECTORY:PATH=${MITK_CMAKE_RUNTIME_OUTPUT_DIRECTORY} -DMITK_CMAKE_ARCHIVE_OUTPUT_DIRECTORY:PATH=${MITK_CMAKE_ARCHIVE_OUTPUT_DIRECTORY} # ------------- Boolean build options -------------- ${mitk_superbuild_boolean_args} ${mitk_optional_cache_args} -DMITK_USE_SUPERBUILD:BOOL=OFF -DMITK_BUILD_CONFIGURATION:STRING=${MITK_BUILD_CONFIGURATION} -DCTEST_USE_LAUNCHERS:BOOL=${CTEST_USE_LAUNCHERS} # ----------------- Miscellaneous --------------- -DCMAKE_LIBRARY_PATH:PATH=${CMAKE_LIBRARY_PATH} -DCMAKE_INCLUDE_PATH:PATH=${CMAKE_INCLUDE_PATH} -DMITK_CTEST_SCRIPT_MODE:STRING=${MITK_CTEST_SCRIPT_MODE} -DMITK_SUPERBUILD_BINARY_DIR:PATH=${MITK_BINARY_DIR} -DMITK_MODULES_TO_BUILD:INTERNAL=${MITK_MODULES_TO_BUILD} -DMITK_WHITELIST:STRING=${MITK_WHITELIST} -DMITK_WHITELISTS_EXTERNAL_PATH:STRING=${MITK_WHITELISTS_EXTERNAL_PATH} -DMITK_WHITELISTS_INTERNAL_PATH:STRING=${MITK_WHITELISTS_INTERNAL_PATH} ${qt_project_args} -DMITK_ACCESSBYITK_INTEGRAL_PIXEL_TYPES:STRING=${MITK_ACCESSBYITK_INTEGRAL_PIXEL_TYPES} -DMITK_ACCESSBYITK_FLOATING_PIXEL_TYPES:STRING=${MITK_ACCESSBYITK_FLOATING_PIXEL_TYPES} -DMITK_ACCESSBYITK_COMPOSITE_PIXEL_TYPES:STRING=${MITK_ACCESSBYITK_COMPOSITE_PIXEL_TYPES} -DMITK_ACCESSBYITK_VECTOR_PIXEL_TYPES:STRING=${MITK_ACCESSBYITK_VECTOR_PIXEL_TYPES} -DMITK_ACCESSBYITK_DIMENSIONS:STRING=${MITK_ACCESSBYITK_DIMENSIONS} # --------------- External project options --------------- -DMITK_DATA_DIR:PATH=${MITK_DATA_DIR} -DMITK_EXTERNAL_PROJECT_PREFIX:PATH=${ep_prefix} -DCppMicroServices_DIR:PATH=${CppMicroServices_DIR} -DMITK_KWSTYLE_EXECUTABLE:FILEPATH=${MITK_KWSTYLE_EXECUTABLE} -DDCMTK_CMAKE_DEBUG_POSTFIX:STRING=d -DBOOST_ROOT:PATH=${BOOST_ROOT} -DBOOST_LIBRARYDIR:PATH=${BOOST_LIBRARYDIR} -DMITK_USE_Boost_LIBRARIES:STRING=${MITK_USE_Boost_LIBRARIES} CMAKE_ARGS ${mitk_initial_cache_arg} ${MAC_OSX_ARCHITECTURE_ARGS} ${mitk_superbuild_ep_args} "-DCMAKE_PREFIX_PATH:PATH=${ep_prefix}${sep}${CMAKE_PREFIX_PATH}" SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR} BINARY_DIR ${CMAKE_BINARY_DIR}/MITK-build BUILD_COMMAND "" INSTALL_COMMAND "" DEPENDS MITK-Utilities ) mitkFunctionInstallExternalCMakeProject(${proj}) #----------------------------------------------------------------------------- # MITK #----------------------------------------------------------------------------- if(CMAKE_GENERATOR MATCHES ".*Makefiles.*") set(mitk_build_cmd "$(MAKE)") else() set(mitk_build_cmd ${CMAKE_COMMAND} --build ${CMAKE_CURRENT_BINARY_DIR}/MITK-build --config ${CMAKE_CFG_INTDIR}) endif() if(NOT DEFINED SUPERBUILD_EXCLUDE_MITKBUILD_TARGET OR NOT SUPERBUILD_EXCLUDE_MITKBUILD_TARGET) set(MITKBUILD_TARGET_ALL_OPTION "ALL") else() set(MITKBUILD_TARGET_ALL_OPTION "") endif() add_custom_target(MITK-build ${MITKBUILD_TARGET_ALL_OPTION} COMMAND ${mitk_build_cmd} WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/MITK-build DEPENDS MITK-Configure ) #----------------------------------------------------------------------------- # Custom target allowing to drive the build of the MITK project itself #----------------------------------------------------------------------------- add_custom_target(MITK COMMAND ${mitk_build_cmd} WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/MITK-build ) diff --git a/Utilities/mbilog/mbilogTextBackendBase.cpp b/Utilities/mbilog/mbilogTextBackendBase.cpp index 7a095ec690..5f7c74b68b 100644 --- a/Utilities/mbilog/mbilogTextBackendBase.cpp +++ b/Utilities/mbilog/mbilogTextBackendBase.cpp @@ -1,572 +1,573 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mbilogTextBackendBase.h" #include "mbilogLoggingTypes.h" #include #include #include #include #ifdef _WIN32 #define USE_WIN32COLOREDCONSOLE #include + #include "mbilogTextDictionary.h" #endif static bool g_init=false; mbilog::TextBackendBase::~TextBackendBase() {} #ifdef USE_WIN32COLOREDCONSOLE static HANDLE g_hConsole; class AutoCategorize { protected: std::vector path; std::string current,category; int pos; void flush() { if(current.size()>0) { if(current.compare("..")==0) { if(path.size()>0) path.pop_back(); } else { path.push_back(current); } current=""; } } std::string simplify(std::string x) { bool redo; std::string lft(""),rgt(""); do { redo=false; for(int r=0; r < sizeof(mbilog::replace)/sizeof(char*); r+=2) { int s = static_cast( strlen(mbilog::replace[r]) ); int xs = static_cast( x.size() ); if(xs==s) { if( mbilog::replace[r+1][0] || !lft.empty() || !rgt.empty() ) if(x.compare(mbilog::replace[r])==0) x=mbilog::replace[r+1]; } else if(xs>s) { if(strncmp(mbilog::replace[r],&x.c_str()[xs-s],s)==0) { std::string rp = mbilog::replace[r+1]; if(!rp.empty()) rp[0]=toupper(rp[0]); x = x.substr(0,xs-s); rgt = rp + rgt; redo=true; } else if(strncmp(mbilog::replace[r],x.c_str(),s)==0) { std::string rp = mbilog::replace[r+1]; if(!rp.empty()) rp[0]=toupper(rp[0]); x=x.substr(s,xs-s); lft = lft + rp; redo=true; } } } } while(redo); x[0]=toupper(x[0]); x=lft+x+rgt; x[0]=tolower(x[0]); return x; } std::string concat(std::string a,std::string b,bool opt) { int as = static_cast( a.size() ); int bs = static_cast( b.size() ); if(opt && as <= bs) { if (as==bs && a.compare(b)==0) return a; if(strncmp(a.c_str(),b.c_str(),as)==0) { b=b.substr(as,bs-as); b[0]=tolower(b[0]); } } return a+"."+b; } bool search2p2(char *a,char *b,bool optimize=true) { int size = static_cast( path.size() ) - 3; for(int r=0;r( path.size() ) - 2; for(int r=0;r( path.size() ) - 2; for(int r=0;r( strlen(l.filePath) ); current = ""; for(int r = 0;r>> " << std::flush; ChangeColor( colorNormal ); std::cout << std::endl; */ // Give out start time ChangeColor( colorTime ); AppendTimeStamp(std::cout); std::cout << std::endl; } switch(l.level) { case mbilog::Info: break; case mbilog::Warn: colorTime = FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_INTENSITY; //colorText = FOREGROUND_RED|FOREGROUND_GREEN; colorCat = FOREGROUND_BLUE | FOREGROUND_RED | FOREGROUND_INTENSITY; showColon = false; forceCat = true; break; case mbilog::Error: colorTime = FOREGROUND_RED|FOREGROUND_INTENSITY; //colorText = FOREGROUND_RED; colorCat = FOREGROUND_BLUE | FOREGROUND_RED | FOREGROUND_INTENSITY; showColon = false; forceCat = true; break; case mbilog::Fatal: colorTime = FOREGROUND_RED|FOREGROUND_BLUE|FOREGROUND_INTENSITY; //colorText = FOREGROUND_RED|FOREGROUND_BLUE|FOREGROUND_INTENSITY; colorCat = FOREGROUND_BLUE | FOREGROUND_RED | FOREGROUND_INTENSITY; showColon = false; forceCat = true; break; case mbilog::Debug: colorTime = FOREGROUND_BLUE|FOREGROUND_INTENSITY; //colorText |= FOREGROUND_INTENSITY; showColon = false; break; } ChangeColor( colorTime ); std::locale C("C"); std::locale originalLocale = std::cout.getloc(); std::cout.imbue(C); std::cout << std::fixed << std::setprecision(2) << ((double)std::clock())/CLOCKS_PER_SEC << " "; std::cout.imbue( originalLocale ); // category { AutoCategorize ac(l); std::string pre=ac.GetPrefix(); std::string cat=ac.GetCategory(); cat = pre + cat; if(cat.empty()) cat = l.category; if(!cat.empty()) { ChangeColor( colorCat ); // static std::string lastCat; // if(forceCat||lastCat.compare(cat)) { std::cout << cat << std::flush; // lastCat = cat; } // else // std::cout << "..." << std::flush; if(showColon) { ChangeColor( FOREGROUND_BLUE | FOREGROUND_INTENSITY ); std::cout << ": " << std::flush; } else std::cout << " "; } } switch(l.level) { case mbilog::Info: break; case mbilog::Warn: ChangeColor( colorTime ); std::cout << "WARNING" << std::flush; ChangeColor( FOREGROUND_BLUE | FOREGROUND_INTENSITY ); std::cout << ": " << std::flush; break; case mbilog::Error: ChangeColor( colorTime ); std::cout << "ERROR" << std::flush; ChangeColor( FOREGROUND_BLUE | FOREGROUND_INTENSITY ); std::cout << ": " << std::flush; break; case mbilog::Fatal: ChangeColor( colorTime ); std::cout << "FATAL" << std::flush; ChangeColor( FOREGROUND_BLUE | FOREGROUND_INTENSITY ); std::cout << ": " << std::flush; break; case mbilog::Debug: ChangeColor( colorTime ); std::cout << "DBG" << std::flush; ChangeColor( FOREGROUND_BLUE | FOREGROUND_INTENSITY ); std::cout << ": " << std::flush; break; } ChangeColor( colorText ); std::cout << l.message << std::endl; ChangeColor( colorNormal ); } #endif